<commit_before>/**
 * Fortnite plugin
 *
 * This uses FNBR's API to fetch the item shop.
 *
 * @license MIT license
 */
'use strict';

const https = require('https');
const puppeteer = require('puppeteer');
const URL = require('url');
const fs = require('fs');
var CronJob = require('cron').CronJob;
new CronJob('1 20 * * *', function() { // everday at 8:01 EST
	console.log('item shop posting triggered');
	bot.channels.forEach(function (channel, id) {
		console.log('id: ' + id);
		if (id === '576600954510770176') {
			console.log('found channel');
			Chat.commands['itemshop'](null, channel, null);
			return;
		}
	});
}, null, true, 'America/New_York');

const imageSize = 130;

const colors = {
	common: {
		bg: 'background: radial-gradient(#bebebe,#646464);',
		border: 'border: 2px solid #b1b1b1;;',
	},
	uncommon: {
		bg: 'background: radial-gradient(#60aa3a,#175117);',
		border: 'border: 2px solid #87e339;',
	},
	rare: {
		bg: 'background: radial-gradient(#49acf2,#143977);',
		border: 'border: 2px solid #37d1ff;',
	},
	epic: {
		bg: 'background: radial-gradient(#b15be2,#4b2483);',
		border: 'border: 2px solid #e95eff;',
    },
	marvel: {
		bg: 'background: radial-gradient(#c53334,#761b1b);',
		border: 'border: 2px solid #ef3537;',
	},
	legendary: {
		bg: 'background: radial-gradient(#d37841,#78371d);',
		border: 'border: 2px solid #e98d4b;',
	},
};

function screenshot(callback) {
	puppeteer.launch().then(function (browser) {
		browser.newPage().then(function (page) {
			page.setViewport({width: 1920, height: 1080}).then(function () {
				page.goto(URL.pathToFileURL('./shop.html'), {waitUntil: 'networkidle0'}).then(function () {
					page.$('body > div > table').then(function (selector) {
						selector.screenshot({path: 'itemshop.png'}).then(function (img) {
							browser.close();
							return callback(img);
						});
					});
				});
			});
		});
	});
}

exports.commands = {
  	fortnite: 'itemshop',
	itemshop: function (target, room, user) {
		if (!Config.fnbrAPI) return Chat.send(room, "This bot does not have an API key configured to use this command.");
		const date = new Date();
		const stamp = `${date.getMonth() + 1}-${date.getDate()}-${date.getFullYear()}`;
		if (!user || Chat.isAdmin(user)) {
			const options = {
				host: 'fnbr.co',
				port: 443,
				path: `/api/shop`,
				method: 'GET',
				headers: {
					'x-api-key': Config.fnbrAPI,
				},
			};
			let body = '';
			const self = Chat;
			const r = room;
			https.get(options, function (res, error) {
				res.on('data', function (data) {
					body += data;
				});
				res.on('end', function () {
					let buff = `

Fortnite Item Shop
${stamp}

Featured	`;
					let shop = false;
					try {
						shop = (JSON.parse(body).data);
					} catch (e) {
						self.send(r, "Could not fetch shop.");
						return;
					}
					if (!shop) return self.send(r, 'oh no, something failed while trying to load the shop');
					const featured = shop.featured;
					const daily = shop.daily;
					let itemCount = 0;
					function newRow(count) {
						if (count % 2 !== 0) return true;
						return false;
					}
					featured.forEach(item => {
						itemCount++;
						if (newRow(itemCount)) {
							buff += '

';
						};
						let marquee = false; // item.name.length > 15;
						buff += `

${marquee ? '<marquee scrollamount="5">' : ''}${item.name}${marquee ? '</marquee>' : ''}
${item.priceIconLink ? `<img style="vertical-align:middle" src="${item.priceIconLink}" width="16" height="16">` : ''}${item.price}

	`;
					});
					buff += '

Daily	';

					daily.forEach(item => {
						itemCount++;
						if (newRow(itemCount)) {
							buff += '

';
						};
						let marquee = false; // item.name.length > 15;
						buff += `

${marquee ? '<marquee scrollamount="5">' : ''}${item.name}${marquee ? '</marquee>' : ''}
${item.priceIconLink ? `<img style="vertical-align:middle" src="${item.priceIconLink}" width="16" height="16">` : ''}${item.price}

	`;
					});
					buff += '

Powered by the API from fnbr.co

';

					fs.writeFileSync('shop.html', '' + buff + '</bod>', 'utf8');

					screenshot(function (buffer) {
						room.send("Current Fortnite Item Shop", {files: [{attachment: buffer}]});
					});
				});
				res.on('error', function (e) {
					self.send(r, `Crashed while trying to get the shop: ${e.code}`);
				});
			});
		} else {
			room.send("Current Fortnite Item Shop", {files: [{attachment: 'itemshop.png'}]});
		}
	},
};
<commit_msg>Update console logging for Fortnite plugin<commit_after>/**
 * Fortnite plugin
 *
 * This uses FNBR's API to fetch the item shop.
 *
 * @license MIT license
 */
'use strict';

const https = require('https');
const puppeteer = require('puppeteer');
const URL = require('url');
const fs = require('fs');
var CronJob = require('cron').CronJob;
new CronJob('1 20 * * *', function() { // everday at 8:01 EST
	console.log('item shop posting triggered');
	bot.channels.forEach(function (channel, id) {
		if (id === '576600954510770176') {
			console.log('posting item shop...');
			Chat.commands['itemshop'](null, channel, null);
			return;
		}
	});
}, null, true, 'America/New_York');

const imageSize = 130;

const colors = {
	common: {
		bg: 'background: radial-gradient(#bebebe,#646464);',
		border: 'border: 2px solid #b1b1b1;;',
	},
	uncommon: {
		bg: 'background: radial-gradient(#60aa3a,#175117);',
		border: 'border: 2px solid #87e339;',
	},
	rare: {
		bg: 'background: radial-gradient(#49acf2,#143977);',
		border: 'border: 2px solid #37d1ff;',
	},
	epic: {
		bg: 'background: radial-gradient(#b15be2,#4b2483);',
		border: 'border: 2px solid #e95eff;',
    },
	marvel: {
		bg: 'background: radial-gradient(#c53334,#761b1b);',
		border: 'border: 2px solid #ef3537;',
	},
	legendary: {
		bg: 'background: radial-gradient(#d37841,#78371d);',
		border: 'border: 2px solid #e98d4b;',
	},
};

function screenshot(callback) {
	puppeteer.launch().then(function (browser) {
		browser.newPage().then(function (page) {
			page.setViewport({width: 1920, height: 1080}).then(function () {
				page.goto(URL.pathToFileURL('./shop.html'), {waitUntil: 'networkidle0'}).then(function () {
					page.$('body > div > table').then(function (selector) {
						selector.screenshot({path: 'itemshop.png'}).then(function (img) {
							browser.close();
							return callback(img);
						});
					});
				});
			});
		});
	});
}

exports.commands = {
  	fortnite: 'itemshop',
	itemshop: function (target, room, user) {
		if (!Config.fnbrAPI) return Chat.send(room, "This bot does not have an API key configured to use this command.");
		const date = new Date();
		const stamp = `${date.getMonth() + 1}-${date.getDate()}-${date.getFullYear()}`;
		if (!user || Chat.isAdmin(user)) {
			const options = {
				host: 'fnbr.co',
				port: 443,
				path: `/api/shop`,
				method: 'GET',
				headers: {
					'x-api-key': Config.fnbrAPI,
				},
			};
			let body = '';
			const self = Chat;
			const r = room;
			https.get(options, function (res, error) {
				res.on('data', function (data) {
					body += data;
				});
				res.on('end', function () {
					let buff = `

Fortnite Item Shop
${stamp}

Featured	`;
					let shop = false;
					try {
						shop = (JSON.parse(body).data);
					} catch (e) {
						self.send(r, "Could not fetch shop.");
						return;
					}
					if (!shop) return self.send(r, 'oh no, something failed while trying to load the shop');
					const featured = shop.featured;
					const daily = shop.daily;
					let itemCount = 0;
					function newRow(count) {
						if (count % 2 !== 0) return true;
						return false;
					}
					featured.forEach(item => {
						itemCount++;
						if (newRow(itemCount)) {
							buff += '

';
						};
						let marquee = false; // item.name.length > 15;
						buff += `

${marquee ? '<marquee scrollamount="5">' : ''}${item.name}${marquee ? '</marquee>' : ''}
${item.priceIconLink ? `<img style="vertical-align:middle" src="${item.priceIconLink}" width="16" height="16">` : ''}${item.price}

	`;
					});
					buff += '

Daily	';

					daily.forEach(item => {
						itemCount++;
						if (newRow(itemCount)) {
							buff += '

';
						};
						let marquee = false; // item.name.length > 15;
						buff += `

${marquee ? '<marquee scrollamount="5">' : ''}${item.name}${marquee ? '</marquee>' : ''}
${item.priceIconLink ? `<img style="vertical-align:middle" src="${item.priceIconLink}" width="16" height="16">` : ''}${item.price}

	`;
					});
					buff += '

Powered by the API from fnbr.co

';

					fs.writeFileSync('shop.html', '' + buff + '</bod>', 'utf8');

					screenshot(function (buffer) {
						room.send("Current Fortnite Item Shop", {files: [{attachment: buffer}]});
					});
				});
				res.on('error', function (e) {
					self.send(r, `Crashed while trying to get the shop: ${e.code}`);
				});
			});
		} else {
			room.send("Current Fortnite Item Shop", {files: [{attachment: 'itemshop.png'}]});
		}
	},
};
<|endoftext|>


<commit_before>var CoreView = require('backbone/core-view');
var _ = require('underscore');
var $ = require('jquery');
var TableViewModel = require('./table-view-model.js');
var TableHeadView = require('./head/table-head-view');
var TableBodyView = require('./body/table-body-view');
var addTableRow = require('./operations/table-add-row');
var addTableColumn = require('./operations/table-add-column');
var SQLUtils = require('../../helpers/sql-utils');
var checkAndBuildOpts = require('../../helpers/required-opts');

var REQUIRED_OPTS = [
  'analysisDefinitionNodeModel',
  'columnsCollection',
  'modals'
];

/*
 *  Main table view
 */

module.exports = CoreView.extend({

  className: 'Table-wrapper',
  tagName: 'div',

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this._rowsCollection = this._analysisDefinitionNodeModel.queryRowsCollection;
    this._queryGeometryModel = this._analysisDefinitionNodeModel.queryGeometryModel;
    this._querySchemaModel = this._analysisDefinitionNodeModel.querySchemaModel;
    this._tableModel = this._analysisDefinitionNodeModel.isSourceType() && this._analysisDefinitionNodeModel.getTableModel();

    this._tableViewModel = new TableViewModel({
      relativePositionated: opts.relativePositionated,
      tableName: opts.tableName
    }, {
      analysisDefinitionNodeModel: this._analysisDefinitionNodeModel,
      columnsCollection: this._columnsCollection
    });

    this._initBinds();

    if (this._queryGeometryModel.shouldFetch()) {
      this._queryGeometryModel.fetch();
    }

    if (this._querySchemaModel.shouldFetch()) {
      this._querySchemaModel.fetch();
    } else if (this._rowsCollection.shouldFetch()) {
      this._fetchRowsData();
    }
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    var tableElement = $('<div>').addClass('Table js-table');
    this.$el.append(tableElement);
    this._initViews();

    this.$('.js-table').toggleClass('Table--relative', !!this._tableViewModel.get('relativePositionated'));
    this._setDisableState();
    return this;
  },

  _initBinds: function () {
    this._onChangeQueryOrStatus = this._onChangeQueryOrStatus.bind(this);

    this.listenTo(this._querySchemaModel, 'change:query change:status', _.debounce(this._onChangeQueryOrStatus, 100));
    this.listenTo(this._querySchemaModel, 'change:status', this._setDisableState);
    this.listenTo(this._querySchemaModel, 'change:query', this._onQueryChanged);
    this.listenTo(this._querySchemaModel, 'change:status', this._fetchRowsData);
    this.listenTo(this._tableViewModel, 'change:sort_order change:order_by', this._fetchRowsData);

    if (this._tableModel && this._tableModel.isSync()) {
      var syncModel = this._tableModel.getSyncModel();
      this.listenTo(syncModel, 'destroy', this.render);
    }
  },

  _setDisableState: function () {
    this.$('.js-table').toggleClass('is-disabled', !!this._tableViewModel.isDisabled());
  },

  _fetchRowsData: function (model) {
    var attrsChanged = model && _.keys(model.changed);
    var altersData = SQLUtils.altersData(this._querySchemaModel.get('query'));
    var isCustomQueryApplied = this._tableViewModel.isCustomQueryApplied();
    var changeComeFromSortOrOrder = false;

    if (attrsChanged && (_.contains(attrsChanged, 'sort_order') || _.contains(attrsChanged, 'order_by'))) {
      changeComeFromSortOrOrder = true;
    }

    if (this._querySchemaModel.isFetched() && !altersData) {
      this._rowsCollection.fetch({
        data: {
          page: this._tableViewModel.get('page'),
          order_by: !isCustomQueryApplied || changeComeFromSortOrOrder ? this._tableViewModel.get('order_by') : '',
          sort_order: !isCustomQueryApplied || changeComeFromSortOrOrder ? this._tableViewModel.get('sort_order') : '',
          exclude: !isCustomQueryApplied || changeComeFromSortOrOrder ? ['the_geom_webmercator'] : []
        }
      });
    }
  },

  _initViews: function () {
    var tableHeadView = new TableHeadView({
      modals: this._modals,
      queryGeometryModel: this._queryGeometryModel,
      columnsCollection: this._columnsCollection,
      tableViewModel: this._tableViewModel
    });

    this.addView(tableHeadView);
    this.$('.js-table').append(tableHeadView.render().el);

    var tableBodyView = new TableBodyView({
      modals: this._modals,
      columnsCollection: this._columnsCollection,
      rowsCollection: this._rowsCollection,
      queryGeometryModel: this._queryGeometryModel,
      querySchemaModel: this._querySchemaModel,
      tableViewModel: this._tableViewModel
    });

    this.addView(tableBodyView);
    this.$('.js-table').append(tableBodyView.render().el);
  },

  _onChangeQueryOrStatus: function () {
    var schemaStatus = this._querySchemaModel.get('status');
    var geometryStatus = this._queryGeometryModel.get('status');

    if (schemaStatus === 'unfetched' && this._querySchemaModel.canFetch()) {
      this._querySchemaModel.fetch();
    }

    if (geometryStatus === 'unfetched' && this._queryGeometryModel.canFetch()) {
      this._queryGeometryModel.fetch();
    }
  },

  addRow: function () {
    addTableRow({
      rowsCollection: this._rowsCollection
    });
  },

  addColumn: function () {
    addTableColumn({
      columnsCollection: this._columnsCollection
    });
  },

  getColumnsCollection: function () {
    return this._columnsCollection;
  },

  _onQueryChanged: function () {
    this._tableViewModel.resetFetchDefaults();
  },

  // Remove elements that are not applied in the view
  remove: function () {
    $('.Table-paginator').remove();
    CoreView.prototype.remove.apply(this);
  }
});
<commit_msg>Remove duplicated code<commit_after>var CoreView = require('backbone/core-view');
var _ = require('underscore');
var $ = require('jquery');
var TableViewModel = require('./table-view-model.js');
var TableHeadView = require('./head/table-head-view');
var TableBodyView = require('./body/table-body-view');
var addTableRow = require('./operations/table-add-row');
var addTableColumn = require('./operations/table-add-column');
var SQLUtils = require('../../helpers/sql-utils');
var checkAndBuildOpts = require('../../helpers/required-opts');

var REQUIRED_OPTS = [
  'analysisDefinitionNodeModel',
  'columnsCollection',
  'modals'
];

/*
 *  Main table view
 */

module.exports = CoreView.extend({

  className: 'Table-wrapper',
  tagName: 'div',

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this._rowsCollection = this._analysisDefinitionNodeModel.queryRowsCollection;
    this._queryGeometryModel = this._analysisDefinitionNodeModel.queryGeometryModel;
    this._querySchemaModel = this._analysisDefinitionNodeModel.querySchemaModel;
    this._tableModel = this._analysisDefinitionNodeModel.isSourceType() && this._analysisDefinitionNodeModel.getTableModel();

    this._tableViewModel = new TableViewModel({
      relativePositionated: opts.relativePositionated,
      tableName: opts.tableName
    }, {
      analysisDefinitionNodeModel: this._analysisDefinitionNodeModel,
      columnsCollection: this._columnsCollection
    });

    this._initBinds();

    if (this._querySchemaModel.shouldFetch()) {
      this._querySchemaModel.fetch();
    } else if (this._rowsCollection.shouldFetch()) {
      this._fetchRowsData();
    }
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    var tableElement = $('<div>').addClass('Table js-table');
    this.$el.append(tableElement);
    this._initViews();

    this.$('.js-table').toggleClass('Table--relative', !!this._tableViewModel.get('relativePositionated'));
    this._setDisableState();
    return this;
  },

  _initBinds: function () {
    this._onChangeQueryOrStatus = this._onChangeQueryOrStatus.bind(this);

    this.listenTo(this._querySchemaModel, 'change:query change:status', _.debounce(this._onChangeQueryOrStatus, 100));
    this.listenTo(this._querySchemaModel, 'change:status', this._setDisableState);
    this.listenTo(this._querySchemaModel, 'change:query', this._onQueryChanged);
    this.listenTo(this._querySchemaModel, 'change:status', this._fetchRowsData);
    this.listenTo(this._tableViewModel, 'change:sort_order change:order_by', this._fetchRowsData);

    if (this._tableModel && this._tableModel.isSync()) {
      var syncModel = this._tableModel.getSyncModel();
      this.listenTo(syncModel, 'destroy', this.render);
    }
  },

  _setDisableState: function () {
    this.$('.js-table').toggleClass('is-disabled', !!this._tableViewModel.isDisabled());
  },

  _fetchRowsData: function (model) {
    var attrsChanged = model && _.keys(model.changed);
    var altersData = SQLUtils.altersData(this._querySchemaModel.get('query'));
    var isCustomQueryApplied = this._tableViewModel.isCustomQueryApplied();
    var changeComeFromSortOrOrder = false;

    if (attrsChanged && (_.contains(attrsChanged, 'sort_order') || _.contains(attrsChanged, 'order_by'))) {
      changeComeFromSortOrOrder = true;
    }

    if (this._querySchemaModel.isFetched() && !altersData) {
      this._rowsCollection.fetch({
        data: {
          page: this._tableViewModel.get('page'),
          order_by: !isCustomQueryApplied || changeComeFromSortOrOrder ? this._tableViewModel.get('order_by') : '',
          sort_order: !isCustomQueryApplied || changeComeFromSortOrOrder ? this._tableViewModel.get('sort_order') : '',
          exclude: !isCustomQueryApplied || changeComeFromSortOrOrder ? ['the_geom_webmercator'] : []
        }
      });
    }
  },

  _initViews: function () {
    var tableHeadView = new TableHeadView({
      modals: this._modals,
      queryGeometryModel: this._queryGeometryModel,
      columnsCollection: this._columnsCollection,
      tableViewModel: this._tableViewModel
    });

    this.addView(tableHeadView);
    this.$('.js-table').append(tableHeadView.render().el);

    var tableBodyView = new TableBodyView({
      modals: this._modals,
      columnsCollection: this._columnsCollection,
      rowsCollection: this._rowsCollection,
      queryGeometryModel: this._queryGeometryModel,
      querySchemaModel: this._querySchemaModel,
      tableViewModel: this._tableViewModel
    });

    this.addView(tableBodyView);
    this.$('.js-table').append(tableBodyView.render().el);
  },

  _onChangeQueryOrStatus: function () {
    var schemaStatus = this._querySchemaModel.get('status');
    var geometryStatus = this._queryGeometryModel.get('status');

    if (schemaStatus === 'unfetched' && this._querySchemaModel.canFetch()) {
      this._querySchemaModel.fetch();
    }

    if (geometryStatus === 'unfetched' && this._queryGeometryModel.canFetch()) {
      this._queryGeometryModel.fetch();
    }
  },

  addRow: function () {
    addTableRow({
      rowsCollection: this._rowsCollection
    });
  },

  addColumn: function () {
    addTableColumn({
      columnsCollection: this._columnsCollection
    });
  },

  getColumnsCollection: function () {
    return this._columnsCollection;
  },

  _onQueryChanged: function () {
    this._tableViewModel.resetFetchDefaults();
  },

  // Remove elements that are not applied in the view
  remove: function () {
    $('.Table-paginator').remove();
    CoreView.prototype.remove.apply(this);
  }
});
<|endoftext|>


<commit_before>/**
 * @author v.lugovsky
 * created on 16.12.2015
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.pages.dashboard.profile')
    .controller('ProfilePageCtrl', ProfilePageCtrl);

  /** @ngInject */
  function ProfilePageCtrl($scope, fileReader, $filter, $uibModal,editableOptions,editableThemes) {
    $scope.picture = $filter('profilePicture')('Nasta');

    $scope.removePicture = function () {
      $scope.picture = $filter('appImage')('theme/no-photo.png');
      $scope.noPicture = true;
    };

    $scope.uploadPicture = function () {
      var fileInput = document.getElementById('uploadFile');
      fileInput.click();

    };

    $scope.update = function(){
      var techs = JSON.parse(JSON.stringify($scope.techs));
      // console.log(techs);
      // $scope.vm.data = {
      //   "techs" : techs
      // };
      var social = JSON.parse(JSON.stringify($scope.socialProfiles));
      // $scope.vm.data = {
      //     "social" : social
      //
      // };
      console.log(social);
      var internDetails = {
        firstname : $scope.vm.data.firstname ,
        lastname : $scope.vm.data.lastname ,
        fullname : $scope.vm.data.fullname,
        NIC : $scope.vm.data.nic,
        password : $scope.vm.data.conformpassword,
        email : $scope.vm.data.email,
        mobile : $scope.vm.data.mobile,
        tel : $scope.vm.data.tel,
        address : $scope.vm.data.address,
        goals : $scope.vm.data.goal,
        social : social,
        techs : techs

      };
      console.log(internDetails);
    };

    $scope.socialProfiles = [
      {
        name: 'Facebook',
        icon: 'socicon-facebook'
      },
      {
        name: 'LinkedIn',
        icon: 'socicon-linkedin'
      },
      {
        name: 'GitHub',
        icon: 'socicon-github'
      },
      {
        name: 'StackOverflow',
        icon: 'socicon-stackoverflow'
      }
    ];

    $scope.techs = [
      {
        "id": 1,
        "name": "Angular"

      },
      {
        "id": 2,
        "name": "React"

      }

    ];

    $scope.unconnect = function (item) {
      item.href = undefined;
    };

    $scope.showModal = function (item) {
      $uibModal.open({
        animation: true,
        controller: 'ProfileModalCtrl',
        templateUrl: 'app/pages/profile/profileModal.html'
      }).result.then(function (link) {
          item.href = link;
        });
    };

    $scope.getFile = function () {
      fileReader.readAsDataUrl($scope.file, $scope)
          .then(function (result) {
            $scope.picture = result;
          });
    };

    $scope.showGroup = function(user) {
      if(tech.group && $scope.groups.length) {
        var selected = $filter('filter')($scope.groups, {id: tech.group});
        return selected.length ? selected[0].text : 'Not set';
      } else return 'Not set'
    };

    $scope.showStatus = function(user) {
      var selected = [];
      if(tech.status) {
        selected = $filter('filter')($scope.statuses, {value: tech.status});
      }
      return selected.length ? selected[0].text : 'Not set';
    };

    $scope.removeUser = function(index) {
      $scope.techs.splice(index, 1);
    };

    $scope.addUser = function() {
      $scope.inserted = {
        id: $scope.techs.length+1,
        name: '',
        status: null,
        group: null
      };
      $scope.techs.push($scope.inserted);
    };

    editableOptions.theme = 'bs3';
    editableThemes['bs3'].submitTpl = '<button type="submit" class="btn btn-primary btn-with-icon"></button>';
    editableThemes['bs3'].cancelTpl = '<button type="button" ng-click="$form.$cancel()" class="btn btn-default btn-with-icon"></button>';

    $scope.switches = [true, true, false, true, true, false];
  }

})();
<commit_msg>profile ctrl was changed 2<commit_after>/**
 * @author v.lugovsky
 * created on 16.12.2015
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.pages.dashboard.profile')
    .controller('ProfilePageCtrl', ProfilePageCtrl);

  /** @ngInject */
  function ProfilePageCtrl($scope, fileReader, $filter, $uibModal,editableOptions,editableThemes) {
    $scope.picture = $filter('profilePicture')('Nasta');

    $scope.removePicture = function () {
      $scope.picture = $filter('appImage')('theme/no-photo.png');
      $scope.noPicture = true;
    };

    $scope.uploadPicture = function () {
      var fileInput = document.getElementById('uploadFile');
      fileInput.click();

    };

    $scope.update = function(){
      var techs = JSON.parse(JSON.stringify($scope.techs));
      // console.log(techs);
      // $scope.vm.data = {
      //   "techs" : techs
      // };
      var social = JSON.parse(JSON.stringify($scope.socialProfiles));
      // $scope.vm.data = {
      //     "social" : social
      //
      // };
      console.log(social);
      var internDetails = {
        firstname : $scope.vm.data.firstname ,
        lastname : $scope.vm.data.lastname ,
        fullname : $scope.vm.data.fullname,
        NIC : $scope.vm.data.nic,
        password : $scope.vm.data.conformpassword,
        email : $scope.vm.data.email,
        mobile : $scope.vm.data.mobile,
        tel : $scope.vm.data.tel,
        address : $scope.vm.data.address,
        goals : $scope.vm.data.goal,
        social : social,
        techs : techs

      };

      console.log(internDetails);
    };

    $scope.socialProfiles = [
      {
        name: 'Facebook',
        icon: 'socicon-facebook'
      },
      {
        name: 'LinkedIn',
        icon: 'socicon-linkedin'
      },
      {
        name: 'GitHub',
        icon: 'socicon-github'
      },
      {
        name: 'StackOverflow',
        icon: 'socicon-stackoverflow'
      }
    ];

    $scope.techs = [
      {
        "id": 1,
        "name": "Angular"

      },
      {
        "id": 2,
        "name": "React"

      }

    ];

    $scope.unconnect = function (item) {
      item.href = undefined;
    };

    $scope.showModal = function (item) {
      $uibModal.open({
        animation: true,
        controller: 'ProfileModalCtrl',
        templateUrl: 'app/pages/profile/profileModal.html'
      }).result.then(function (link) {
          item.href = link;
        });
    };

    $scope.getFile = function () {
      fileReader.readAsDataUrl($scope.file, $scope)
          .then(function (result) {
            $scope.picture = result;
          });
    };

    $scope.showGroup = function(user) {
      if(tech.group && $scope.groups.length) {
        var selected = $filter('filter')($scope.groups, {id: tech.group});
        return selected.length ? selected[0].text : 'Not set';
      } else return 'Not set'
    };

    $scope.showStatus = function(user) {
      var selected = [];
      if(tech.status) {
        selected = $filter('filter')($scope.statuses, {value: tech.status});
      }
      return selected.length ? selected[0].text : 'Not set';
    };

    $scope.removeUser = function(index) {
      $scope.techs.splice(index, 1);
    };

    $scope.addUser = function() {
      $scope.inserted = {
        id: $scope.techs.length+1,
        name: '',
        status: null,
        group: null
      };
      $scope.techs.push($scope.inserted);
    };

    editableOptions.theme = 'bs3';
    editableThemes['bs3'].submitTpl = '<button type="submit" class="btn btn-primary btn-with-icon"></button>';
    editableThemes['bs3'].cancelTpl = '<button type="button" ng-click="$form.$cancel()" class="btn btn-default btn-with-icon"></button>';

    $scope.switches = [true, true, false, true, true, false];
  }

})();
<|endoftext|>


<commit_before>/**
controller.js

Copyright (c) 2015 xylitol45

This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
(function(){
    'use strict';

    angular.module("controllerModule", ['ngSanitize'])
    .controller('firstCtrl',['shared',function(shared){

        console.log(shared.uuid());
/*
var memo = MC.Collection("memo_collection");
memo.findOneMine(CRITERIA)
.then(function(item) {
  item.title = NEW_TITLE;
  return item.update();
}, function(err){
  console.log('Error: ' + JSON.stringify(err));
  return null; })
.then(function(updatedItem) {
  console.log('Updating is success!' + JSON.stringify(updatedItem));
});
*/
        monaca.cloud.User.autoLogin()
        .then(function(result){
            shared.userid = result._userid;
            app.navi.replacePage('top.html',{animation:"none"});
        },function(err){
            app.navi.replacePage('signup.html',{animation:"none"});
        });
    }])
    .controller('signupCtrl',['shared','$scope',function(shared,$scope){
        console.log('signupCtrl');
        var _this=this;
        _this.username = _this.password = '',
        _this.sample = 'hello',
        _this.onSignup = function(){
            monaca.cloud.User.register(_this.username, _this.password)
            .done(function(result)
            {
                shared.userid = result.user._id;
                app.navi.replacePage('top.html',{animation:"none"});
            }
            )
            .fail(function(err)
            {
                ons.notification.alert({
                    title:'error',
                    message: err.message,
                    animation: 'none',
                });
            });
        },
        _this.onGoLogin = function(){
            app.navi.replacePage('login.html',{animation:"none"});
        };
        var _uuid = shared.uuid();

        shared.startup().then(
             function(res){ console.log(res); },
             function(res){ console.log(res); }
        );

    }])
    .controller('loginCtrl',['shared','$scope',function(shared,$scope){
        var _this=this;
        _this.username=_this.password='',
        _this.onLogin = function(){
            monaca.cloud.User.login(_this.username, _this.password)
            .done(function(result){
                shared.userid = result.user._id;
                app.navi.replacePage('top.html',{animation:"none"});
            })
            .fail(function(err)
            {
                ons.notification.alert({
                    title:'error',
                    message: err.message,
                    animation: 'none',
                });
            });
        },
        _this.onGoSignup = function(){
            app.navi.replacePage('signup.html',{"animation":"none"});
        };
    }])
    .controller('topCtrl',['shared','$scope',function(shared,$scope){
        var _this = this,
            _diary = monaca.cloud.Collection("idea"),
            _permission = {'public':'r'},
            _userid = null;

        _this.memo = 'ABC',
        _this.onRegister = function(){
            monaca.cloud.User.register("me@example.com", "password", {age:21})
            .done(function(result)
            {
                console.log("Welcome, " + result.user._username);
                console.log("You are " + result.user.age + " years old.");
                _userid = result.user._id;
            }
            )
            .fail(function(err)
            {
               console.log("Err#" + err.code +": " + err.message);
            });
/*
            monaca.cloud.User.validate("me@example.com")
            .done(function(result)
            {
                console.log("Validation passed!");
            })
            .fail(function(err)
            {
                console.log("Err#" + err.code +": " + err.message);
            });
*/
        },
        _this.onSave = function() {
            _userid = 'u144995e1-5941-4fff-8a25-eec91ac4570d';
            var _permission = {};
            _diary.insert({memo: _this.memo}, _permission)
            .done(function(result)
            {
               console.log("Inserted!");
            })
            .fail(function(err)
            {
               console.log("Err#" + err.code +": " + err.message);
            });
        };

        monaca.cloud.User.autoLogin()
        .done(function(result)
        {
            console.log("Hello again, " + result.user._username);
        })
        .fail(function(err)
        {
            console.log("Err#" + err.code +": " + err.message);
        });
    }])
    .controller('top2Ctrl',['shared','$http', '$scope',function(shared,$http,$scope){

//        console.log('topCtrl');

        var _this=this;
        shared.loadBooks();

        _this.getBooks = function() {
//            console.log('getBooks');
            return shared.getBooks();
        },
        _this.onBook = function(i) {
            shared.startQuestion(i);
            app.navi.pushPage('question.html');
        },
        _this.onDeleteBook = function(i,e){
//console.log(i);
            e.stopPropagation();
            var _books = shared.getBooks(),
                _book = _books[i];
            if (!_book) {
                return;
            }
            ons.notification.confirm({
                message: _book['title'] + 'を削除しますか？',
                // もしくは messageHTML: '
HTML形式のメッセージ
',
                title: '',
                buttonLabels: ['はい', 'いいえ'],
                animation: 'default', // もしくは'none'
                primaryButtonIndex: 1,
                cancelable: true,
                callback: function(index) {
                // -1: キャンセルされた
                // 0-: 左から0ではじまるボタン番号
                    if (index == 0) {
                        shared.removeBook(i);
                        shared.loadBooks();
                        $scope.$apply();
                    }
                }
            });
        },
        _this.onMenu = function(){
            var _dlg = 'top_menu_dialog.html';
            ons.createDialog(_dlg).then(function(dialog) {
                dialog.show();
            });
        },
        _this.goQuestion = function(){
            app.navi.pushPage('question.html');
        },
        _this.start = function(){
            shared.startQuestion();
            app.navi.pushPage('question.html');
        };
    }])
    .controller('topMenuDialogCtrl',['shared',function(shared){
        var _this=this;
        _this.goHowto=function(){
            app.topMenuDialog.hide();
            app.navi.pushPage('howto.html');
        },
        _this.goLoadSample=function(){
            app.topMenuDialog.hide();
            app.navi.pushPage('load_sample.html');
        },
        _this.goLoadUrl=function(){
            app.topMenuDialog.hide();
            app.navi.pushPage('load_url.html');
        };
    }])
    .controller('howtoCtrl',['shared','$http',function(shared,$http){
        var _this=this;
        $http.get('qa.txt',{
            params:{"t":(+new Date())},
            transformResponse:function(data){return data;}
        })
        .then(
            function(res){
                _this.data = res.data;
            });

    }])
    .controller('loadSampleCtrl',['shared','$scope',function(shared,$scope){
        var _this=this;
        _this.onLoadSample=function(url){
            shared.addBook(url).then(
                function(){
                    shared.loadBooks();
                    app.navi.popPage();
                },
                function(){
                    console.log('failed');
                    ons.notification.alert({
                        title:'', message: '読み込みに失敗しました',
                    });
                }
            );
        };
    }])
    .controller('loadUrlCtrl',['shared','$scope',function(shared,$scope){
        var _this=this;
        _this.url='',
        _this.onLoad=function(){
            shared.addBook(_this.url).then(
                function(){
                    shared.loadBooks();
                    app.navi.popPage();
                },
                function(){
                    ons.notification.alert({
                        title:'', message: '読み込みに失敗しました',
                    });
                }
            );
        };
    }])
    .controller('questionCtrl',['shared','$http', function(shared,$http){
        var _this=this;
        _this.q = "",
        _this.title='',
        _this.total=0,
        _this.choices = shared.choices,
        _this.displayQuestion=function(){
            var _que = shared.getQuestionDetail();
            if (_que) {
                _this.index = _que.index;
                _this.total = _que.total;
                _this.title = _que.title;
                _this.q = (_que.q || '').replace(/\n/g,'
');
            }
        },
        _this.goQuestion = function(){
            app.navi.pushPage('question.html');
        },
        _this.goAnswer = function(no){
            shared.setAnswer(no);
            ons.createDialog("answer_dialog.html").then(function(dlg) {
                dlg.on('prehide',function(e){
                    _this.next();
                });
                dlg.show();
            });
        },
        _this.goPass = function(){
            shared.setAnswer(0);
            _this.next();
        },
        _this.next = function(){
            if (shared.nextQuestion()){
                _this.displayQuestion();
            } else {
                app.navi.replacePage('result.html');
            };
        },
        _this.onExit = function(){
            ons.notification.confirm({
                message: '終了してもよろしいですか？',
                // もしくは messageHTML: '
HTML形式のメッセージ
',
                title: '',
                buttonLabels: ['はい', 'いいえ'],
                animation: 'default', // もしくは'none'
                primaryButtonIndex: 1,
                cancelable: true,
                callback: function(index) {
                // -1: キャンセルされた
                // 0-: 左から0ではじまるボタン番号
                    console.log(index);
                    if (index == 0) {
                        app.navi.replacePage('result.html');
                    }
                }
            });
        },
        _this.show = function(dlg) {
            ons.createDialog(dlg).then(function(dialog) {
                dialog.show();
            });
        };
        _this.displayQuestion();
    }])
    .controller('answerDialogCtrl',['shared',function(shared){
        var _this=this;
        _this.isCorrect = shared.isCorrect();
    }])
    .controller('questionMenuDialogCtrl',['shared',function(shared){
        var _this=this;
        _this.goFinish=function(){
            app.questionMenuDialog.hide();
            app.navi.replacePage('result.html');
        };
    }])
    .controller('resultCtrl', ['shared',function(shared){
        var _this=this;
        _this.correctTotal = shared.getCorrectTotal(),
        _this.total = shared.questions.length,
        _this.goTop = function(){
            app.navi.replacePage('top.html');
        };

        shared.updateBookResult({
            'time' : (+ new Date()),
            'total': _this.total,
            'correctTotal':_this.correctTotal
        });
    }]);

})();
<commit_msg>Update controller.js<commit_after>(function(){
    'use strict';

    angular.module("controllerModule", [])
    .controller('firstCtrl',['shared','$scope',function(shared,$scope){
        var _this=this;
        _this.loading = true,
        _this.onStartup = function(){
            _this.loading = true;
            shared.startup().then(
                function(res){
                     app.navi.replacePage('top.html',{animation:"none"});
                },
                function(err){_this.loading=false;$scope.$apply();}
            );
        };
        _this.onStartup();
    }])
    .controller('topCtrl',['shared',function(shared){
    }])
    .controller('signupCtrl',['shared','$scope',function(shared,$scope){
        console.log('signupCtrl');
        var _this=this;
        _this.username = _this.password = '',
        _this.sample = 'hello',
        _this.onSignup = function(){
            monaca.cloud.User.register(_this.username, _this.password)
            .done(function(result)
            {
                shared.userid = result.user._id;
                app.navi.replacePage('top.html',{animation:"none"});
            }
            )
            .fail(function(err)
            {
                ons.notification.alert({
                    title:'error',
                    message: err.message,
                    animation: 'none',
                });
            });
        },
        _this.onGoLogin = function(){
            app.navi.replacePage('login.html',{animation:"none"});
        };
        var _uuid = shared.uuid();

        shared.startup().then(
             function(res){ console.log(res); },
             function(res){ console.log(res); }
        );

        ons.ready(function(){
           console.log('ons.ready2');
           monaca.getDeviceId(function(id){
            console.log('id:'+id);
               _this.sample = id;
               $scope.$apply();
           });
        });

    }])
    .controller('loginCtrl',['shared','$scope',function(shared,$scope){
        var _this=this;
        _this.username=_this.password='',
        _this.onLogin = function(){
            monaca.cloud.User.login(_this.username, _this.password)
            .done(function(result){
                shared.userid = result.user._id;
                app.navi.replacePage('top.html',{animation:"none"});
            })
            .fail(function(err)
            {
                ons.notification.alert({
                    title:'error',
                    message: err.message,
                    animation: 'none',
                });
            });
        },
        _this.onGoSignup = function(){
            app.navi.replacePage('signup.html',{"animation":"none"});
        };
    }])
    .controller('top2Ctrl',['shared','$scope',function(shared,$scope){
        var _this = this,
            _diary = monaca.cloud.Collection("idea"),
            _permission = {'public':'r'},
            _userid = null;

        _this.memo = 'ABC',
        _this.onRegister = function(){
            monaca.cloud.User.register("me@example.com", "password", {age:21})
            .done(function(result)
            {
                console.log("Welcome, " + result.user._username);
                console.log("You are " + result.user.age + " years old.");
                _userid = result.user._id;
            }
            )
            .fail(function(err)
            {
               console.log("Err#" + err.code +": " + err.message);
            });
/*
            monaca.cloud.User.validate("me@example.com")
            .done(function(result)
            {
                console.log("Validation passed!");
            })
            .fail(function(err)
            {
                console.log("Err#" + err.code +": " + err.message);
            });
*/
        },
        _this.onSave = function() {
            _userid = 'u144995e1-5941-4fff-8a25-eec91ac4570d';
            var _permission = {};
            _diary.insert({memo: _this.memo}, _permission)
            .done(function(result)
            {
               console.log("Inserted!");
            })
            .fail(function(err)
            {
               console.log("Err#" + err.code +": " + err.message);
            });
        };

        monaca.cloud.User.autoLogin()
        .done(function(result)
        {
            console.log("Hello again, " + result.user._username);
        })
        .fail(function(err)
        {
            console.log("Err#" + err.code +": " + err.message);
        });
    }])
    .controller('top2Ctrl',['shared','$http', '$scope',function(shared,$http,$scope){

//        console.log('topCtrl');

        var _this=this;
        shared.loadBooks();

        _this.getBooks = function() {
//            console.log('getBooks');
            return shared.getBooks();
        },
        _this.onBook = function(i) {
            shared.startQuestion(i);
            app.navi.pushPage('question.html');
        },
        _this.onDeleteBook = function(i,e){
//console.log(i);
            e.stopPropagation();
            var _books = shared.getBooks(),
                _book = _books[i];
            if (!_book) {
                return;
            }
            ons.notification.confirm({
                message: _book['title'] + 'を削除しますか？',
                // もしくは messageHTML: '
HTML形式のメッセージ
',
                title: '',
                buttonLabels: ['はい', 'いいえ'],
                animation: 'default', // もしくは'none'
                primaryButtonIndex: 1,
                cancelable: true,
                callback: function(index) {
                // -1: キャンセルされた
                // 0-: 左から0ではじまるボタン番号
                    if (index == 0) {
                        shared.removeBook(i);
                        shared.loadBooks();
                        $scope.$apply();
                    }
                }
            });
        },
        _this.onMenu = function(){
            var _dlg = 'top_menu_dialog.html';
            ons.createDialog(_dlg).then(function(dialog) {
                dialog.show();
            });
        },
        _this.goQuestion = function(){
            app.navi.pushPage('question.html');
        },
        _this.start = function(){
            shared.startQuestion();
            app.navi.pushPage('question.html');
        };
    }])
    .controller('topMenuDialogCtrl',['shared',function(shared){
        var _this=this;
        _this.goHowto=function(){
            app.topMenuDialog.hide();
            app.navi.pushPage('howto.html');
        },
        _this.goLoadSample=function(){
            app.topMenuDialog.hide();
            app.navi.pushPage('load_sample.html');
        },
        _this.goLoadUrl=function(){
            app.topMenuDialog.hide();
            app.navi.pushPage('load_url.html');
        };
    }])
    .controller('howtoCtrl',['shared','$http',function(shared,$http){
        var _this=this;
        $http.get('qa.txt',{
            params:{"t":(+new Date())},
            transformResponse:function(data){return data;}
        })
        .then(
            function(res){
                _this.data = res.data;
            });

    }])
    .controller('loadSampleCtrl',['shared','$scope',function(shared,$scope){
        var _this=this;
        _this.onLoadSample=function(url){
            shared.addBook(url).then(
                function(){
                    shared.loadBooks();
                    app.navi.popPage();
                },
                function(){
                    console.log('failed');
                    ons.notification.alert({
                        title:'', message: '読み込みに失敗しました',
                    });
                }
            );
        };
    }])
    .controller('loadUrlCtrl',['shared','$scope',function(shared,$scope){
        var _this=this;
        _this.url='',
        _this.onLoad=function(){
            shared.addBook(_this.url).then(
                function(){
                    shared.loadBooks();
                    app.navi.popPage();
                },
                function(){
                    ons.notification.alert({
                        title:'', message: '読み込みに失敗しました',
                    });
                }
            );
        };
    }])
    .controller('questionCtrl',['shared','$http', function(shared,$http){
        var _this=this;
        _this.q = "",
        _this.title='',
        _this.total=0,
        _this.choices = shared.choices,
        _this.displayQuestion=function(){
            var _que = shared.getQuestionDetail();
            if (_que) {
                _this.index = _que.index;
                _this.total = _que.total;
                _this.title = _que.title;
                _this.q = (_que.q || '').replace(/\n/g,'
');
            }
        },
        _this.goQuestion = function(){
            app.navi.pushPage('question.html');
        },
        _this.goAnswer = function(no){
            shared.setAnswer(no);
            ons.createDialog("answer_dialog.html").then(function(dlg) {
                dlg.on('prehide',function(e){
                    _this.next();
                });
                dlg.show();
            });
        },
        _this.goPass = function(){
            shared.setAnswer(0);
            _this.next();
        },
        _this.next = function(){
            if (shared.nextQuestion()){
                _this.displayQuestion();
            } else {
                app.navi.replacePage('result.html');
            };
        },
        _this.onExit = function(){
            ons.notification.confirm({
                message: '終了してもよろしいですか？',
                // もしくは messageHTML: '
HTML形式のメッセージ
',
                title: '',
                buttonLabels: ['はい', 'いいえ'],
                animation: 'default', // もしくは'none'
                primaryButtonIndex: 1,
                cancelable: true,
                callback: function(index) {
                // -1: キャンセルされた
                // 0-: 左から0ではじまるボタン番号
                    console.log(index);
                    if (index == 0) {
                        app.navi.replacePage('result.html');
                    }
                }
            });
        },
        _this.show = function(dlg) {
            ons.createDialog(dlg).then(function(dialog) {
                dialog.show();
            });
        };
        _this.displayQuestion();
    }])
    .controller('answerDialogCtrl',['shared',function(shared){
        var _this=this;
        _this.isCorrect = shared.isCorrect();
    }])
    .controller('questionMenuDialogCtrl',['shared',function(shared){
        var _this=this;
        _this.goFinish=function(){
            app.questionMenuDialog.hide();
            app.navi.replacePage('result.html');
        };
    }])
    .controller('resultCtrl', ['shared',function(shared){
        var _this=this;
        _this.correctTotal = shared.getCorrectTotal(),
        _this.total = shared.questions.length,
        _this.goTop = function(){
            app.navi.replacePage('top.html');
        };

        shared.updateBookResult({
            'time' : (+ new Date()),
            'total': _this.total,
            'correctTotal':_this.correctTotal
        });
    }]);

})();
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { FormattedHTMLMessage, FormattedMessage } from 'react-intl';

class MediaChecklist extends Component {
  render() {
    return (

<FormattedMessage id="mediaChecklist.heading" defaultMessage="Verification checklist" />

<FormattedMessage id="mediaChecklist.instructions" defaultMessage="Here are some common steps in collaborative media verification. Complete as many tasks as you can so we have a complete, transparent record of our investigation." />

<FormattedMessage id="mediaChecklist.headingWho" defaultMessage="Who" />

            <FormattedHTMLMessage id="mediaChecklist.messageWho" defaultMessage="Who’s the contact? Indicate information like @username and Email or Phone" />.

<FormattedMessage id="mediaChecklist.headingWhat" defaultMessage="What" />

            <FormattedMessage id="mediaChecklist.messageWhat" defaultMessage="What’s the issue? Clearly explain which facts are in question." />

<FormattedMessage id="mediaChecklist.headingWhere" defaultMessage="Where" />

            <FormattedMessage id="mediaChecklist.messageWhere" defaultMessage="Where’s the location? Indicate specific city names and regions." />

<FormattedMessage id="mediaChecklist.headingWhen" defaultMessage="When" />

            <FormattedHTMLMessage id="mediaChecklist.messageWhen" defaultMessage="When did it happen? Include a timestamp with time zone, like 9/11/2016 HH:MM PM EST." />

<FormattedMessage id="mediaChecklist.headingOriginal" defaultMessage="Original" />

            <FormattedHTMLMessage id="mediaChecklist.messageOriginal" defaultMessage="Is this just a retweet? Indicate Is original or Is not original or Unsure." />

<FormattedMessage id="mediaChecklist.headingDetails" defaultMessage="Details" />

            <FormattedMessage id="mediaChecklist.messageDetails" defaultMessage="Anything else? Indicate additional info including social media exchanges or interviews." />

    );
  }
}

export default MediaChecklist;
<commit_msg>Fixes lost space between h4 and FormattedMessage. #5624<commit_after>import React, { Component, PropTypes } from 'react';
import { FormattedHTMLMessage, FormattedMessage } from 'react-intl';

class MediaChecklist extends Component {
  render() {
    return (

<FormattedMessage id="mediaChecklist.heading" defaultMessage="Verification checklist" />

<FormattedMessage id="mediaChecklist.instructions" defaultMessage="Here are some common steps in collaborative media verification. Complete as many tasks as you can so we have a complete, transparent record of our investigation." />

<FormattedMessage id="mediaChecklist.headingWho" defaultMessage="Who" />

            <FormattedHTMLMessage id="mediaChecklist.messageWho" defaultMessage="Who’s the contact? Indicate information like @username and Email or Phone" />.

<FormattedMessage id="mediaChecklist.headingWhat" defaultMessage="What" />

            <FormattedMessage id="mediaChecklist.messageWhat" defaultMessage="What’s the issue? Clearly explain which facts are in question." />

<FormattedMessage id="mediaChecklist.headingWhere" defaultMessage="Where" />

            <FormattedMessage id="mediaChecklist.messageWhere" defaultMessage="Where’s the location? Indicate specific city names and regions." />

<FormattedMessage id="mediaChecklist.headingWhen" defaultMessage="When" />

            <FormattedHTMLMessage id="mediaChecklist.messageWhen" defaultMessage="When did it happen? Include a timestamp with time zone, like 9/11/2016 HH:MM PM EST." />

<FormattedMessage id="mediaChecklist.headingOriginal" defaultMessage="Original" />

            <FormattedHTMLMessage id="mediaChecklist.messageOriginal" defaultMessage="Is this just a retweet? Indicate Is original or Is not original or Unsure." />

<FormattedMessage id="mediaChecklist.headingDetails" defaultMessage="Details" />

            <FormattedMessage id="mediaChecklist.messageDetails" defaultMessage="Anything else? Indicate additional info including social media exchanges or interviews." />

    );
  }
}

export default MediaChecklist;
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import PropTypes from 'prop-types';
import {submitConfigure} from '../../actions/configure';
import {Button} from 'reactstrap';
import {ComponentWithError} from '../components/ComponentWithError';

class ConfigureMetadataComponent extends Component {
  static propTypes = {
    defaultMetadataUrl: PropTypes.string.isRequired,
    errorMessage: PropTypes.string,
    redirect: PropTypes.string,
    submitConfigure: PropTypes.func.isRequired,
    urlGroupClass: PropTypes.string,
    nameGroupClass: PropTypes.string,
  };

  state = {
    metadataUrl: '',
  };

  componentDidMount() {
    this.setState({
      metadataUrl: this.props.defaultMetadataUrl,
    });
  }

  componentDidUpdate() {
    if (this.props.redirect) {
      document.location.replace(this.props.redirect);
    }
  }

  handleInputChange = ({target: {name, value}}) => {
    this.setState({
      [name]: value,
    });
  };

  handleSubmit = (event) => {
    event.preventDefault();
    const {metadataUrl,profileName} = this.state;
    const payload = {
      metadataUrl,
      profileName,
    };

    this.props.submitConfigure(payload);
  };

  handleKeyDown = (event) => event.keyCode === 13 && this.handleSubmit(event);

  render() {
    return (
      <fieldset>
        <legend>Configure</legend>
        {this.props.errorMessage}

          SAML Metadata URL
          <input
            className="form-control"
            id="metadataUrl"
            name="metadataUrl"
            onChange={this.handleInputChange}
            onKeyDown={this.handleKeyDown}
            pattern="https://.+"
            required
            type="url"
            value={this.state.metadataUrl}
          />

          SAML Metadata URL
          Account Alias
          <input
            className="form-control"
            id="profileName"
            name="profileName"
            onChange={this.handleInputChange}
            onKeyDown={this.handleKeyDown}
            pattern=".+"
            type="string"
          />

        <Button
          color="primary"
          onClick={this.handleSubmit}
          outline
        >
          Done
        </Button>
      </fieldset>
    );
  }
}

const mapStateToProps = ({configure}, ownProps) => ({
  ...configure.submitFailure,
  ...configure.submitSuccess,
  ...ownProps,
});

const mapDispatchToProps = (dispatch) => ({
  submitConfigure: bindActionCreators(submitConfigure, dispatch),
});

export const ConfigureMetadata = connect(
  mapStateToProps,
  mapDispatchToProps
)(ComponentWithError(ConfigureMetadataComponent));
<commit_msg>remove duplicate label<commit_after>import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import PropTypes from 'prop-types';
import {submitConfigure} from '../../actions/configure';
import {Button} from 'reactstrap';
import {ComponentWithError} from '../components/ComponentWithError';

class ConfigureMetadataComponent extends Component {
  static propTypes = {
    defaultMetadataUrl: PropTypes.string.isRequired,
    errorMessage: PropTypes.string,
    redirect: PropTypes.string,
    submitConfigure: PropTypes.func.isRequired,
    urlGroupClass: PropTypes.string,
    nameGroupClass: PropTypes.string,
  };

  state = {
    metadataUrl: '',
  };

  componentDidMount() {
    this.setState({
      metadataUrl: this.props.defaultMetadataUrl,
    });
  }

  componentDidUpdate() {
    if (this.props.redirect) {
      document.location.replace(this.props.redirect);
    }
  }

  handleInputChange = ({target: {name, value}}) => {
    this.setState({
      [name]: value,
    });
  };

  handleSubmit = (event) => {
    event.preventDefault();
    const {metadataUrl,profileName} = this.state;
    const payload = {
      metadataUrl,
      profileName,
    };

    this.props.submitConfigure(payload);
  };

  handleKeyDown = (event) => event.keyCode === 13 && this.handleSubmit(event);

  render() {
    return (
      <fieldset>
        <legend>Configure</legend>
        {this.props.errorMessage}

          SAML Metadata URL
          <input
            className="form-control"
            id="metadataUrl"
            name="metadataUrl"
            onChange={this.handleInputChange}
            onKeyDown={this.handleKeyDown}
            pattern="https://.+"
            required
            type="url"
            value={this.state.metadataUrl}
          />

          Account Alias
          <input
            className="form-control"
            id="profileName"
            name="profileName"
            onChange={this.handleInputChange}
            onKeyDown={this.handleKeyDown}
            pattern=".+"
            type="string"
          />

        <Button
          color="primary"
          onClick={this.handleSubmit}
          outline
        >
          Done
        </Button>
      </fieldset>
    );
  }
}

const mapStateToProps = ({configure}, ownProps) => ({
  ...configure.submitFailure,
  ...configure.submitSuccess,
  ...ownProps,
});

const mapDispatchToProps = (dispatch) => ({
  submitConfigure: bindActionCreators(submitConfigure, dispatch),
});

export const ConfigureMetadata = connect(
  mapStateToProps,
  mapDispatchToProps
)(ComponentWithError(ConfigureMetadataComponent));
<|endoftext|>


<commit_before>(function(TL, TM, TLM, STS) {

  //----------------------------------------------------------------------------
  // general use

  function appearVSlide(container, time, completeCB)
  {
    time || (time = 0.4);

    TL.set(container[0], { overflow: 'hidden', display: 'block', height: 0 });

    TL.to(container[0], time, {height: measureH(container), opacity: 1, onComplete: function(e) {
      container.css({
        height: 'auto'
      });
      if (completeCB) {
        completeCB.apply(this, arguments);
      }
    }});
  }

  function hideVSlide(container, time, completedCB)
  {
    time || (time = 0.4);

    TL.set(container[0], { overflow: 'hidden', display: 'block', height: container.height() });

    TL.to(container[0], time, {opacity: 0, height: 0, onComplete: function(e) {
      container.css({
        display: 'none',
        height: 0
      });
    }});
  }

  function scrollToEl(el, time, completedCB)
  {
    TM.to(window, time || 0.3, {
      scrollTo : { y: el.offset().top, autoKill:true },
      ease: Power1.easeOut,
      onComplete : completedCB
    });
  }

  //----------------------------------------------------------------------------
  // map

  function mapEnter(mapDOM)
  {
    mapEnterTween = new TimelineMax({pause: true})
      .to(mapDOM, 0, {opacity: 0, transform: "rotateY(-90deg)"})
      .to(mapDOM, 1.25, {opacity: 1, transform: "rotateY(0) scale(" + STS.CampaignMap.getContainerScale(mapDOM) + ")"});

    return mapEnterTween;
  }

  //----------------------------------------------------------------------------
  // map electorates

  var runningMapTweens = [];

  function pingElectorate(layer, color, intensity, completedCB)
  {
    intensity = Math.max(intensity, 10) / 10;  // clamp size of pulses

    // bring to front
    layer.bringToFront();

    var shapeData = STS.CampaignMap.getGeoJSONShape(layer);
    var g = shapeData[0];
    var $paths = shapeData[1];

    var currentAttrs;

    // abort any running animations on this electorate and read stateless attributes to finish on
    for (var i = 0, l = runningMapTweens.length, running; i < l && (running = runningMapTweens[i]); ++i) {
      if (running[0] === g) {
        running[1].kill();
        currentAttrs = running[2];
        runningMapTweens.splice(i, 1);
        break;
      }
    }

    // read current attributes if we're not doing anything yet
    if (!currentAttrs) {
      currentAttrs = [
        ['stroke-width', 'strokeWidth'], ['stroke', 'stroke'], ['stroke-opacity', 'strokeOpacity'], ['fill', 'fill'], ['fill-opacity', 'fillOpacity']
      ].reduce(function(attrs, at) {
        attrs[at[1]] = $paths.attr(at[0]);
        return attrs;
      }, {});
    }

    var newTimeline = new TLM({ onComplete: completedCB || function() {} });

    newTimeline.to($paths, 0.1, {
      'strokeWidth': '5px',
      'stroke': color,
      'fill': color,
      'fillOpacity': 0.2 + (0.8 * intensity),
      'strokeOpacity': 0.2 + (0.8 * intensity),
      ease: Power1.easeOut
    }).to($paths, 0.5, currentAttrs);

    runningMapTweens.push([g, newTimeline, currentAttrs]);
  }

  //----------------------------------------------------------------------------

  // export our anims into app namespace
  STS.anim = {
    appearVSlide : appearVSlide,
    hideVSlide : hideVSlide,
    scrollToEl : scrollToEl,

    map : {
      enter : mapEnter,
      notifyElectorate: pingElectorate
    }
  };

})(TweenLite, TweenMax, TimelineMax, STS);
<commit_msg>simple fade-in for stats map<commit_after>(function(TL, TM, TLM, STS) {

  //----------------------------------------------------------------------------
  // general use

  function appearVSlide(container, time, completeCB)
  {
    time || (time = 0.4);

    TL.set(container[0], { overflow: 'hidden', display: 'block', height: 0 });

    TL.to(container[0], time, {height: measureH(container), opacity: 1, onComplete: function(e) {
      container.css({
        height: 'auto'
      });
      if (completeCB) {
        completeCB.apply(this, arguments);
      }
    }});
  }

  function hideVSlide(container, time, completedCB)
  {
    time || (time = 0.4);

    TL.set(container[0], { overflow: 'hidden', display: 'block', height: container.height() });

    TL.to(container[0], time, {opacity: 0, height: 0, onComplete: function(e) {
      container.css({
        display: 'none',
        height: 0
      });
    }});
  }

  function scrollToEl(el, time, completedCB)
  {
    TM.to(window, time || 0.3, {
      scrollTo : { y: el.offset().top, autoKill:true },
      ease: Power1.easeOut,
      onComplete : completedCB
    });
  }

  //----------------------------------------------------------------------------
  // map

  function mapEnter(mapDOM)
  {
    mapEnterTween = new TimelineMax({pause: true})
      .to(mapDOM, 0, {opacity: 0, transform: "rotateY(0) scale(" + STS.CampaignMap.getContainerScale(mapDOM) + ")"})
      .to(mapDOM, 1.25, {opacity: 0.3});

    return mapEnterTween;
  }

  //----------------------------------------------------------------------------
  // map electorates

  var runningMapTweens = [];

  function pingElectorate(layer, color, intensity, completedCB)
  {
    intensity = Math.max(intensity, 10) / 10;  // clamp size of pulses

    // bring to front
    layer.bringToFront();

    var shapeData = STS.CampaignMap.getGeoJSONShape(layer);
    var g = shapeData[0];
    var $paths = shapeData[1];

    var currentAttrs;

    // abort any running animations on this electorate and read stateless attributes to finish on
    for (var i = 0, l = runningMapTweens.length, running; i < l && (running = runningMapTweens[i]); ++i) {
      if (running[0] === g) {
        running[1].kill();
        currentAttrs = running[2];
        runningMapTweens.splice(i, 1);
        break;
      }
    }

    // read current attributes if we're not doing anything yet
    if (!currentAttrs) {
      currentAttrs = [
        ['stroke-width', 'strokeWidth'], ['stroke', 'stroke'], ['stroke-opacity', 'strokeOpacity'], ['fill', 'fill'], ['fill-opacity', 'fillOpacity']
      ].reduce(function(attrs, at) {
        attrs[at[1]] = $paths.attr(at[0]);
        return attrs;
      }, {});
    }

    var newTimeline = new TLM({ onComplete: completedCB || function() {} });

    newTimeline.to($paths, 0.1, {
      'strokeWidth': '5px',
      'stroke': color,
      'fill': color,
      'fillOpacity': 0.2 + (0.8 * intensity),
      'strokeOpacity': 0.2 + (0.8 * intensity),
      ease: Power1.easeOut
    }).to($paths, 0.5, currentAttrs);

    runningMapTweens.push([g, newTimeline, currentAttrs]);
  }

  //----------------------------------------------------------------------------

  // export our anims into app namespace
  STS.anim = {
    appearVSlide : appearVSlide,
    hideVSlide : hideVSlide,
    scrollToEl : scrollToEl,

    map : {
      enter : mapEnter,
      notifyElectorate: pingElectorate
    }
  };

})(TweenLite, TweenMax, TimelineMax, STS);
<|endoftext|>


<commit_before>'use strict';

var ensureArray  = require('es5-ext/array/valid-array')
  , ensureObject = require('es5-ext/object/valid-object')
  , generateId   = require('dom-ext/html-document/generate-id');

var generateTableBody = function (rows, master) {
	return rows.map(function (row) {
		return tr(th(row.label, span({ class: 'hint' }, row.inputHint)),
			list(row.paths, function (path) {
				var resolved = master.resolveSKeyPath(path);
				return td(
					input({ id: 'matrix-display-input-' + path,
						dbjs: resolved.observable, required: false })
				);
			}),
			td({ id: row.totalId }));
	});
};

module.exports = function (config) {
	var horizontalTotal, horizontalTotals = [], verticalTotals = [], totalId,
		rows, columnLabels, lastRowLabel, tableId, master, formId;
	ensureObject(config);
	rows         = ensureArray(config.rows);
	columnLabels = ensureArray(config.columnLabels);
	lastRowLabel = config.lastRowLabel;
	master       = ensureObject(config.master);
	tableId      = config.tableId || generateId();
	formId       = config.formId;

	totalId = generateId('total');
	//vertical totals
	rows.forEach(function (row) {
		var verticalTotal = {
			totalId: generateId('total'),
			paths: row.paths
		};
		verticalTotals.push(verticalTotal);
		row.totalId = verticalTotal.totalId;
	});
	//horizontal totals
	rows[0].paths.forEach(function (path, index) {
		horizontalTotal = {
			totalId: generateId('total'),
			paths: []
		};
		rows.forEach(function (row) {
			horizontalTotal.paths.push(row.paths[index]);
		});
		horizontalTotals.push(horizontalTotal);
	});

	return table({ id: tableId },
		thead(tr(
			th(),
			list(columnLabels, function (label) {
				return th(label);
			})
		)),
		tbody(generateTableBody(rows, master)),
		tfoot(tr(
			th(lastRowLabel),
			list(horizontalTotals, function (horizontalTotal) {
				return td({ id: horizontalTotal.totalId });
			}),
			td({ id: totalId })
		)),

		script(function (formId, horizontalTotals, verticalTotals, totalId) {
			var form = $(formId), totals = [], fullTotal = { total: $(totalId), subTotals: [] };
			$.forEach(horizontalTotals.concat(verticalTotals), function (total) {
				totals.push({
					total: $(total.totalId),
					subTotals: total.paths.map(function (path) {
						return $('matrix-display-input-' + path);
					})
				});
			});
			$.forEach(verticalTotals, function (total) {
				fullTotal.subTotals = fullTotal.subTotals.concat(total.paths.map(function (path) {
					return $('matrix-display-input-' + path);
				}));
			});
			totals.push(fullTotal);

			$.onEnvUpdate(form, function () {
				$.forEach(totals, function (total) {
					var sum = 0;
					$.forEach(total.subTotals, function (subTotal) {
						sum += (subTotal.value ? Number(subTotal.value) : 0);
					});
					total.total.innerText = sum.toLocaleString();
				});
			});
		}, formId, horizontalTotals, verticalTotals, totalId));
};
<commit_msg>#1500 used $.forEach instead of map in legacy<commit_after>'use strict';

var ensureArray  = require('es5-ext/array/valid-array')
  , ensureObject = require('es5-ext/object/valid-object')
  , generateId   = require('dom-ext/html-document/generate-id');

var generateTableBody = function (rows, master) {
	return rows.map(function (row) {
		return tr(th(row.label, span({ class: 'hint' }, row.inputHint)),
			list(row.paths, function (path) {
				var resolved = master.resolveSKeyPath(path);
				return td(
					input({ id: 'matrix-display-input-' + path,
						dbjs: resolved.observable, required: false })
				);
			}),
			td({ id: row.totalId }));
	});
};

module.exports = function (config) {
	var horizontalTotal, horizontalTotals = [], verticalTotals = [], totalId,
		rows, columnLabels, lastRowLabel, tableId, master, formId;
	ensureObject(config);
	rows         = ensureArray(config.rows);
	columnLabels = ensureArray(config.columnLabels);
	lastRowLabel = config.lastRowLabel;
	master       = ensureObject(config.master);
	tableId      = config.tableId || generateId();
	formId       = config.formId;

	totalId = generateId('total');
	//vertical totals
	rows.forEach(function (row) {
		var verticalTotal = {
			totalId: generateId('total'),
			paths: row.paths
		};
		verticalTotals.push(verticalTotal);
		row.totalId = verticalTotal.totalId;
	});
	//horizontal totals
	rows[0].paths.forEach(function (path, index) {
		horizontalTotal = {
			totalId: generateId('total'),
			paths: []
		};
		rows.forEach(function (row) {
			horizontalTotal.paths.push(row.paths[index]);
		});
		horizontalTotals.push(horizontalTotal);
	});

	return table({ id: tableId },
		thead(tr(
			th(),
			list(columnLabels, function (label) {
				return th(label);
			})
		)),
		tbody(generateTableBody(rows, master)),
		tfoot(tr(
			th(lastRowLabel),
			list(horizontalTotals, function (horizontalTotal) {
				return td({ id: horizontalTotal.totalId });
			}),
			td({ id: totalId })
		)),

		script(function (formId, horizontalTotals, verticalTotals, totalId) {
			var form = $(formId), totals = [], fullTotal = { total: $(totalId), subTotals: [] };
			$.forEach(horizontalTotals.concat(verticalTotals), function (total) {
				var subTotatals = [];
				$.forEach(total.paths, function (path) {
					subTotatals.push($('matrix-display-input-' + path));
				});
				totals.push({
					total: $(total.totalId),
					subTotals: subTotatals
				});
			});
			$.forEach(verticalTotals, function (total) {
				var subTotatals = [];
				$.forEach(total.paths, function (path) {
					subTotatals.push($('matrix-display-input-' + path));
				});
				fullTotal.subTotals = fullTotal.subTotals.concat(subTotatals);
			});
			totals.push(fullTotal);

			$.onEnvUpdate(form, function () {
				$.forEach(totals, function (total) {
					var sum = 0;
					$.forEach(total.subTotals, function (subTotal) {
						sum += (subTotal.value ? Number(subTotal.value) : 0);
					});
					total.total.innerText = sum.toLocaleString();
				});
			});
		}, formId, horizontalTotals, verticalTotals, totalId));
};
<|endoftext|>


<commit_before>'use strict';

var Geometry = require('../../util/Geometry'),
    BendpointUtil = require('./BendpointUtil'),
    LayoutUtil = require('../../layout/LayoutUtil');

var MARKER_CONNECT_HOVER = 'connect-hover',
    MARKER_CONNECT_UPDATING = 'djs-updating';

function axisAdd(point, axis, delta) {
  return axisSet(point, axis, point[axis] + delta);
}

function axisSet(point, axis, value) {
  return {
    x: (axis === 'x' ? value : point.x),
    y: (axis === 'y' ? value : point.y)
  };
}

function flipAxis(axis) {
  return axis === 'x' ? 'y' : 'x';
}

/**
 * Get the docking point on the given element.
 *
 * Compute a reasonable docking, if non exists.
 *
 * @param  {Point} point
 * @param  {djs.model.Shape} referenceElement
 * @param  {String} moveAxis (x|y)
 *
 * @return {Point}
 */
function getDocking(point, referenceElement, moveAxis) {

  var referenceMid,
      inverseAxis;

  if (point.original) {
    return point.original;
  } else {
    referenceMid = LayoutUtil.getMid(referenceElement);
    inverseAxis = flipAxis(moveAxis);

    return axisSet(point, inverseAxis, referenceMid[inverseAxis]);
  }
}

/**
 * A component that implements moving of bendpoints
 */
function ConnectionSegmentMove(injector, eventBus, canvas, dragging, graphicsFactory, rules, modeling) {

  // optional connection docking integration
  var connectionDocking = injector.get('connectionDocking', false);

  // API

  this.start = function(event, connection, idx) {

    var context,
        gfx = canvas.getGraphics(connection),
        segmentStartIndex = idx - 1,
        segmentEndIndex = idx,
        waypoints = connection.waypoints,
        segmentStart = waypoints[segmentStartIndex],
        segmentEnd = waypoints[segmentEndIndex],
        direction,
        axis;

    direction = Geometry.pointsAligned(segmentStart, segmentEnd);

    // do not move diagonal connection
    if (!direction) {
      return;
    }

    // the axis where we are going to move things
    axis = direction === 'v' ? 'y' : 'x';

    if (segmentStartIndex === 0) {
      segmentStart = getDocking(segmentStart, connection.source, axis);
    }

    if (segmentEndIndex === waypoints.length - 1) {
      segmentEnd = getDocking(segmentEnd, connection.target, axis);
    }

    context = {
      connection: connection,
      segmentStartIndex: segmentStartIndex,
      segmentEndIndex: segmentEndIndex,
      segmentStart: segmentStart,
      segmentEnd: segmentEnd,
      axis: axis
    };

    dragging.activate(event, 'connectionSegment.move', {
      cursor: axis === 'x' ? 'resize-ew' : 'resize-ns',
      data: {
        connection: connection,
        connectionGfx: gfx,
        context: context
      }
    });
  };

  // DRAGGING IMPLEMENTATION

  function redrawConnection(data) {
    graphicsFactory.update('connection', data.connection, data.connectionGfx);
  }

  function filterRedundantWaypoints(waypoints) {
    return waypoints.filter(function(r, idx) {
      return !Geometry.pointsOnLine(waypoints[idx - 1], waypoints[idx + 1], r);
    });
  }

  eventBus.on('connectionSegment.move.start', function(e) {

    var context = e.context,
        connection = e.connection,
        layer = canvas.getLayer('overlays');

    context.originalWaypoints = connection.waypoints.slice();

    // add dragger gfx
    context.draggerGfx = BendpointUtil.addSegmentDragger(layer, context.segmentStart, context.segmentEnd);
    context.draggerGfx.addClass('djs-dragging');

    canvas.addMarker(connection, MARKER_CONNECT_UPDATING);
  });

  eventBus.on('connectionSegment.move.move', function(e) {

    var context = e.context,
        connection = context.connection,
        segmentStartIndex = context.segmentStartIndex,
        segmentEndIndex = context.segmentEndIndex,
        segmentStart = context.segmentStart,
        segmentEnd = context.segmentEnd,
        axis = context.axis;

    var newWaypoints = context.originalWaypoints.slice(),
        newSegmentStart = axisAdd(segmentStart, axis, e['d' + axis]),
        newSegmentEnd = axisAdd(segmentEnd, axis, e['d' + axis]);

    var waypointCount = newWaypoints.length;

    // move segment start / end by axis delta
    newWaypoints[segmentStartIndex] = newSegmentStart;
    newWaypoints[segmentEndIndex] = newSegmentEnd;

    var sourceToSegmentOrientation,
        targetToSegmentOrientation;

    // handle first segment
    if (segmentStartIndex < 2) {
      sourceToSegmentOrientation = LayoutUtil.getOrientation(connection.source, newSegmentStart);

      // first bendpoint, remove first segment if intersecting
      if (segmentStartIndex === 1) {

        if (sourceToSegmentOrientation === 'intersect') {
          newWaypoints.shift();
          newWaypoints[0] = newSegmentStart;
        }
      }

      // docking point, add segment if not intersecting anymore
      else {
        if (sourceToSegmentOrientation !== 'intersect') {
          newWaypoints.unshift(segmentStart);
        }
      }
    }

    // handle last segment
    if (segmentEndIndex > waypointCount - 3) {
      targetToSegmentOrientation = LayoutUtil.getOrientation(connection.target, newSegmentEnd);

      // last bendpoint, remove last segment if intersecting
      if (segmentEndIndex === waypointCount - 2) {

        if (targetToSegmentOrientation === 'intersect') {
          newWaypoints.pop();
          newWaypoints[newWaypoints.length - 1] = newSegmentEnd;
        }
      }

      // last bendpoint, remove last segment if intersecting
      else {
        if (targetToSegmentOrientation !== 'intersect') {
          newWaypoints.push(segmentEnd);
        }
      }
    }

    // update connection waypoints
    connection.waypoints = newWaypoints;

    // crop connection, if docking service is provided
    if (connectionDocking) {
      connection.waypoints = connectionDocking.getCroppedWaypoints(connection);
    }

    // save new waypoints in context
    context.newWaypoints = connection.waypoints;

    // update dragger
    context.draggerGfx.translate(e.x, e.y);

    // redraw connection
    redrawConnection(e);
  });

  eventBus.on('connectionSegment.move.hover', function(e) {

    e.context.hover = e.hover;
    canvas.addMarker(e.hover, MARKER_CONNECT_HOVER);
  });

  eventBus.on([
    'connectionSegment.move.out',
    'connectionSegment.move.cleanup'
  ], function(e) {

    // remove connect marker
    // if it was added
    var hover = e.context.hover;

    if (hover) {
      canvas.removeMarker(hover, MARKER_CONNECT_HOVER);
    }
  });

  eventBus.on('connectionSegment.move.cleanup', function(e) {

    var context = e.context,
        connection = context.connection;

    // remove dragger gfx
    if (context.draggerGfx) {
      context.draggerGfx.remove();
    }

    canvas.removeMarker(connection, MARKER_CONNECT_UPDATING);
  });

  eventBus.on([
    'connectionSegment.move.cancel',
    'connectionSegment.move.end'
  ], function(e) {
    var context = e.context,
        connection = context.connection;

    connection.waypoints = context.originalWaypoints;

    redrawConnection(e);
  });

  eventBus.on('connectionSegment.move.end', function(e) {

    var context = e.context,
        waypoints = context.newWaypoints;

    // ensure we have actual pixel values bendpoint
    // coordinates (important when zoom level was > 1 during move)
    waypoints.forEach(function(wp) {
      wp.x = Math.round(wp.x);
      wp.y = Math.round(wp.y);
    });

    modeling.updateWaypoints(context.connection, filterRedundantWaypoints(waypoints));
  });
}

ConnectionSegmentMove.$inject = [
  'injector', 'eventBus', 'canvas',
  'dragging', 'graphicsFactory', 'rules',
  'modeling'
];

module.exports = ConnectionSegmentMove;<commit_msg>fix(bendpoints/ConnectionSegmentMove): keep dragger on connections<commit_after>'use strict';

var Geometry = require('../../util/Geometry'),
    BendpointUtil = require('./BendpointUtil'),
    LayoutUtil = require('../../layout/LayoutUtil');

var MARKER_CONNECT_HOVER = 'connect-hover',
    MARKER_CONNECT_UPDATING = 'djs-updating';

function axisAdd(point, axis, delta) {
  return axisSet(point, axis, point[axis] + delta);
}

function axisSet(point, axis, value) {
  return {
    x: (axis === 'x' ? value : point.x),
    y: (axis === 'y' ? value : point.y)
  };
}

function axisFenced(position, segmentStart, segmentEnd, axis) {

  var maxValue = Math.max(segmentStart[axis], segmentEnd[axis]),
      minValue = Math.min(segmentStart[axis], segmentEnd[axis]);

  var padding = 25;

  var fencedValue = Math.min(Math.max(minValue + padding, position[axis]), maxValue - padding);

  return axisSet(segmentStart, axis, fencedValue);
}

function flipAxis(axis) {
  return axis === 'x' ? 'y' : 'x';
}

/**
 * Get the docking point on the given element.
 *
 * Compute a reasonable docking, if non exists.
 *
 * @param  {Point} point
 * @param  {djs.model.Shape} referenceElement
 * @param  {String} moveAxis (x|y)
 *
 * @return {Point}
 */
function getDocking(point, referenceElement, moveAxis) {

  var referenceMid,
      inverseAxis;

  if (point.original) {
    return point.original;
  } else {
    referenceMid = LayoutUtil.getMid(referenceElement);
    inverseAxis = flipAxis(moveAxis);

    return axisSet(point, inverseAxis, referenceMid[inverseAxis]);
  }
}

/**
 * A component that implements moving of bendpoints
 */
function ConnectionSegmentMove(injector, eventBus, canvas, dragging, graphicsFactory, rules, modeling) {

  // optional connection docking integration
  var connectionDocking = injector.get('connectionDocking', false);

  // API

  this.start = function(event, connection, idx) {

    var context,
        gfx = canvas.getGraphics(connection),
        segmentStartIndex = idx - 1,
        segmentEndIndex = idx,
        waypoints = connection.waypoints,
        segmentStart = waypoints[segmentStartIndex],
        segmentEnd = waypoints[segmentEndIndex],
        direction,
        axis;

    direction = Geometry.pointsAligned(segmentStart, segmentEnd);

    // do not move diagonal connection
    if (!direction) {
      return;
    }

    // the axis where we are going to move things
    axis = direction === 'v' ? 'y' : 'x';

    if (segmentStartIndex === 0) {
      segmentStart = getDocking(segmentStart, connection.source, axis);
    }

    if (segmentEndIndex === waypoints.length - 1) {
      segmentEnd = getDocking(segmentEnd, connection.target, axis);
    }

    context = {
      connection: connection,
      segmentStartIndex: segmentStartIndex,
      segmentEndIndex: segmentEndIndex,
      segmentStart: segmentStart,
      segmentEnd: segmentEnd,
      axis: axis
    };

    dragging.activate(event, 'connectionSegment.move', {
      cursor: axis === 'x' ? 'resize-ew' : 'resize-ns',
      data: {
        connection: connection,
        connectionGfx: gfx,
        context: context
      }
    });
  };

  // DRAGGING IMPLEMENTATION

  function redrawConnection(data) {
    graphicsFactory.update('connection', data.connection, data.connectionGfx);
  }

  function updateDragger(context, segmentOffset, event) {

    var newWaypoints = context.newWaypoints,
        segmentStartIndex = context.segmentStartIndex + segmentOffset,
        segmentStart = newWaypoints[segmentStartIndex],
        segmentEndIndex = context.segmentEndIndex + segmentOffset,
        segmentEnd = newWaypoints[segmentEndIndex],
        axis = flipAxis(context.axis);

    // make sure the dragger does not move
    // outside the connection
    var draggerPosition = axisFenced(event, segmentStart, segmentEnd, axis);

    // update dragger
    context.draggerGfx.translate(draggerPosition.x, draggerPosition.y);
  }

  function filterRedundantWaypoints(waypoints) {
    return waypoints.filter(function(r, idx) {
      return !Geometry.pointsOnLine(waypoints[idx - 1], waypoints[idx + 1], r);
    });
  }

  eventBus.on('connectionSegment.move.start', function(e) {

    var context = e.context,
        connection = e.connection,
        layer = canvas.getLayer('overlays');

    context.originalWaypoints = connection.waypoints.slice();

    // add dragger gfx
    context.draggerGfx = BendpointUtil.addSegmentDragger(layer, context.segmentStart, context.segmentEnd);
    context.draggerGfx.addClass('djs-dragging');

    canvas.addMarker(connection, MARKER_CONNECT_UPDATING);
  });

  eventBus.on('connectionSegment.move.move', function(e) {

    var context = e.context,
        connection = context.connection,
        segmentStartIndex = context.segmentStartIndex,
        segmentEndIndex = context.segmentEndIndex,
        segmentStart = context.segmentStart,
        segmentEnd = context.segmentEnd,
        axis = context.axis;

    var newWaypoints = context.originalWaypoints.slice(),
        newSegmentStart = axisAdd(segmentStart, axis, e['d' + axis]),
        newSegmentEnd = axisAdd(segmentEnd, axis, e['d' + axis]);

    // original waypoint count and added / removed
    // from start waypoint delta. We use the later
    // to retrieve the updated segmentStartIndex / segmentEndIndex
    var waypointCount = newWaypoints.length,
        segmentOffset = 0;

    // move segment start / end by axis delta
    newWaypoints[segmentStartIndex] = newSegmentStart;
    newWaypoints[segmentEndIndex] = newSegmentEnd;

    var sourceToSegmentOrientation,
        targetToSegmentOrientation;

    // handle first segment
    if (segmentStartIndex < 2) {
      sourceToSegmentOrientation = LayoutUtil.getOrientation(connection.source, newSegmentStart);

      // first bendpoint, remove first segment if intersecting
      if (segmentStartIndex === 1) {

        if (sourceToSegmentOrientation === 'intersect') {
          newWaypoints.shift();
          newWaypoints[0] = newSegmentStart;
          segmentOffset--;
        }
      }

      // docking point, add segment if not intersecting anymore
      else {
        if (sourceToSegmentOrientation !== 'intersect') {
          newWaypoints.unshift(segmentStart);
          segmentOffset++;
        }
      }
    }

    // handle last segment
    if (segmentEndIndex > waypointCount - 3) {
      targetToSegmentOrientation = LayoutUtil.getOrientation(connection.target, newSegmentEnd);

      // last bendpoint, remove last segment if intersecting
      if (segmentEndIndex === waypointCount - 2) {

        if (targetToSegmentOrientation === 'intersect') {
          newWaypoints.pop();
          newWaypoints[newWaypoints.length - 1] = newSegmentEnd;
        }
      }

      // last bendpoint, remove last segment if intersecting
      else {
        if (targetToSegmentOrientation !== 'intersect') {
          newWaypoints.push(segmentEnd);
        }
      }
    }

    // update connection waypoints
    connection.waypoints = newWaypoints;

    // crop connection, if docking service is provided
    if (connectionDocking) {
      connection.waypoints = newWaypoints = connectionDocking.getCroppedWaypoints(connection);
    }

    // save new waypoints in context
    context.newWaypoints = newWaypoints;

    // update dragger position
    updateDragger(context, segmentOffset, e);

    // redraw connection
    redrawConnection(e);
  });

  eventBus.on('connectionSegment.move.hover', function(e) {

    e.context.hover = e.hover;
    canvas.addMarker(e.hover, MARKER_CONNECT_HOVER);
  });

  eventBus.on([
    'connectionSegment.move.out',
    'connectionSegment.move.cleanup'
  ], function(e) {

    // remove connect marker
    // if it was added
    var hover = e.context.hover;

    if (hover) {
      canvas.removeMarker(hover, MARKER_CONNECT_HOVER);
    }
  });

  eventBus.on('connectionSegment.move.cleanup', function(e) {

    var context = e.context,
        connection = context.connection;

    // remove dragger gfx
    if (context.draggerGfx) {
      context.draggerGfx.remove();
    }

    canvas.removeMarker(connection, MARKER_CONNECT_UPDATING);
  });

  eventBus.on([
    'connectionSegment.move.cancel',
    'connectionSegment.move.end'
  ], function(e) {
    var context = e.context,
        connection = context.connection;

    connection.waypoints = context.originalWaypoints;

    redrawConnection(e);
  });

  eventBus.on('connectionSegment.move.end', function(e) {

    var context = e.context,
        waypoints = context.newWaypoints;

    // ensure we have actual pixel values bendpoint
    // coordinates (important when zoom level was > 1 during move)
    waypoints.forEach(function(wp) {
      wp.x = Math.round(wp.x);
      wp.y = Math.round(wp.y);
    });

    modeling.updateWaypoints(context.connection, filterRedundantWaypoints(waypoints));
  });
}

ConnectionSegmentMove.$inject = [
  'injector', 'eventBus', 'canvas',
  'dragging', 'graphicsFactory', 'rules',
  'modeling'
];

module.exports = ConnectionSegmentMove;<|endoftext|>