<commit_before>(function(angular) {
	'use strict';

	function createWidgetBlock(title, content) {
		var block = angular.element('
'
				+ '
' + title + '
'
				+ '
');
		var contentDiv = angular.element('

');
		contentDiv.append(content);
		block.append(contentDiv);
		return block;
	}

	angular.module('xpsui:directives')
	.directive('xpsuiDashboardWidgetRequests',
			['xpsui:logging', '$compile', '$translate', '$http', '$location', 'xpsui:SchemaUtil', 'xpsui:NotificationFactory',
			 'xpsui:NavigationService',
	        function(log, $compile, $translate, $http, $location, schemaUtilFactory, notificationFactory, navigationService) {
		return {
			controller: function($scope, $element, $attrs) {
			},
			link: function(scope, elm, attrs, ctrls) {
				scope.showRegistrations = function() {
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FregistrationRequests~23views~2FpeopleRegistrationApplicant~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FregistrationRequests~23views~2FpeopleRegistrationApplicant~2Fsearch');
				};

				scope.showDataChanges = function() {
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FdataChangeRequests~23views~2FdataChangeApplicant~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FdataChangeRequests~23views~2FdataChangeApplicant~2Fsearch');
				}

				scope.showTransfers = function() {
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferApplicant~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferApplicant~2Fsearch');
				}

				scope.showRegistrationsSolver = function(){
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FregistrationRequests~23views~2FpeopleRegistrationSolver~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FregistrationRequests~23views~2FpeopleRegistrationSolver~2Fsearch');
				}

				scope.showDataChangesSolver = function(){
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FdataChangeRequests~23views~2FdataChangeSolver~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FdataChangeRequests~23views~2FdataChangeSolver~2Fsearch');
				}

				scope.showTransfersSolver = function(){
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferSolver~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferSolver~2Fsearch');
				}

				scope.showTransfersSolverClubFrom = function(){
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferSolverClubFrom~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferSolverClubFrom~2Fsearch');
				}

				// Gets the number of results for a search query specified by the URI.
				var getCount = function (uri, block, onClick){
					$http({ method : 'POST',
						url: '/search/' + schemaUtilFactory.encodeUri(uri)})
					.success(function(data, status, headers, config) {
						block.empty();
						if (data) {
							block.html(
									'' + data.length + '
'
									+ ' ' + $translate.instant('generic.more') + '');
							$compile(block)(scope);
							return;
						}
						var label_noOpenRequests = $translate.instant('dashboard.widget.members.noOpenRequests');
						block.text(label_noOpenRequests);
					}).error(function(err) {
						notificationFactory.error(err);
					});
				}

				log.group('xpsui-dashboard-widget-requests Widget');

				elm.empty();

				elm.addClass('dashboard-widget-container');
				var title = $translate.instant('dashboard.widget.notifications.title');
				var titleBar = angular.element('
' + title + '
');

				var content = angular.element(
					'
'
					+ '
');
				var blocks = angular.element('

');
				content.append(blocks);

				var label_loading = $translate.instant('generic.loading');

				var contentBlock1Elm = angular.element('
' + label_loading + '
');
				var contentBlock2Elm = angular.element('
' + label_loading + '
');
				var contentBlock3Elm = angular.element('
' + label_loading + '
');
				var contentBlock4Elm = angular.element('
' + label_loading + '
');

				//If the user can solve requests, the request solver search results are used
				if (scope.hasPermissions(['Registry - read'])){
					var contentBlock1Title = $translate.instant('dashboard.widget.members.openRequests');
					var contentBlock2Title = $translate.instant('dashboard.widget.data.openRequests');
					var contentBlock3Title = $translate.instant('dashboard.widget.transfer.openRequests');

					getCount('uri://registries/registrationRequests#views/peopleRegistrationSolver/search', contentBlock1Elm, 'showRegistrationsSolver()');
					getCount('uri://registries/dataChangeRequests#views/dataChangeSolver/search', contentBlock2Elm, 'showDataChangesSolver()');
					getCount('uri://registries/transferRequests#views/transferSolver/search', contentBlock3Elm, 'showTransfersSolver()');
				}
				// If the user can only create requests, the request applicant search results are used
				else if (scope.hasPermissions(['Registry Requests'])){
					var contentBlock1Title = $translate.instant('dashboard.widget.members.openRequests');
					var contentBlock2Title = $translate.instant('dashboard.widget.data.openRequests');
					var contentBlock3Title = $translate.instant('dashboard.widget.transfer.openRequests');
					var contentBlock4Title = $translate.instant('dashboard.widget.transferSolverKM.openRequests');

					getCount('uri://registries/registrationRequests#views/peopleRegistrationApplicant/search', contentBlock1Elm, 'showRegistrations()');
					getCount('uri://registries/dataChangeRequests#views/dataChangeApplicant/search', contentBlock2Elm,'showDataChanges()');
					getCount('uri://registries/transferRequests#views/transferApplicant/search', contentBlock3Elm, 'showTransfers()');
					getCount('uri://registries/transferRequests#views/transferSolverClubFrom/search', contentBlock4Elm, 'showTransfersSolverClubFrom()');
				}

				var block1 = createWidgetBlock(contentBlock1Title, contentBlock1Elm)
				blocks.append(block1);

				var block2 = createWidgetBlock(contentBlock2Title, contentBlock2Elm)
				blocks.append(block2);

				var block3 = createWidgetBlock(contentBlock3Title, contentBlock3Elm)
				blocks.append(block3);

				var block4 = createWidgetBlock(contentBlock4Title, contentBlock4Elm)
				blocks.append(block4);

				elm.append(titleBar);
				elm.append(content);

				log.groupEnd();
			}
		};
	}]);

}(window.angular));
<commit_msg>Fixed problem with displays undefined widgets.<commit_after>(function(angular) {
	'use strict';

	function createWidgetBlock(title, content) {
		var block = angular.element('
'
				+ '
' + title + '
'
				+ '
');
		var contentDiv = angular.element('

');
		contentDiv.append(content);
		block.append(contentDiv);
		return block;
	}

	angular.module('xpsui:directives')
	.directive('xpsuiDashboardWidgetRequests',
			['xpsui:logging', '$compile', '$translate', '$http', '$location', 'xpsui:SchemaUtil', 'xpsui:NotificationFactory',
			 'xpsui:NavigationService',
	        function(log, $compile, $translate, $http, $location, schemaUtilFactory, notificationFactory, navigationService) {
		return {
			controller: function($scope, $element, $attrs) {
			},
			link: function(scope, elm, attrs, ctrls) {
				scope.showRegistrations = function() {
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FregistrationRequests~23views~2FpeopleRegistrationApplicant~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FregistrationRequests~23views~2FpeopleRegistrationApplicant~2Fsearch');
				};

				scope.showDataChanges = function() {
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FdataChangeRequests~23views~2FdataChangeApplicant~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FdataChangeRequests~23views~2FdataChangeApplicant~2Fsearch');
				}

				scope.showTransfers = function() {
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferApplicant~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferApplicant~2Fsearch');
				}

				scope.showRegistrationsSolver = function(){
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FregistrationRequests~23views~2FpeopleRegistrationSolver~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FregistrationRequests~23views~2FpeopleRegistrationSolver~2Fsearch');
				}

				scope.showDataChangesSolver = function(){
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FdataChangeRequests~23views~2FdataChangeSolver~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FdataChangeRequests~23views~2FdataChangeSolver~2Fsearch');
				}

				scope.showTransfersSolver = function(){
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferSolver~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferSolver~2Fsearch');
				}

				scope.showTransfersSolverClubFrom = function(){
					navigationService.navigateToPath(
							'/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferSolverClubFrom~2Fsearch',
							'search');
					$location.path('/registry/search/uri~3A~2F~2Fregistries~2FtransferRequests~23views~2FtransferSolverClubFrom~2Fsearch');
				}

				// Gets the number of results for a search query specified by the URI.
				var getCount = function (uri, block, onClick){
					$http({ method : 'POST',
						url: '/search/' + schemaUtilFactory.encodeUri(uri)})
					.success(function(data, status, headers, config) {
						block.empty();
						if (data) {
							block.html(
									'' + data.length + '
'
									+ ' ' + $translate.instant('generic.more') + '');
							$compile(block)(scope);
							return;
						}
						var label_noOpenRequests = $translate.instant('dashboard.widget.members.noOpenRequests');
						block.text(label_noOpenRequests);
					}).error(function(err) {
						notificationFactory.error(err);
					});
				}

				log.group('xpsui-dashboard-widget-requests Widget');

				elm.empty();

				elm.addClass('dashboard-widget-container');
				var title = $translate.instant('dashboard.widget.notifications.title');
				var titleBar = angular.element('
' + title + '
');

				var content = angular.element(
					'
'
					+ '
');
				var blocks = angular.element('

');
				content.append(blocks);

				var label_loading = $translate.instant('generic.loading');

				//If the user can solve requests, the request solver search results are used
				if (scope.hasPermissions(['Registry - read'])){
					var contentBlock1Elm = angular.element('
' + label_loading + '
');
					var contentBlock2Elm = angular.element('
' + label_loading + '
');
					var contentBlock3Elm = angular.element('
' + label_loading + '
');

					var contentBlock1Title = $translate.instant('dashboard.widget.members.openRequests');
					var contentBlock2Title = $translate.instant('dashboard.widget.data.openRequests');
					var contentBlock3Title = $translate.instant('dashboard.widget.transfer.openRequests');

					getCount('uri://registries/registrationRequests#views/peopleRegistrationSolver/search', contentBlock1Elm, 'showRegistrationsSolver()');
					getCount('uri://registries/dataChangeRequests#views/dataChangeSolver/search', contentBlock2Elm, 'showDataChangesSolver()');
					getCount('uri://registries/transferRequests#views/transferSolver/search', contentBlock3Elm, 'showTransfersSolver()');

					var block1 = createWidgetBlock(contentBlock1Title, contentBlock1Elm)
					blocks.append(block1);

					var block2 = createWidgetBlock(contentBlock2Title, contentBlock2Elm)
					blocks.append(block2);

					var block3 = createWidgetBlock(contentBlock3Title, contentBlock3Elm)
					blocks.append(block3);
				}
				// If the user can only create requests, the request applicant search results are used
				else if (scope.hasPermissions(['Registry Requests'])){
					var contentBlock1Elm = angular.element('
' + label_loading + '
');
					var contentBlock2Elm = angular.element('
' + label_loading + '
');
					var contentBlock3Elm = angular.element('
' + label_loading + '
');
					var contentBlock4Elm = angular.element('
' + label_loading + '
');

					var contentBlock1Title = $translate.instant('dashboard.widget.members.openRequests');
					var contentBlock2Title = $translate.instant('dashboard.widget.data.openRequests');
					var contentBlock3Title = $translate.instant('dashboard.widget.transfer.openRequests');
					var contentBlock4Title = $translate.instant('dashboard.widget.transferSolverKM.openRequests');

					getCount('uri://registries/registrationRequests#views/peopleRegistrationApplicant/search', contentBlock1Elm, 'showRegistrations()');
					getCount('uri://registries/dataChangeRequests#views/dataChangeApplicant/search', contentBlock2Elm,'showDataChanges()');
					getCount('uri://registries/transferRequests#views/transferApplicant/search', contentBlock3Elm, 'showTransfers()');
					getCount('uri://registries/transferRequests#views/transferSolverClubFrom/search', contentBlock4Elm, 'showTransfersSolverClubFrom()');

					var block1 = createWidgetBlock(contentBlock1Title, contentBlock1Elm)
					blocks.append(block1);

					var block2 = createWidgetBlock(contentBlock2Title, contentBlock2Elm)
					blocks.append(block2);

					var block3 = createWidgetBlock(contentBlock3Title, contentBlock3Elm)
					blocks.append(block3);

					var block4 = createWidgetBlock(contentBlock4Title, contentBlock4Elm)
					blocks.append(block4);
				}

				elm.append(titleBar);
				elm.append(content);

				log.groupEnd();
			}
		};
	}]);

}(window.angular));
<|endoftext|>


<commit_before>function atInputSecretLink (scope, element, attrs, controllers) {
    let formController = controllers[0];
    let inputController = controllers[1];

    if (scope.tab === '1') {
        element.find('input')[0].focus();
    }

    inputController.init(scope, element, formController);
}

function AtInputSecretController (baseInputController) {
    let vm = this || {};

    let scope;

    vm.init = (_scope_, element, form) => {
        baseInputController.call(vm, 'input', _scope_, element, form);

        scope = _scope_;

        if (!scope.state._value || scope.state._promptOnLaunch) {
            scope.mode = 'input';
            scope.state._buttonText = vm.strings.get('SHOW');
            scope.type = 'password';

            vm.toggle = vm.toggleShowHide;
        } else {
            scope.mode = 'encrypted';
            scope.state._buttonText = vm.strings.get('REPLACE');
            scope.state._placeholder = vm.strings.get('ENCRYPTED');
            vm.toggle = vm.toggleRevertReplace;
        }

        vm.check();
    };

    vm.toggleShowHide = () => {
        if (scope.type === 'password') {
            scope.type = 'text';
            scope.state._buttonText = vm.strings.get('HIDE');
        } else {
            scope.type = 'password';
            scope.state._buttonText = vm.strings.get('SHOW');
        }
    };
}

AtInputSecretController.$inject = ['BaseInputController'];

function atInputSecret (pathService) {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        require: ['^^atForm', 'atInputSecret'],
        templateUrl: pathService.getPartialPath('components/input/secret'),
        controller: AtInputSecretController,
        controllerAs: 'vm',
        link: atInputSecretLink,
        scope: {
            state: '=',
            col: '@',
            tab: '@'
        }
    };
}

atInputSecret.$inject = ['PathService'];

export default atInputSecret;
<commit_msg>Change secret input edit mode to display as hiddden<commit_after>function atInputSecretLink (scope, element, attrs, controllers) {
    let formController = controllers[0];
    let inputController = controllers[1];

    if (scope.tab === '1') {
        element.find('input')[0].focus();
    }

    inputController.init(scope, element, formController);
}

function AtInputSecretController (baseInputController) {
    let vm = this || {};

    let scope;

    vm.init = (_scope_, element, form) => {
        baseInputController.call(vm, 'input', _scope_, element, form);

        scope = _scope_;
        scope.type = 'password';

        if (!scope.state._value || scope.state._promptOnLaunch) {
            scope.mode = 'input';
            scope.state._buttonText = vm.strings.get('SHOW');

            vm.toggle = vm.toggleShowHide;
        } else {
            scope.mode = 'encrypted';
            scope.state._buttonText = vm.strings.get('REPLACE');
            scope.state._placeholder = vm.strings.get('ENCRYPTED');
            vm.toggle = vm.toggleRevertReplace;
        }

        vm.check();
    };

    vm.toggleShowHide = () => {
        if (scope.type === 'password') {
            scope.type = 'text';
            scope.state._buttonText = vm.strings.get('HIDE');
        } else {
            scope.type = 'password';
            scope.state._buttonText = vm.strings.get('SHOW');
        }
    };
}

AtInputSecretController.$inject = ['BaseInputController'];

function atInputSecret (pathService) {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        require: ['^^atForm', 'atInputSecret'],
        templateUrl: pathService.getPartialPath('components/input/secret'),
        controller: AtInputSecretController,
        controllerAs: 'vm',
        link: atInputSecretLink,
        scope: {
            state: '=',
            col: '@',
            tab: '@'
        }
    };
}

atInputSecret.$inject = ['PathService'];

export default atInputSecret;
<|endoftext|>


<commit_before>var utils = require('../utils'),
    evt = require('./event');

var gesture = module.exports = {
    draggable: null,
    position: null,
    cursor: null
};

var handlers = {};

// add single drag set of drag events for an element
// regardless of the number of listeners
var addDraggestures = {
    setup: function(el) {
        if (el.__draggesturebound) {
            el.__draggesturebound++;
        } else {
            el.__draggesturebound = 1;
            evt.addListener(el, 'mousedown', dragGestureStart);
        }
    },
    teardown: function(el) {
        el.__draggesturebound--;
        if (!el.__draggesturebound) evt.removeListener(el, 'mousedown', dragGestureStart);
    }
};

// drag gestures
utils.extend(evt.special, {
    draggesturestart: addDraggestures,
    draggestureend: addDraggestures,
    draggesture: addDraggestures
});

function startGesture (el, e) {
    if (gesture.draggable) return;
    gesture.draggable = e.draggable || el;
    if (e.cursor) {
        gesture.cursor = uki.doc.body.style.cursor;
        uki.doc.body.style.cursor = e.cursor;
    }
    evt.addListener(uki.doc, 'mousemove scroll', dragGesture);
    evt.addListener(uki.doc, 'mouseup dragend', dragGestureEnd);
    evt.addListener(uki.doc, 'selectstart mousedown', evt.preventDefaultHandler);
}

function stopGesture () {
    gesture.draggable = null;
    uki.doc.body.style.cursor = gesture.cursor;
    gesture.cursor = null;
    evt.removeListener(uki.doc, 'mousemove scroll', dragGesture);
    evt.removeListener(uki.doc, 'mouseup dragend', dragGestureEnd);
    evt.removeListener(uki.doc, 'selectstart mousedown', evt.preventDefaultHandler);
}

function dragGestureStart (e) {
    e = evt.createEvent(e, {type:'draggesturestart'});
    evt.trigger.call(this, e);
    if (!e.isDefaultPrevented()) {
        gesture.position = { x: e.pageX, y: e.pageY };
        startGesture(this, e);
    }
}

function dragGesture (e) {
    e = evt.createEvent(e, {type:'draggesture'});
    e.dragOffset = {
        x: e.pageX - gesture.position.x,
        y: e.pageY - gesture.position.y
    };
    evt.trigger.call(gesture.draggable, e);

    if (e.isDefaultPrevented()) stopGesture(gesture.draggable);
}

function dragGestureEnd (e) {
    e = evt.createEvent(e, {type:'draggestureend'});
    e.dragOffset = {
        x: e.pageX - gesture.position.x,
        y: e.pageY - gesture.position.y
    };
    evt.trigger.call(gesture.draggable, e);

    stopGesture(gesture.draggable);
}

utils.extend(require('../dom'), gesture);
<commit_msg>transition fixes<commit_after>var utils = require('../utils'),
    uki = require('../uki'),
    evt = require('./event');

var gesture = module.exports = {
    draggable: null,
    position: null,
    cursor: null
};

var handlers = {};

// add single drag set of drag events for an element
// regardless of the number of listeners
var addDraggestures = {
    setup: function(el) {
        if (el.__draggesturebound) {
            el.__draggesturebound++;
        } else {
            el.__draggesturebound = 1;
            evt.addListener(el, 'mousedown', dragGestureStart);
        }
    },
    teardown: function(el) {
        el.__draggesturebound--;
        if (!el.__draggesturebound) evt.removeListener(el, 'mousedown', dragGestureStart);
    }
};

// drag gestures
utils.extend(evt.special, {
    draggesturestart: addDraggestures,
    draggestureend: addDraggestures,
    draggesture: addDraggestures
});

function startGesture (el, e) {
    if (gesture.draggable) return;
    gesture.draggable = e.draggable || el;
    if (e.cursor) {
        gesture.cursor = uki.doc.body.style.cursor;
        uki.doc.body.style.cursor = e.cursor;
    }
    evt.on(uki.doc, 'mousemove scroll', dragGesture);
    evt.on(uki.doc, 'mouseup dragend', dragGestureEnd);
    evt.on(uki.doc, 'selectstart mousedown', evt.preventDefaultHandler);
}

function stopGesture () {
    gesture.draggable = null;
    uki.doc.body.style.cursor = gesture.cursor;
    gesture.cursor = null;
    evt.removeListener(uki.doc, 'mousemove scroll', dragGesture);
    evt.removeListener(uki.doc, 'mouseup dragend', dragGestureEnd);
    evt.removeListener(uki.doc, 'selectstart mousedown', evt.preventDefaultHandler);
}

function dragGestureStart (e) {
    e = evt.createEvent(e, {type:'draggesturestart'});
    evt.trigger.call(this, e);
    if (!e.isDefaultPrevented()) {
        gesture.position = { x: e.pageX, y: e.pageY };
        startGesture(this, e);
    }
}

function dragGesture (e) {
    e = evt.createEvent(e, {type:'draggesture'});
    e.dragOffset = {
        x: e.pageX - gesture.position.x,
        y: e.pageY - gesture.position.y
    };
    evt.trigger.call(gesture.draggable, e);

    if (e.isDefaultPrevented()) stopGesture(gesture.draggable);
}

function dragGestureEnd (e) {
    e = evt.createEvent(e, {type:'draggestureend'});
    e.dragOffset = {
        x: e.pageX - gesture.position.x,
        y: e.pageY - gesture.position.y
    };
    evt.trigger.call(gesture.draggable, e);

    stopGesture(gesture.draggable);
}

utils.extend(require('../dom'), gesture);
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import Modal from '@material-ui/core/Modal';
import DialogContent from '@material-ui/core/DialogContent';
import messages from '../../../resources/messages';
import PickedMediaContainer from './PickedMediaContainer';
import MediaPickerResultsContainer from './MediaPickerResultsContainer';
import { fetchMediaPickerFeaturedCollections, initializePreviouslySelectedMedia, clearSelectedMedia } from '../../../actions/systemActions';
import AppButton from '../AppButton';
import { PICK_FEATURED } from '../../../lib/explorerUtil';
import { TAG_SET_MC_ID } from '../../../lib/tagUtil';
import { ALL_MEDIA } from '../../../lib/mediaUtil';

const localMessages = {
  title: { id: 'system.mediaPicker.select.title', defaultMessage: 'title' },
  intro: { id: 'system.mediaPicker.select.info',
    defaultMessage: '
This is an intro
' },
  helpTitle: { id: 'system.mediaPicker.select.help.title', defaultMessage: 'About Media' },
  selectMediaTitle: { id: 'system.mediaPicker.selectMediaTitle', defaultMessage: 'Select Media' },
  searchByName: { id: 'system.mediaPicker.select.searchby.name', defaultMessage: 'Search by Name/URL' },
  addMedia: { id: 'system.mediaPicker.select.addMedia', defaultMessage: 'Change/add media sources and collections' },
};

class MediaPickerDialog extends React.Component {
  state = {
    open: false,
  };

  componentWillMount() { // only called on intial parent load -eg not when dialog pops up
    if (this.state.open) {
      window.scrollTo(0, 0);
    }
  }

  componentWillReceiveProps(nextProps) {
    // select the media so we fill the reducer with the previously selected media
    const { initMedia, handleInitialSelectionOfMedia } = this.props;
    if (JSON.stringify(initMedia) !== JSON.stringify(nextProps.initMedia)) {
      if (nextProps.initMedia) { // expects an array of media from caller
        handleInitialSelectionOfMedia(nextProps.initMedia);
      }
    }
  }

  componentWillUnmount() {
    const { reset } = this.props;
    reset();
  }

  handleModifyClick = (initMedia) => {
    const { setQueryFormChildDialogOpen, handleInitialSelectionOfMedia } = this.props;
    this.setState({ open: true });
    handleInitialSelectionOfMedia(initMedia); // push into selectedMedia in store

    // document.body.style.overflow = 'hidden';
    if (setQueryFormChildDialogOpen) { // way to tell parent that a dialog is open - focus issue stuff
      setQueryFormChildDialogOpen(true);
    }
    // need to set body to overflow: hidden somehow...
  };

  handleRemoveDialogClose = (confirm) => {
    const { onConfirmSelection, selectedMedia, setQueryFormChildDialogOpen, reset } = this.props;
    this.setState({ open: false });
    if (confirm) {
      const allTest = selectedMedia.filter(m => m.id === ALL_MEDIA);
      if (allTest.length > 0) {
        onConfirmSelection(allTest); // if selected, this takes precedence
      } else {
        onConfirmSelection(selectedMedia); // passed in from containing element
      }
    }
    reset();
    if (setQueryFormChildDialogOpen) {
      setQueryFormChildDialogOpen(false);
    }
  };

  render() {
    const { initMedia, selectedMedia, handleSelection, lookupTimestamp } = this.props;
    const { formatMessage } = this.props.intl;
    let modalContent = null;
    if (this.state.open) {
      modalContent = (

          <Modal
            title={formatMessage(localMessages.selectMediaTitle)}
            open={this.state.open}
            onClose={() => this.handleRemoveDialogClose(false)}
          >
            <DialogContent className="select-media-dialog-wrapper">

                  <PickedMediaContainer selectedMedia={selectedMedia} />
                  <AppButton
                    className="select-media-ok-button"
                    label={formatMessage(messages.ok)}
                    onTouchTap={() => this.handleRemoveDialogClose(true)}
                    type="submit"
                    primary
                  />

                  <MediaPickerResultsContainer timestamp={lookupTimestamp} selectedMediaQueryType={PICK_FEATURED} selectedMedia={selectedMedia} handleSelection={handleSelection} />

            </DialogContent>
          </Modal>

      );
    }

    return (

        <AppButton
          onClick={() => this.handleModifyClick(initMedia)}
          tooltip={formatMessage(localMessages.addMedia)}
          label="Add Media"
        />
        {modalContent}

    );
  }
}

MediaPickerDialog.propTypes = {
  // from context
  intl: PropTypes.object.isRequired,
  // from parent/implementer
  initMedia: PropTypes.array,
  selectedMedia: PropTypes.array,
  lookupTimestamp: PropTypes.string,
  handleSelection: PropTypes.func.isRequired,
  handleInitialSelectionOfMedia: PropTypes.func.isRequired,
  onConfirmSelection: PropTypes.func.isRequired,
  reset: PropTypes.func.isRequired,
  setQueryFormChildDialogOpen: PropTypes.func,
};

const mapStateToProps = state => ({
  fetchStatus: state.system.mediaPicker.selectMedia.fetchStatus,
  selectedMedia: state.system.mediaPicker.selectMedia.list, // initially empty
  lookupTimestamp: state.system.mediaPicker.featured.timestamp, // or maybe any of them? trying to get to receive new props when fetch succeeds
});

const mapDispatchToProps = dispatch => ({
  handleSelection: (values) => {
    if (values) {
      dispatch(fetchMediaPickerFeaturedCollections(TAG_SET_MC_ID));
    }
  },
  reset: () => {
    dispatch(clearSelectedMedia());
  },
  handleInitialSelectionOfMedia: (prevSelectedMedia) => {
    if (prevSelectedMedia) {
      dispatch(initializePreviouslySelectedMedia(prevSelectedMedia)); // disable button too
    }
  },
});

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(
    MediaPickerDialog
  )
);
<commit_msg>#1258<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import Modal from '@material-ui/core/Modal';
import DialogContent from '@material-ui/core/DialogContent';
import messages from '../../../resources/messages';
import PickedMediaContainer from './PickedMediaContainer';
import MediaPickerResultsContainer from './MediaPickerResultsContainer';
import { fetchMediaPickerFeaturedCollections, initializePreviouslySelectedMedia, clearSelectedMedia } from '../../../actions/systemActions';
import AppButton from '../AppButton';
import { PICK_FEATURED } from '../../../lib/explorerUtil';
import { TAG_SET_MC_ID } from '../../../lib/tagUtil';
import { ALL_MEDIA } from '../../../lib/mediaUtil';

const localMessages = {
  title: { id: 'system.mediaPicker.select.title', defaultMessage: 'title' },
  intro: { id: 'system.mediaPicker.select.info',
    defaultMessage: '
This is an intro
' },
  helpTitle: { id: 'system.mediaPicker.select.help.title', defaultMessage: 'About Media' },
  selectMediaTitle: { id: 'system.mediaPicker.selectMediaTitle', defaultMessage: 'Select Media' },
  searchByName: { id: 'system.mediaPicker.select.searchby.name', defaultMessage: 'Search by Name/URL' },
  addMedia: { id: 'system.mediaPicker.select.addMedia', defaultMessage: 'Change/add media sources and collections' },
};

class MediaPickerDialog extends React.Component {
  state = {
    open: false,
  };

  componentWillMount() { // only called on intial parent load -eg not when dialog pops up
    if (this.state.open) {
      window.scrollTo(0, 0);
    }
  }

  componentWillReceiveProps(nextProps) {
    // select the media so we fill the reducer with the previously selected media
    const { initMedia, handleInitialSelectionOfMedia } = this.props;
    if (JSON.stringify(initMedia) !== JSON.stringify(nextProps.initMedia)) {
      if (nextProps.initMedia) { // expects an array of media from caller
        handleInitialSelectionOfMedia(nextProps.initMedia);
      }
    }
  }

  componentWillUnmount() {
    const { reset } = this.props;
    reset();
  }

  handleModifyClick = (initMedia) => {
    const { setQueryFormChildDialogOpen, handleInitialSelectionOfMedia } = this.props;
    this.setState({ open: true });
    handleInitialSelectionOfMedia(initMedia); // push into selectedMedia in store

    // document.body.style.overflow = 'hidden';
    if (setQueryFormChildDialogOpen) { // way to tell parent that a dialog is open - focus issue stuff
      setQueryFormChildDialogOpen(true);
    }
    // need to set body to overflow: hidden somehow...
  };

  handleRemoveDialogClose = (confirm) => {
    const { onConfirmSelection, selectedMedia, setQueryFormChildDialogOpen, reset } = this.props;
    this.setState({ open: false });
    if (confirm) {
      const allTest = selectedMedia.filter(m => m.id === ALL_MEDIA);
      if (allTest.length > 0) {
        onConfirmSelection(allTest); // if selected, this takes precedence
      } else {
        onConfirmSelection(selectedMedia); // passed in from containing element
      }
    }
    reset();
    if (setQueryFormChildDialogOpen) {
      setQueryFormChildDialogOpen(false);
    }
  };

  render() {
    const { initMedia, selectedMedia, handleSelection, lookupTimestamp } = this.props;
    const { formatMessage } = this.props.intl;
    let modalContent = null;
    if (this.state.open) {
      modalContent = (

          <Modal
            title={formatMessage(localMessages.selectMediaTitle)}
            open={this.state.open}
            onClose={() => this.handleRemoveDialogClose(false)}
          >
            <DialogContent className="select-media-dialog-wrapper">

                  <PickedMediaContainer selectedMedia={selectedMedia} />
                  <AppButton
                    className="select-media-ok-button"
                    label={formatMessage(messages.ok)}
                    onTouchTap={() => this.handleRemoveDialogClose(true)}
                    type="submit"
                    primary
                  />
                <AppButton
                    className="select-media-cancel-button"
                    label={formatMessage(messages.cancel)}
                    onTouchTap={() => this.handleRemoveDialogClose(false)}
                    type="submit"
                  />

                  <MediaPickerResultsContainer timestamp={lookupTimestamp} selectedMediaQueryType={PICK_FEATURED} selectedMedia={selectedMedia} handleSelection={handleSelection} />

            </DialogContent>
          </Modal>

      );
    }

    return (

        <AppButton
          onClick={() => this.handleModifyClick(initMedia)}
          tooltip={formatMessage(localMessages.addMedia)}
          label="Add Media"
        />
        {modalContent}

    );
  }
}

MediaPickerDialog.propTypes = {
  // from context
  intl: PropTypes.object.isRequired,
  // from parent/implementer
  initMedia: PropTypes.array,
  selectedMedia: PropTypes.array,
  lookupTimestamp: PropTypes.string,
  handleSelection: PropTypes.func.isRequired,
  handleInitialSelectionOfMedia: PropTypes.func.isRequired,
  onConfirmSelection: PropTypes.func.isRequired,
  reset: PropTypes.func.isRequired,
  setQueryFormChildDialogOpen: PropTypes.func,
};

const mapStateToProps = state => ({
  fetchStatus: state.system.mediaPicker.selectMedia.fetchStatus,
  selectedMedia: state.system.mediaPicker.selectMedia.list, // initially empty
  lookupTimestamp: state.system.mediaPicker.featured.timestamp, // or maybe any of them? trying to get to receive new props when fetch succeeds
});

const mapDispatchToProps = dispatch => ({
  handleSelection: (values) => {
    if (values) {
      dispatch(fetchMediaPickerFeaturedCollections(TAG_SET_MC_ID));
    }
  },
  reset: () => {
    dispatch(clearSelectedMedia());
  },
  handleInitialSelectionOfMedia: (prevSelectedMedia) => {
    if (prevSelectedMedia) {
      dispatch(initializePreviouslySelectedMedia(prevSelectedMedia)); // disable button too
    }
  },
});

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(
    MediaPickerDialog
  )
);
<|endoftext|>


<commit_before>var config = require("./config.js");
var utility = require("./utility.js");
var request = require('request');
var WebSocket = require('ws');

var slack = module.exports = {};

// connect to slack real time messaging
slack.connect = function(onconnect, onmessage) {
	request(encodeURI('https://slack.com/api/rtm.start?token=' + config.slackToken), function(error, response, body) {
		utility.log("connecting to slack");

		if (!error && response.statusCode === 200) {
			slack.data = JSON.parse(body);
			slack.users = toAssoc('id', slack.data.users);
			slack.channels = toAssoc('id', slack.data.channels.concat(slack.data.groups, slack.data.ims));

			slack.socket = new WebSocket(slack.data.url);

			slack.socket.onopen = function() {
				utility.log('connected to slack');
				onconnect();
			};

			slack.socket.onmessage = onmessage;

			slack.socket.onclose = function() {
				utility.log("slack socket closed");
				process.exit();
			};

			slack.socket.onerror = function(error) {
				utility.log("slack socket error: " + JSON.stringify(error));
				process.exit();
			};
		}
		else {
			utility.log("unable to connect to slack");
			process.exit();
		}
	});
}

// post reply
slack.post = function post(reply, context, callback){
	if (!context) return utility.log('Post called without context');

	slack.socket.send(JSON.stringify({
		type: 'message',
		channel: context.channel,
		thread_ts: context.thread_ts || context.ts,
		text: String(reply) || "[no reply]"
	}));

	var channel = slack.channels[context.channel];
	utility.log("(in " + (channel.name || "<private message>")  + ")\n" +
		context.user.real_name + ": " + context.text + "\n" +
		config.botName + ": " + reply);
	if (callback) callback();
}

// find id of user based on a provided string
slack.findUser = function(userString) {
	var user = slack.data.users.find(function(user) {
		return  userString == user.name ||
				userString == user.real_name ||
				userString == user.profile.real_name ||
				userString == user.profile.email;
	});
	return user === undefined ? undefined : user.id;
}

slack.decodeControlChars = function(s) {
	return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}

// generate associative array from array of objects
function toAssoc(keyName, arr) {
	var result = {};
	for (var i = 0; i < arr.length; i++) {
		var item = arr[i];
		result[item[keyName]] = item;
	}
	return result;
}
<commit_msg>enable posting to channel directly (rather than responding to message)<commit_after>var config = require("./config.js");
var utility = require("./utility.js");
var request = require('request');
var WebSocket = require('ws');

var slack = module.exports = {};

// connect to slack real time messaging
slack.connect = function(onconnect, onmessage) {
	request(encodeURI('https://slack.com/api/rtm.start?token=' + config.slackToken), function(error, response, body) {
		utility.log("connecting to slack");

		if (!error && response.statusCode === 200) {
			slack.data = JSON.parse(body);
			slack.users = toAssoc('id', slack.data.users);
			slack.channels = toAssoc('id', slack.data.channels.concat(slack.data.groups, slack.data.ims));

			slack.socket = new WebSocket(slack.data.url);

			slack.socket.onopen = function() {
				utility.log('connected to slack');
				onconnect();
			};

			slack.socket.onmessage = onmessage;

			slack.socket.onclose = function() {
				utility.log("slack socket closed");
				process.exit();
			};

			slack.socket.onerror = function(error) {
				utility.log("slack socket error: " + JSON.stringify(error));
				process.exit();
			};
		}
		else {
			utility.log("unable to connect to slack");
			process.exit();
		}
	});
}

// post reply
slack.post = function post(reply, context, callback){
	if (!context) return utility.log('Post called without context');
	if (typeof(context) === 'string') context = { channel: context };

	slack.socket.send(JSON.stringify({
		type: 'message',
		channel: context.channel,
		thread_ts: context.thread_ts || context.ts,
		text: String(reply) || "[no reply]"
	}));

	var channel = slack.channels[context.channel];
	utility.log("(in " + (channel.name || "<private message>")  + ")\n" +
		(context.user ? (context.user.real_name + ": " + context.text + "\n") : "") +
		config.botName + ": " + reply);
	if (callback) callback();
}

// find id of user based on a provided string
slack.findUser = function(userString) {
	var user = slack.data.users.find(function(user) {
		return  userString == user.name ||
				userString == user.real_name ||
				userString == user.profile.real_name ||
				userString == user.profile.email;
	});
	return user === undefined ? undefined : user.id;
}

slack.decodeControlChars = function(s) {
	return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}

// generate associative array from array of objects
function toAssoc(keyName, arr) {
	var result = {};
	for (var i = 0; i < arr.length; i++) {
		var item = arr[i];
		result[item[keyName]] = item;
	}
	return result;
}
<|endoftext|>


<commit_before>module.exports = function (data, process) {

    function checkForFailures(err) {
        if (err) {
            process.fail('Could not send POST request: ' + err);
        }
    }

    var branchToProtect = data.parameters.branch || 'master',
        preventInfiniteLoop = 'githook-super-protected-branches protected you!';

    if ( data.payload.ref !== ('refs/heads/' + branchToProtect) ) {
        process.succeed('the commit was to ' + data.payload.ref + ' and thus was not a problem');
    }
    else if (data.payload.head_commit.message === preventInfiniteLoop ) {
        process.succeed('This was an automated commit made by super-protected-branches, so processing was skipped');
    }
    else {
        // STEP 1 - branch off.
        var newBranchName = branchToProtect + "--super-protected--" + Date.now(),
            options = {
                url: data.payload.repository.git_refs_url.replace('{/sha}', ''),
                headers: {
                    'Content-Type':  'application/json',
                    'User-Agent':    'super-protected-branches',
                    'Authorization': 'token ' + data.access_token
                },
                json: {
                    "ref": "refs/heads/" + newBranchName,
                    "sha": data.payload.after
                }
            };

        request.post(options, function newBranchCreated(err, httpResponse, body) {
            checkForFailures(err);

            // STEP 2 - create new temporary 'master' branch
            var tmpBranch = branchToProtect + "--tmp--" + Date.now();

            options.url = data.payload.repository.git_refs_url.replace('{/sha}', ''),
            options.json = {
                "ref": "refs/heads/" + tmpBranch,
                "sha": data.payload.before
            }
            request.post(options, function newBranchCreated(err, httpResponse, body) {
                checkForFailures(err);

                // STEP 3 - revert the pushed commit on the temporary 'master' branch
                options.url = data.payload.repository.git_refs_url.replace('{/sha}', '/heads/' + tmpBranch),
                options.json = {
                    "force": true,
                    "sha": data.payload.before
                };
                request.patch(options, function forceRollback(err, httpResponse, body) {
                    checkForFailures(err);

                    // STEP 4 - add a new commit message `preventInfiniteLoop` to the `tmpBranch`.
                    // This must be tackled in several steps.

                    // STEP 4.1 - get tree structure of the tmpBranch
                    options.url = data.payload.repository.trees_url.replace('{/sha}', '/' + data.payload.before);
                    options.json = {};
                    request.get(options, function getTreeStructure(err, httpResponse, body) {
                        checkForFailures(err);

                        // STEP 4.2 - post a new tree object, getting a tree SHA back
                        options.url = data.payload.repository.trees_url.replace('{/sha}', '');
                        options.json = {
                            "base_tree": data.payload.before,
                            "tree":      body.tree
                        };
                        request.post(options, function newTreeCreated(err, httpResponse, body) {
                            checkForFailures(err);

                            // STEP 4.3 - create a new commit object with the current commit SHA as the parent and the new tree SHA, getting a commit SHA back
                            options.url = data.payload.repository.git_commits_url.replace('{/sha}', '');
                            options.json = {
                                "tree":    body.sha,
                                "message": preventInfiniteLoop,
                                "parents": [data.payload.before]
                            };
                            request.post(options, function treeAssociatedWithCommit(err, httpResponse, body) {
                                checkForFailures(err);

                                // STEP 5 - point the `branchToProtect` head to the latest commit to `body.sha`
                                // (which contains the 'githook-super-protected-branches saved you!' commit message)
                                options.url = data.payload.repository.git_refs_url.replace('{/sha}', '/heads/' + branchToProtect);
                                options.json = {
                                    "sha": body.sha,
                                    "force": true
                                };

                                request.patch(options, function protectedBranchReverted(err, httpResponse, body) {
                                    checkForFailures(err);

                                    // STEP 6 - open a PR with `newBranchName`
                                    options.url = data.payload.repository.pulls_url.replace('{/number}', '');
                                    options.json = {
                                        title: data.payload.head_commit.message,
                                        body:  'This pull request was automatically generated by the [Super Protected Branches GitHook](http://githooks.io/githooks/GitHooksIO/githook-super-protected-branches) when ' + data.payload.head_commit.author.username + ' tried to push directly to ' + branchToProtect + '.',
                                        head:  newBranchName,
                                        base:  branchToProtect
                                    };
                                    request.post(options, function pullRequestOpened(err, httpResponse, body) {
                                        checkForFailures(err);

                                        process.succeed('Result*** body: ' + JSON.stringify(body) + ' \n options: ' + JSON.stringify(options.json));
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    }
}
<commit_msg>improved comments<commit_after>module.exports = function (data, process) {

    function checkForFailures(err) {
        if (err) {
            process.fail('Could not send POST request: ' + err);
        }
    }

    var branchToProtect = data.parameters.branch || 'master',
        preventInfiniteLoop = 'githook-super-protected-branches protected you!';

    if ( data.payload.ref !== ('refs/heads/' + branchToProtect) ) {
        process.succeed('the commit was to ' + data.payload.ref + ' and thus was not a problem');
    }
    else if (data.payload.head_commit.message === preventInfiniteLoop ) {
        process.succeed('This was an automated commit made by super-protected-branches, so processing was skipped');
    }
    else {
        // STEP 1 - create a new branch off branchToProtect - this will be used to open the Pull Request later
        var newBranchName = branchToProtect + "--super-protected--" + Date.now(),
            options = {
                url: data.payload.repository.git_refs_url.replace('{/sha}', ''),
                headers: {
                    'Content-Type':  'application/json',
                    'User-Agent':    'super-protected-branches',
                    'Authorization': 'token ' + data.access_token
                },
                json: {
                    "ref": "refs/heads/" + newBranchName,
                    "sha": data.payload.after
                }
            };

        request.post(options, function newBranchCreated(err, httpResponse, body) {
            checkForFailures(err);

            // STEP 2 - create new temporary branch off branchToProtect - we will do our commit manipulation here
            // and eventually replace branchToProtect with this temporary branch.
            var tmpBranch = branchToProtect + "--tmp--" + Date.now();

            options.url = data.payload.repository.git_refs_url.replace('{/sha}', ''),
            options.json = {
                "ref": "refs/heads/" + tmpBranch,
                "sha": data.payload.before
            }
            request.post(options, function newBranchCreated(err, httpResponse, body) {
                checkForFailures(err);

                // STEP 3 - revert the directly pushed commit on our temporary branch
                // The reason we cannot do this directly on branchToProtect is that it would cause an
                // infinite loop in our GitHook!
                options.url = data.payload.repository.git_refs_url.replace('{/sha}', '/heads/' + tmpBranch),
                options.json = {
                    "force": true,
                    "sha": data.payload.before
                };
                request.patch(options, function forceRollback(err, httpResponse, body) {
                    checkForFailures(err);

                    // STEP 4 - add a new commit message `preventInfiniteLoop` to the `tmpBranch`.
                    // We have to apply the preventInfiniteLoop commit message to prevent an infinite
                    // loop (otherwise thie GitHook would be called again and would run all the revert
                    // code again).
                    // Adding a new commit message must be tackled in several steps.

                    // STEP 4.1 - get tree structure of the tmpBranch
                    options.url = data.payload.repository.trees_url.replace('{/sha}', '/' + data.payload.before);
                    options.json = {};
                    request.get(options, function getTreeStructure(err, httpResponse, body) {
                        checkForFailures(err);

                        // STEP 4.2 - post a new tree object, getting a tree SHA back
                        options.url = data.payload.repository.trees_url.replace('{/sha}', '');
                        options.json = {
                            "base_tree": data.payload.before,
                            "tree":      body.tree
                        };
                        request.post(options, function newTreeCreated(err, httpResponse, body) {
                            checkForFailures(err);

                            var treeSHA = body.sha;

                            // STEP 4.3 - create a new commit object with the current commit SHA as the parent and the new tree SHA, getting a commit SHA back
                            options.url = data.payload.repository.git_commits_url.replace('{/sha}', '');
                            options.json = {
                                "tree":    treeSHA,
                                "message": preventInfiniteLoop,
                                "parents": [data.payload.before]
                            };
                            request.post(options, function treeAssociatedWithCommit(err, httpResponse, body) {
                                checkForFailures(err);

                                var commitSHA = body.sha;

                                // STEP 5 - point the `branchToProtect` head to the latest commit to `body.sha`
                                // (which contains the 'githook-super-protected-branches saved you!' commit message)
                                options.url = data.payload.repository.git_refs_url.replace('{/sha}', '/heads/' + branchToProtect);
                                options.json = {
                                    "sha": commitSHA,
                                    "force": true
                                };
                                request.patch(options, function protectedBranchReverted(err, httpResponse, body) {
                                    checkForFailures(err);

                                    // STEP 6 - open a PR with `newBranchName`
                                    options.url = data.payload.repository.pulls_url.replace('{/number}', '');
                                    options.json = {
                                        title: data.payload.head_commit.message,
                                        body:  'This pull request was automatically generated by the [Super Protected Branches GitHook](http://githooks.io/githooks/GitHooksIO/githook-super-protected-branches) when ' + data.payload.head_commit.author.username + ' tried to push directly to ' + branchToProtect + '.',
                                        head:  newBranchName,
                                        base:  branchToProtect
                                    };
                                    request.post(options, function pullRequestOpened(err, httpResponse, body) {
                                        checkForFailures(err);

                                        process.succeed('Result*** body: ' + JSON.stringify(body) + ' \n options: ' + JSON.stringify(options.json));

                                        // @TODO - STEP 7 - clean up by destroying the tmp branch
                                        // @TODO - make sure this works for multiple local commits all pushed at once (I think only the latest commit would be reverted at the moment).
                                        // @TODO - make sure this works for repositories which have a lot of commit history (when we create a new tree SHA in step 4.2, we want to make sure we don't lose the earliest commits)
                                        // @TODO - make it clear that developers could still potentially bypass this protection if they make a commit with the same message as `preventInfiniteLoop`, so this GitHook isn't absolutely water tight.
                                        // @TODO - ideally, we want to prevent devs from being able to branch locally, merge with branchToProtect locally, and push that up. We want all merges with branchToProtect to happen via Pull Requests.
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    }
}
<|endoftext|>


<commit_before>"use strict";

function gen(key, attrs, parent) {
    key = key || 'div';
    attrs = attrs || {};

    key = key.split('/');
    if (key.length > 1) {
        var node = gen(key.shift(), null, parent);
        while (key.length > 1) {
            node = node.gen(key.shift());
        }
        return node.gen(key.shift(), attrs);
    }

    key = key[0].split('.');
    var tag = key[0] || 'div';
    key.shift();
    if (key.length) attrs.class = key.join(' ');
    var ele = $('<'+tag+'>', attrs);
    if (parent) ele.appendTo($(parent));
    ele.gen = function(key, attrs) {
        var child = gen(key, attrs, ele);
        if (child[0].tagName === 'TABLE') {
            child.horizontalRecords = function(schema, list) {
                var data_keys = [];
                var header = child.gen('tr');

                var col_names = Object.keys(schema);
                col_names.forEach(k => {
                    data_keys.push(schema[k]);
                    header.gen('th', {text: k});
                });

                var max = Math.floor(Math.random() * 6) + 1;
                for (var i = 0; i < max; ++i)
                list.map(row => {
                    var tr = child.gen('tr');
                    col_names.map(name => {
                        var data_key = schema[name];
                        tr.gen('td', {text: row[data_key]});
                    });
                });
            };

            child.verticalRecord = function(tup) {
                Object.keys(tup).filter(k => tup[k] != undefined).map(k => {
                    var tr = child.gen('tr');
                    tr.gen('td', {text: k});
                    tr.gen('td', {text: tup[k]});
                });
                return child;
            };
        }
        return child;
    };
    return ele;
}

<commit_msg>remove hack, add return val<commit_after>"use strict";

function gen(key, attrs, parent) {
    key = key || 'div';
    attrs = attrs || {};

    key = key.split('/');
    if (key.length > 1) {
        var node = gen(key.shift(), null, parent);
        while (key.length > 1) {
            node = node.gen(key.shift());
        }
        return node.gen(key.shift(), attrs);
    }

    key = key[0].split('.');
    var tag = key[0] || 'div';
    key.shift();
    if (key.length) attrs.class = key.join(' ');
    var ele = $('<'+tag+'>', attrs);
    if (parent) ele.appendTo($(parent));
    ele.gen = function(key, attrs) {
        var child = gen(key, attrs, ele);
        if (child[0].tagName === 'TABLE') {
            child.horizontalRecords = function(schema, list) {
                var data_keys = [];
                var header = child.gen('tr');

                var col_names = Object.keys(schema);
                col_names.forEach(k => {
                    data_keys.push(schema[k]);
                    header.gen('th', {text: k});
                });

                return list.map(row => {
                    var tr = child.gen('tr');
                    col_names.map(name => {
                        var data_key = schema[name];
                        tr.gen('td', {text: row[data_key]});
                    });
					return tr;
                });
            };

            child.verticalRecord = function(tup) {
                Object.keys(tup).filter(k => tup[k] != undefined).map(k => {
                    var tr = child.gen('tr');
                    tr.gen('td', {text: k});
                    tr.gen('td', {text: tup[k]});
                });
                return child;
            };
        }
        return child;
    };
    return ele;
}

<|endoftext|>


<commit_before>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var PlumbGenerator;

(function()
{
    "use strict";

    PlumbGenerator =
    {
        genJsPlumbInstance : genJsPlumbInstance
    };

    // Expects an element returned from a jquery selector
    function genJsPlumbInstance(container)
    {
        var instance = jsPlumb.getInstance();

        instance.setContainer(container);

        instance.importDefaults(
        {
            Endpoint : ["Dot", {radius:2}],
            Anchor : "Continuous",
            HoverPaintStyle : {strokeStyle:"#1e8151", lineWidth:2 },
            Connector: ["StateMachine", {curviness: 20}],
            PaintStyle : {strokeStyle: "#5c96bc", lineWidth: 2, outlineColor: "transparent", outlineWidth: 4},
            ConnectionOverlays : [
                [ "Arrow", {
                    location:1,
                    id:"arrow",
                    length:14,
                    foldback:0.8
                } ]
            ]
        });

        // On dblclick, the connection will be deleted
        instance.bind("dblclick", instance.detach);

        // On click, select the connection
        instance.bind("click",function(c, e)
        {
            if(!c) return;

            // There are other elements (nodes or trees) selected, so deselect those elements
            if (Main.selectedElements.length > 0) Main.selectElement(null);

            var selectedConnections = Zoom.getZoomed().selectedConnections;
            var connectionId;
            if (c.id in selectedConnections)
            {
                if (e.ctrlKey)
                {
                    Main.deselectConnection(instance, selectedConnections, c.id);
                }
                else
                {
                    for (connectionId in selectedConnections)
                    {
                        Main.deselectConnection(instance, selectedConnections, connectionId);
                    }
                }
            }
            else
            {
                if (!e.ctrlKey)
                {
                    for (connectionId in selectedConnections)
                    {
                        Main.deselectConnection(instance, selectedConnections, connectionId);
                    }
                }

                selectedConnections[c.id] = { source: c.sourceId, target: c.targetId };

                // Change the color of the connection
                c.setPaintStyle({strokeStyle:"darkgoldenrod"});
            }
        });

        instance.bind("beforeDrop", function(info)
        {
            Main.makeConnection(info.sourceId,info.targetId, instance);
            instance.updateOffset({elId:info.sourceId, recalc:true});
            instance.repaint(info.sourceId, null, 0);

            instance.updateOffset({elId:info.targetId, recalc:true});
            instance.repaint(info.targetId, null, 0);
        });

        instance.bind("connection", function(info)
        {
            if($("#" + info.targetId).hasClass("parentSelected") ||
               $("#" + info.targetId).hasClass("selected"))
            {
                if($("#allParents").hasClass("enabled"))
                {
                    $("#" + info.sourceId).addClass("parentSelected");
                    Main.highlightParents(info.sourceId);
                }
            }
        });

        return instance;
    }
})();<commit_msg>Changed jsPlumb connectors<commit_after>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var PlumbGenerator;

(function()
{
    "use strict";

    PlumbGenerator =
    {
        genJsPlumbInstance : genJsPlumbInstance
    };

    // Expects an element returned from a jquery selector
    function genJsPlumbInstance(container)
    {
        var instance = jsPlumb.getInstance();

        instance.setContainer(container);

        instance.importDefaults(
        {
            Endpoint : ["Dot", {radius:2}],
            Anchor: "Continuous",
            HoverPaintStyle : {strokeStyle:"#1e8151", lineWidth:2 },
            Connector: ["StateMachine", { curviness: 14, margin: 5, proximityLimit: 75 }],
            PaintStyle : {strokeStyle: "#5c96bc", lineWidth: 2, outlineColor: "transparent", outlineWidth: 4},
            ConnectionOverlays : [
                [ "Arrow", {
                    location:1,
                    id:"arrow",
                    length:14,
                    foldback:0.8
                } ]
            ]
        });

        // On dblclick, the connection will be deleted
        instance.bind("dblclick", instance.detach);

        // On click, select the connection
        instance.bind("click",function(c, e)
        {
            if(!c) return;

            // There are other elements (nodes or trees) selected, so deselect those elements
            if (Main.selectedElements.length > 0) Main.selectElement(null);

            var selectedConnections = Zoom.getZoomed().selectedConnections;
            var connectionId;
            if (c.id in selectedConnections)
            {
                if (e.ctrlKey)
                {
                    Main.deselectConnection(instance, selectedConnections, c.id);
                }
                else
                {
                    for (connectionId in selectedConnections)
                    {
                        Main.deselectConnection(instance, selectedConnections, connectionId);
                    }
                }
            }
            else
            {
                if (!e.ctrlKey)
                {
                    for (connectionId in selectedConnections)
                    {
                        Main.deselectConnection(instance, selectedConnections, connectionId);
                    }
                }

                selectedConnections[c.id] = { source: c.sourceId, target: c.targetId };

                // Change the color of the connection
                c.setPaintStyle({strokeStyle:"darkgoldenrod"});
            }
        });

        instance.bind("beforeDrop", function(info)
        {
            Main.makeConnection(info.sourceId,info.targetId, instance);
            instance.updateOffset({elId:info.sourceId, recalc:true});
            instance.repaint(info.sourceId, null, 0);

            instance.updateOffset({elId:info.targetId, recalc:true});
            instance.repaint(info.targetId, null, 0);
        });

        instance.bind("connection", function(info)
        {
            if($("#" + info.targetId).hasClass("parentSelected") ||
               $("#" + info.targetId).hasClass("selected"))
            {
                if($("#allParents").hasClass("enabled"))
                {
                    $("#" + info.sourceId).addClass("parentSelected");
                    Main.highlightParents(info.sourceId);
                }
            }
        });

        return instance;
    }
})();<|endoftext|>


<commit_before>var fullScreen = slate.operation("move", {
  "x" : "screenOriginX",
  "y" : "screenOriginY",
  "width" : "screenSizeX",
  "height" : "screenSizeY"
});

var pushLeftThird = slate.operation("push", {
  "direction" : "left",
  "style" : "bar-resize:screenSizeX/3"
});

var pushRightThird = slate.operation("push", {
  "direction" : "right",
  "style" : "bar-resize:screenSizeX/3"
});

var pushRight2Thirds = slate.operation("push", {
  "direction" : "right",
  "style" : "bar-resize:2*screenSizeX/3"
});

var pushLeft2Thirds = slate.operation("push", {
  "direction" : "left",
  "style" : "bar-resize:2*screenSizeX/3"
});

var pushCenterThird = slate.operation("move", {
  "x": "screenOriginX+screenSizeX/3",
  "y": "screenOriginY",
  "width": "screenSizeX/3",
  "height" : "screenSizeY"
});

var pushLeft = slate.operation("push", {
  "direction" : "left",
  "style" : "bar-resize:screenSizeX/2"
});

var pushRight = slate.operation("push", {
  "direction" : "right",
  "style" : "bar-resize:screenSizeX/2"
});

slate.bind("right:ctrl", function(win) {
    win.doOperation(pushRight);
});

slate.bind("left:ctrl", function(win) {
    win.doOperation(pushLeft);
});

slate.bind("left:shift;ctrl", function(win) {
    win.doOperation(pushLeftThird);
});

slate.bind("right:shift;ctrl", function(win) {
    win.doOperation(pushRightThird);
});

slate.bind("right:shift;ctrl;alt",function(win) {
    win.doOperation(pushRight2Thirds);
});

slate.bind("left:shift;ctrl;alt",function(win) {
    win.doOperation(pushLeft2Thirds);
});

slate.bind("f:alt;ctrl",function(win) {
    win.doOperation(fullScreen);
});
<commit_msg>Map the middle third operation to a key that does not get interference from Mission Control.<commit_after>var fullScreen = slate.operation("move", {
  "x" : "screenOriginX",
  "y" : "screenOriginY",
  "width" : "screenSizeX",
  "height" : "screenSizeY"
});

var pushLeftThird = slate.operation("push", {
  "direction" : "left",
  "style" : "bar-resize:screenSizeX/3"
});

var pushRightThird = slate.operation("push", {
  "direction" : "right",
  "style" : "bar-resize:screenSizeX/3"
});

var pushRight2Thirds = slate.operation("push", {
  "direction" : "right",
  "style" : "bar-resize:2*screenSizeX/3"
});

var pushLeft2Thirds = slate.operation("push", {
  "direction" : "left",
  "style" : "bar-resize:2*screenSizeX/3"
});

var pushCenterThird = slate.operation("move", {
  "x": "screenOriginX+screenSizeX/3",
  "y": "screenOriginY",
  "width": "screenSizeX/3",
  "height" : "screenSizeY"
});

var pushLeft = slate.operation("push", {
  "direction" : "left",
  "style" : "bar-resize:screenSizeX/2"
});

var pushRight = slate.operation("push", {
  "direction" : "right",
  "style" : "bar-resize:screenSizeX/2"
});

slate.bind("right:ctrl", function(win) {
    win.doOperation(pushRight);
});

slate.bind("left:ctrl", function(win) {
    win.doOperation(pushLeft);
});

slate.bind("left:shift;ctrl", function(win) {
    win.doOperation(pushLeftThird);
});

slate.bind("right:shift;ctrl", function(win) {
    win.doOperation(pushRightThird);
});

slate.bind("right:shift;ctrl;alt",function(win) {
    win.doOperation(pushRight2Thirds);
});

slate.bind("left:shift;ctrl;alt",function(win) {
    win.doOperation(pushLeft2Thirds);
});

slate.bind("f:alt;ctrl",function(win) {
    win.doOperation(fullScreen);
});

/*
  tried to map this to up-arrow, seems to be confounded with
  something from mission control or something.
*/
slate.bind("c:alt;ctrl",function(win) {
    win.doOperation(pushCenterThird);
});
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var defaultOptions = {
        title: {
            "text": null
        },
        xAxis: {
            type: 'datetime'
        },
        yAxis: {
            title: {
                text: null
            }
        },
        tooltip: {
            valueDecimals: 2,
            formatter: function () {
                if (!this.points) {
                    this.points = [this.point];
                };

                if (moment.isMoment(this.x)) {
                    var s = '' + moment(this.x).format("DD/MM/YY HH:mm") + '',
                        pointsCount = this.points.length;

                    $.each(this.points, function (i, point) {
                        s += '
' + point.series.name + ': ' +
                            Highcharts.numberFormat(point.y);

                        if (pointsCount > 1 && point.percentage) {
                            s += " (" + Highcharts.numberFormat(point.percentage) + "%)";
                        }
                    });
                } else {
                    var points = this.points;
                    var name = points[0].key || points[0].name;

                    var s = "" + name + "";

                    $.each(points, function (i, point) {
                        if (points.length > 1) {
                            s += '
' + point.series.name + ': ' + Highcharts.numberFormat(point.y);
                        } else {
                            s += ": " + Highcharts.numberFormat(point.y);
                            if (point.percentage < 100) {
                                s += ' (' +Highcharts.numberFormat(point.percentage) +  '%)';
                            }
                        }
                    });
                }

                return s;
            },
            shared: true
        },
        exporting: {
            chartOptions: {
                title: {
                    text: ''
                }
            },
            buttons: {
                contextButton: {
                    menuItems: [
                        {
                            text: 'Toggle % Stacking',
                            onclick: function () {
                                var newStacking = "normal";
                                if (this.series[0].options.stacking == "normal") {
                                    newStacking = "percent";
                                }

                                _.each(this.series, function (series) {
                                    series.update({stacking: newStacking}, true);
                                });
                            }
                        }
                    ]
                }
            }
        },
        credits: {
            enabled: false
        },
        plotOptions: {
            area: {
                marker: {
                    enabled: false,
                    symbol: 'circle',
                    radius: 2,
                    states: {
                        hover: {
                            enabled: true
                        }
                    }
                }
            },
            column: {
                stacking: "normal",
                pointPadding: 0,
                borderWidth: 1,
                groupPadding: 0,
                shadow: false
            },
            line: {
                marker: {
                    radius: 1
                },
                lineWidth: 2,
                states: {
                    hover: {
                        lineWidth: 2,
                        marker: {
                            radius: 3
                        }
                    }
                }
            },
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    format: '{point.name}: {point.y} ({point.percentage:.1f} %)'
                }
            },
            scatter: {
                marker: {
                    radius: 5,
                    states: {
                        hover: {
                            enabled: true,
                            lineColor: 'rgb(100,100,100)'
                        }
                    }
                },
                tooltip: {
                    headerFormat: '{series.name}
',
                    pointFormat: '{point.x}, {point.y}'
                }
            }
        },
        series: []
    };

    angular.module('highchart', [])
        .directive('chart', ['$timeout', function ($timeout) {
            return {
                restrict: 'E',
                template: '

',
                scope: {
                    options: "=options",
                    series: "=series"
                },
                transclude: true,
                replace: true,

                link: function (scope, element, attrs) {
                    var chartsDefaults = {
                        chart: {
                            renderTo: element[0],
                            type: attrs.type || null,
                            height: attrs.height || null,
                            width: attrs.width || null
                        }
                    };

                    var chartOptions = $.extend(true, {}, defaultOptions, chartsDefaults);

                    // $timeout makes sure that this function invoked after the DOM ready. When draw/init
                    // invoked after the DOM is ready, we see first an empty HighCharts objects and later
                    // they get filled up. Which gives the feeling that the charts loading faster (otherwise
                    // we stare at an empty screen until the HighCharts object is ready).
                    $timeout(function(){
                        // Update when options change
                        scope.$watch('options', function (newOptions) {
                            initChart(newOptions);
                        }, true);

                        //Update when charts data changes
                        scope.$watch(function () {
                            // TODO: this might be an issue in case the series change, but they stay
                            // with the same length
                            return (scope.series && scope.series.length) || 0;
                        }, function (length) {
                            if (!length || length == 0) {
                                scope.chart.showLoading();
                            } else {
                                drawChart();
                            };
                        }, true);
                    });

                    function initChart(options) {
                        if (scope.chart) {
                            scope.chart.destroy();
                        };

                        $.extend(true, chartOptions, options);

                        scope.chart = new Highcharts.Chart(chartOptions);
                        drawChart();
                    }

                    function drawChart() {
                        while (scope.chart.series.length > 0) {
                            scope.chart.series[0].remove(false);
                        };

                        if (scope.series.length > 0 && _.some(scope.series[0].data, function (p) {
                            return (angular.isString(p.x) || angular.isDefined(p.name));
                        })) {
                            scope.chart.xAxis[0].update({type: 'category'});

                            if (!angular.isDefined(scope.series[0].data[0].name)) {
                                // We need to make sure that for each category, each series has a value.
                                var categories = _.union.apply(this, _.map(scope.series, function (s) {
                                    return _.pluck(s.data, 'x')
                                }));

                                _.each(scope.series, function (s) {
                                    // TODO: move this logic to Query#getChartData
                                    var yValues = _.groupBy(s.data, 'x');

                                    var newData = _.sortBy(_.map(categories, function (category) {
                                        return {
                                            name: category,
                                            y: yValues[category] && yValues[category][0].y
                                        }
                                    }), 'y').reverse();

                                    s.data = newData;
                                });
                            }
                        } else {
                            scope.chart.xAxis[0].update({type: 'datetime'});
                        }

                        scope.chart.counters.color = 0;

                        _.each(scope.series, function (s) {
                            // here we override the series with the visualization config
                            s = _.extend(s, chartOptions['series']);

                            if (s.type == 'area') {
                                _.each(s.data, function (p) {
                                    // This is an insane hack: somewhere deep in HighChart's code,
                                    // when you stack areas, it tries to convert the string representation
                                    // of point's x into a number. With the default implementation of toString
                                    // it fails....

                                    if (moment.isMoment(p.x)) {
                                        p.x.toString = function () {
                                            return String(this.toDate().getTime());
                                        };
                                    }
                                });
                            };

                            scope.chart.addSeries(s, false);
                        });

                        scope.chart.redraw();
                        scope.chart.hideLoading();
                    }

                }
            };

        }]);
})();<commit_msg>Fix: don't sort values when there is more than one category<commit_after>(function () {
    'use strict';

    var defaultOptions = {
        title: {
            "text": null
        },
        xAxis: {
            type: 'datetime'
        },
        yAxis: {
            title: {
                text: null
            }
        },
        tooltip: {
            valueDecimals: 2,
            formatter: function () {
                if (!this.points) {
                    this.points = [this.point];
                };

                if (moment.isMoment(this.x)) {
                    var s = '' + moment(this.x).format("DD/MM/YY HH:mm") + '',
                        pointsCount = this.points.length;

                    $.each(this.points, function (i, point) {
                        s += '
' + point.series.name + ': ' +
                            Highcharts.numberFormat(point.y);

                        if (pointsCount > 1 && point.percentage) {
                            s += " (" + Highcharts.numberFormat(point.percentage) + "%)";
                        }
                    });
                } else {
                    var points = this.points;
                    var name = points[0].key || points[0].name;

                    var s = "" + name + "";

                    $.each(points, function (i, point) {
                        if (points.length > 1) {
                            s += '
' + point.series.name + ': ' + Highcharts.numberFormat(point.y);
                        } else {
                            s += ": " + Highcharts.numberFormat(point.y);
                            if (point.percentage < 100) {
                                s += ' (' +Highcharts.numberFormat(point.percentage) +  '%)';
                            }
                        }
                    });
                }

                return s;
            },
            shared: true
        },
        exporting: {
            chartOptions: {
                title: {
                    text: ''
                }
            },
            buttons: {
                contextButton: {
                    menuItems: [
                        {
                            text: 'Toggle % Stacking',
                            onclick: function () {
                                var newStacking = "normal";
                                if (this.series[0].options.stacking == "normal") {
                                    newStacking = "percent";
                                }

                                _.each(this.series, function (series) {
                                    series.update({stacking: newStacking}, true);
                                });
                            }
                        }
                    ]
                }
            }
        },
        credits: {
            enabled: false
        },
        plotOptions: {
            area: {
                marker: {
                    enabled: false,
                    symbol: 'circle',
                    radius: 2,
                    states: {
                        hover: {
                            enabled: true
                        }
                    }
                }
            },
            column: {
                stacking: "normal",
                pointPadding: 0,
                borderWidth: 1,
                groupPadding: 0,
                shadow: false
            },
            line: {
                marker: {
                    radius: 1
                },
                lineWidth: 2,
                states: {
                    hover: {
                        lineWidth: 2,
                        marker: {
                            radius: 3
                        }
                    }
                }
            },
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    format: '{point.name}: {point.y} ({point.percentage:.1f} %)'
                }
            },
            scatter: {
                marker: {
                    radius: 5,
                    states: {
                        hover: {
                            enabled: true,
                            lineColor: 'rgb(100,100,100)'
                        }
                    }
                },
                tooltip: {
                    headerFormat: '{series.name}
',
                    pointFormat: '{point.x}, {point.y}'
                }
            }
        },
        series: []
    };

    angular.module('highchart', [])
        .directive('chart', ['$timeout', function ($timeout) {
            return {
                restrict: 'E',
                template: '

',
                scope: {
                    options: "=options",
                    series: "=series"
                },
                transclude: true,
                replace: true,

                link: function (scope, element, attrs) {
                    var chartsDefaults = {
                        chart: {
                            renderTo: element[0],
                            type: attrs.type || null,
                            height: attrs.height || null,
                            width: attrs.width || null
                        }
                    };

                    var chartOptions = $.extend(true, {}, defaultOptions, chartsDefaults);

                    // $timeout makes sure that this function invoked after the DOM ready. When draw/init
                    // invoked after the DOM is ready, we see first an empty HighCharts objects and later
                    // they get filled up. Which gives the feeling that the charts loading faster (otherwise
                    // we stare at an empty screen until the HighCharts object is ready).
                    $timeout(function(){
                        // Update when options change
                        scope.$watch('options', function (newOptions) {
                            initChart(newOptions);
                        }, true);

                        //Update when charts data changes
                        scope.$watch(function () {
                            // TODO: this might be an issue in case the series change, but they stay
                            // with the same length
                            return (scope.series && scope.series.length) || 0;
                        }, function (length) {
                            if (!length || length == 0) {
                                scope.chart.showLoading();
                            } else {
                                drawChart();
                            };
                        }, true);
                    });

                    function initChart(options) {
                        if (scope.chart) {
                            scope.chart.destroy();
                        };

                        $.extend(true, chartOptions, options);

                        scope.chart = new Highcharts.Chart(chartOptions);
                        drawChart();
                    }

                    function drawChart() {
                        while (scope.chart.series.length > 0) {
                            scope.chart.series[0].remove(false);
                        };

                        if (scope.series.length > 0 && _.some(scope.series[0].data, function (p) {
                            return (angular.isString(p.x) || angular.isDefined(p.name));
                        })) {
                            scope.chart.xAxis[0].update({type: 'category'});

                            if (!angular.isDefined(scope.series[0].data[0].name)) {
                                // We need to make sure that for each category, each series has a value.
                                var categories = _.union.apply(this, _.map(scope.series, function (s) {
                                    return _.pluck(s.data, 'x')
                                }));

                                _.each(scope.series, function (s) {
                                    // TODO: move this logic to Query#getChartData
                                    var yValues = _.groupBy(s.data, 'x');

                                    var newData = _.map(categories, function (category) {
                                        return {
                                            name: category,
                                            y: yValues[category] && yValues[category][0].y
                                        }
                                    });

                                    if (categories.length == 1) {
                                        newData = _.sortBy(newData, 'y').reverse();
                                    };

                                    s.data = newData;
                                });
                            }
                        } else {
                            scope.chart.xAxis[0].update({type: 'datetime'});
                        }

                        scope.chart.counters.color = 0;

                        _.each(scope.series, function (s) {
                            // here we override the series with the visualization config
                            s = _.extend(s, chartOptions['series']);

                            if (s.type == 'area') {
                                _.each(s.data, function (p) {
                                    // This is an insane hack: somewhere deep in HighChart's code,
                                    // when you stack areas, it tries to convert the string representation
                                    // of point's x into a number. With the default implementation of toString
                                    // it fails....

                                    if (moment.isMoment(p.x)) {
                                        p.x.toString = function () {
                                            return String(this.toDate().getTime());
                                        };
                                    }
                                });
                            };

                            scope.chart.addSeries(s, false);
                        });

                        scope.chart.redraw();
                        scope.chart.hideLoading();
                    }

                }
            };

        }]);
})();<|endoftext|>


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

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $ */

/**
 * Utilities for dealing with animations in the UI.
 */
define(function (require, exports, module) {
    "use strict";

    var Async   = require("utils/Async");

    /**
     * Start an animation by adding the given class to the given target. When the
     * animation is complete, removes the class, clears the event handler we attach
     * to watch for the animation to finish, and resolves the returned promise.
     *
     * @param {Element} target The DOM node to animate.
     * @param {string} animClass The class that applies the animation/transition to the target.
     * @param {number=} timeoutDuration Time to wait in ms before rejecting promise. Default is 400.
     * @return {$.Promise} A promise that is resolved when the animation completes. Never rejected.
     */
    function animateUsingClass(target, animClass, timeoutDuration) {
        var result  = new $.Deferred(),
            $target = $(target);

        timeoutDuration = timeoutDuration || 400;

        function cleanup() {
            $target
                .removeClass(animClass)
                .off(".asyncWithTimeout");
        }

        function finish(e) {
            if (e.target === target) {
                result.resolve();
            }
        }

        if ($target.is(":hidden")) {
            // Don't do anything if the element is hidden because webkitTransitionEnd wouldn't fire
            result.resolve();
        } else {
            // Note that we can't just use $.one() here because we only want to remove
            // the handler when we get the transition end event for the correct target (not
            // a child).
            $target
                .addClass(animClass)
                .on("webkitTransitionEnd.asyncWithTimeout", finish);
        }

        // Use timeout in case transition end event is not sent
        return Async.withTimeout(result.promise(), timeoutDuration, true)
            .done(cleanup);
    }

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

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $ */

/**
 * Utilities for dealing with animations in the UI.
 */
define(function (require, exports, module) {
    "use strict";

    var Async   = require("utils/Async");

    /**
     * Start an animation by adding the given class to the given target. When the
     * animation is complete, removes the class, clears the event handler we attach
     * to watch for the animation to finish, and resolves the returned promise.
     *
     * @param {Element} target The DOM node to animate.
     * @param {string} animClass The class that applies the animation/transition to the target.
     * @param {number=} timeoutDuration Time to wait in ms before rejecting promise. Default is 400.
     * @return {$.Promise} A promise that is resolved when the animation completes. Never rejected.
     */
    function animateUsingClass(target, animClass, timeoutDuration) {
        var result  = new $.Deferred(),
            $target = $(target);

        timeoutDuration = timeoutDuration || 400;

        function finish(e) {
            if (e.target === target) {
                result.resolve();
            }
        }

        function cleanup() {
            $target
                .removeClass(animClass)
                .off("webkitTransitionEnd", finish);
        }

        if ($target.is(":hidden")) {
            // Don't do anything if the element is hidden because webkitTransitionEnd wouldn't fire
            result.resolve();
        } else {
            // Note that we can't just use $.one() here because we only want to remove
            // the handler when we get the transition end event for the correct target (not
            // a child).
            $target
                .addClass(animClass)
                .on("webkitTransitionEnd", finish);
        }

        // Use timeout in case transition end event is not sent
        return Async.withTimeout(result.promise(), timeoutDuration, true)
            .done(cleanup);
    }

    exports.animateUsingClass = animateUsingClass;
});
<|endoftext|>