<commit_before>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Canvas', 'Entities', 'Physics', 'Utils', 'Maps',
function (B, canvas, Entities, Physics, Utils, Maps) {
	var ball,
		tracks = [],
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		fps = 30,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;
	console.log(DEBUG);

	// Init the view
	canvas.init(document.getElementById('game-canvas'));
	setInterval(updateAll, 1000 / fps);

	// Init the ball
	ball = new Entities.Ball(canvas.width() / 2, canvas.height() / 4, BALL_RADIUS, BALL_SPEED_X, BALL_SPEED_Y);
	// Position of the ball in the grid
	ball.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

	/* Events */
	// Event to execute when the player wins
	B.Events.on('win', null, function () {
		resetTracks(tracks);
		ball.reset();
	});

	// Event to execute when the player loses
	B.Events.on('lost', null, function () {
		resetTracks(tracks);
	});

	// Event to execute when the mouse move
	B.Events.on('mouse-moved', null, function (mX, mY) {
		mouseX = mX;
		mouseY = mY;

		if (DEBUG) {
			ball.x = mouseX;
			ball.y = mouseY;
			ball.speedX = BALL_SPEED_X;
			ball.speedY = BALL_SPEED_Y * -1;
		}
	});
	/* End of Events */

	/*
	 * Create the tracks, The whole game is a grid and tracks are on the grid
	 * The tracks are organised on a rectangle of the grid started at the
	 * position (TRACK_GRID_START_COL, TRACK_GRID_START_COL) and ends at the
	 * position (TRACK_GRID_COL, TRACK_GRID_ROW)
	 * Each track is an instance of the class Entities.Track
	 */
	var col, row,
		trackWidth = canvas.width() / Maps[0].width,
		trackHeight = canvas.height() / Maps[0].height;
	for (row = 0; row < Maps[0].height; row++ ) {
		for (col = 0; col < Maps[0].width; col++ ) {
			tracks.push(new Entities.Track(
				// 5 is the initial left margin
				trackWidth * col, trackHeight * row,
				trackWidth, trackHeight,
				// @TODO remove destructable field
				true, Maps[0].map[row][col] ? Entities.Track.STATE_ACTIVE : Entities.Track.STATE_INACTIVE
			));
		}
	}

	// Set the number of remaining tracks to destroy
	var remainingTracks = TRACKS_NUMBER;

	// @TODO put that somewhere
	// Reset the tracks to the original state (all active)
	function resetTracks (tracks) {
		for (var b = 0; b < TRACKS_NUMBER; b++) {
			tracks[b].reset();
		}
	}

	/**
	 * Method to convert a pair of coordinates to the index of the cell in the
	 * grid the coordinates are in
	 */
	colRowToGridIndex = function (col, row) {
		return col - TRACK_GRID_START_COL +
			(TRACK_GRID_COL - TRACK_GRID_START_COL) * (row - TRACK_GRID_START_ROW);
	};

	/**
	 * Method to update the game state and the objects's position
	 */
	function moveAll () {
		// Update the ball position
		ball.updatePosition();
		ball.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		/* Ball and edges collision*/
		var wallBounded = Physics.sphereBounceAgainstInnerRectangle(ball, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		if (wallBounded == 'down') {
			ball.reset();
			console.log('fire lost');
			B.Events.fire('lost');
		}
		/* End of Ball and edges collision*/

		/* Ball and active track collision */
		var track,
			trackSide,
			trackTopBot;

		track = tracks[colRowToGridIndex(
			ball.gridCellCol,
			ball.gridCellRow
		)];

		// if the ball is on an active track
		if (TRACK_GRID_START_COL <= ball.gridCellCol && ball.gridCellCol < TRACK_GRID_COL
			&& TRACK_GRID_START_COL <= ball.gridCellRow && ball.gridCellRow < TRACK_GRID_ROW
			&& track.state == Entities.Track.STATE_ACTIVE
		) {
			// track next to the current one, according to ball's old position
			trackSide = tracks[colRowToGridIndex(ball.oldGridCellCol, ball.gridCellRow)];
			trackSide = trackSide && trackSide.state == Entities.Track.STATE_ACTIVE && trackSide || undefined;

			// track under or above to the current one, according to ball's old position
			trackTopBot = tracks[colRowToGridIndex(ball.gridCellCol, ball.oldGridCellRow)];
			trackTopBot = trackTopBot && trackTopBot.state == Entities.Track.STATE_ACTIVE && trackTopBot || undefined;

			Physics.sphereBounceAgainstGridRectangle(ball, track, trackSide, trackTopBot);

			track.state = Entities.Track.STATE_INACTIVE;
			remainingTracks--;

			if (remainingTracks == 0) {
				console.log('win');
				B.Events.fire('win');
				return;
			}
		}
		/* End of Ball and active track collision */
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function updateAll () {
		moveAll();
		canvas.drawAll([ball, tracks]);

		if (DEBUG) {
			canvas.drawText('(' +
				Math.floor(mouseX / TRACK_SPACE_WIDTH) + ', ' +
				Math.floor(mouseY / TRACK_SPACE_HEIGHT) + ', ' +
				colRowToGridIndex(Math.floor(mouseX / TRACK_SPACE_WIDTH), Math.floor(mouseY / TRACK_SPACE_HEIGHT)) + ')', mouseX, mouseY, 'white');

			canvas.line([ball.x, ball.y], [ball.x + ball.speedX * 30, ball.y + ball.speedY * 30]);
		}
	}
});
<commit_msg>those are useless in this game<commit_after>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Canvas', 'Entities', 'Physics', 'Utils', 'Maps',
function (B, canvas, Entities, Physics, Utils, Maps) {
	var ball,
		tracks = [],
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		fps = 30,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;
	console.log(DEBUG);

	// Init the view
	canvas.init(document.getElementById('game-canvas'));
	setInterval(updateAll, 1000 / fps);

	// Init the ball
	ball = new Entities.Ball(canvas.width() / 2, canvas.height() / 4, BALL_RADIUS, BALL_SPEED_X, BALL_SPEED_Y);
	// Position of the ball in the grid
	ball.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

	/* Events */
	// Event to execute when the player wins
	B.Events.on('win', null, function () {
		ball.reset();
	});

	// Event to execute when the player loses
	B.Events.on('lost', null, function () {
	});

	// Event to execute when the mouse move
	B.Events.on('mouse-moved', null, function (mX, mY) {
		mouseX = mX;
		mouseY = mY;

		if (DEBUG) {
			ball.x = mouseX;
			ball.y = mouseY;
			ball.speedX = BALL_SPEED_X;
			ball.speedY = BALL_SPEED_Y * -1;
		}
	});
	/* End of Events */

	/*
	 * Create the tracks, The whole game is a grid and tracks are on the grid
	 * The tracks are organised on a rectangle of the grid started at the
	 * position (TRACK_GRID_START_COL, TRACK_GRID_START_COL) and ends at the
	 * position (TRACK_GRID_COL, TRACK_GRID_ROW)
	 * Each track is an instance of the class Entities.Track
	 */
	var col, row,
		trackWidth = canvas.width() / Maps[0].width,
		trackHeight = canvas.height() / Maps[0].height;
	for (row = 0; row < Maps[0].height; row++ ) {
		for (col = 0; col < Maps[0].width; col++ ) {
			tracks.push(new Entities.Track(
				// 5 is the initial left margin
				trackWidth * col, trackHeight * row,
				trackWidth, trackHeight,
				// @TODO remove destructable field
				true, Maps[0].map[row][col] ? Entities.Track.STATE_ACTIVE : Entities.Track.STATE_INACTIVE
			));
		}
	}

	}

	/**
	 * Method to convert a pair of coordinates to the index of the cell in the
	 * grid the coordinates are in
	 */
	colRowToGridIndex = function (col, row) {
		return col - TRACK_GRID_START_COL +
			(TRACK_GRID_COL - TRACK_GRID_START_COL) * (row - TRACK_GRID_START_ROW);
	};

	/**
	 * Method to update the game state and the objects's position
	 */
	function moveAll () {
		// Update the ball position
		ball.updatePosition();
		ball.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		/* Ball and edges collision*/
		var wallBounded = Physics.sphereBounceAgainstInnerRectangle(ball, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		if (wallBounded == 'down') {
			ball.reset();
			console.log('fire lost');
			B.Events.fire('lost');
		}
		/* End of Ball and edges collision*/

		/* Ball and active track collision */
		var track,
			trackSide,
			trackTopBot;

		track = tracks[colRowToGridIndex(
			ball.gridCellCol,
			ball.gridCellRow
		)];

		// if the ball is on an active track
		if (TRACK_GRID_START_COL <= ball.gridCellCol && ball.gridCellCol < TRACK_GRID_COL
			&& TRACK_GRID_START_COL <= ball.gridCellRow && ball.gridCellRow < TRACK_GRID_ROW
			&& track.state == Entities.Track.STATE_ACTIVE
		) {
			// track next to the current one, according to ball's old position
			trackSide = tracks[colRowToGridIndex(ball.oldGridCellCol, ball.gridCellRow)];
			trackSide = trackSide && trackSide.state == Entities.Track.STATE_ACTIVE && trackSide || undefined;

			// track under or above to the current one, according to ball's old position
			trackTopBot = tracks[colRowToGridIndex(ball.gridCellCol, ball.oldGridCellRow)];
			trackTopBot = trackTopBot && trackTopBot.state == Entities.Track.STATE_ACTIVE && trackTopBot || undefined;

			Physics.sphereBounceAgainstGridRectangle(ball, track, trackSide, trackTopBot);
		}
		/* End of Ball and active track collision */
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function updateAll () {
		moveAll();
		canvas.drawAll([ball, tracks]);

		if (DEBUG) {
			canvas.drawText('(' +
				Math.floor(mouseX / TRACK_SPACE_WIDTH) + ', ' +
				Math.floor(mouseY / TRACK_SPACE_HEIGHT) + ', ' +
				colRowToGridIndex(Math.floor(mouseX / TRACK_SPACE_WIDTH), Math.floor(mouseY / TRACK_SPACE_HEIGHT)) + ')', mouseX, mouseY, 'white');

			canvas.line([ball.x, ball.y], [ball.x + ball.speedX * 30, ball.y + ball.speedY * 30]);
		}
	}
});
<|endoftext|>


<commit_before>GTCA = Ember.Application.create();
GTCA.ApplicationController = Ember.Controller.extend({
});

GTCA.Router.map(function() {
  this.resource('patient', { path: '/patient/:patient_id' }, function() {
    this.route("dosing");
  });
});

GTCA.IndexRoute = Ember.Route.extend({
  redirect: function() {
    this.transitionTo('patient', { id: 'huAC827A' });
  }
});

GTCA.PatientDosingRoute = Ember.Route.extend({
  model: function() {
    return [];
  }
});

GTCA.PatientRoute = Ember.Route.extend({
  renderTemplate: function() {
    this.render();
    this.render('patient-sidebar', {
                  into: 'patient',
                  outlet: 'patient_view'
                });
  },
  model: function(params) {
    return {
      id: 'huAC827A',
      first_name: 'John',
      last_name: 'Dou',
      birth_date: '3/10/1960',
      gender: 'Male',
      mr_id: 123213,
      acct_id: 13123
    }
  }
});

GTCA.DrugTextField = Ember.TextField.extend({
  insertNewline: function() {
    this.get('controller').send('add_drug');
  }
});

GTCA.PatientDosingController = Ember.ArrayController.extend({
  init: function() {
    this.set('condition', "");
  },

  condition_specified: function() {
    return this.get('condition') != "";
  }.property('condition'),

  add_drug: function() {
    switch(this.get('drug').toLowerCase()) {
      case 'warfarin':
        this.addObject({
          title: 'Warfarin',
          dosage: '2mg',
          typical_dosage: '1mg',
          factors: [
            { name: 'CYP2C9', type: 'SNP', effect: 0.5 },
            { name: 'Asian', type: 'Ethnicity', effect: -0.2 },
            { name: 'Heart Surgery', type: 'Condition', effect: 0.3 },
          ]
        });
        break;
      case 'heparin':
        this.addObject({
          title: 'Heparin',
          dosage: '3mg',
          typical_dosage: '4mg',
          factors: [
            { name: 'Asian', type: 'Ethnicity', effect: -0.2 },
            { name: 'Heart Surgery', type: 'Condition', effect: 0.3 },
            { name: 'CYP2C9', type: 'SNP', effect: 0.5 },
          ]
        });
        break;
      case '':
        break;
      default:
        alert('Bad drug');
    }
    this.set('drug', "");
    this.set('selection', this.get('lastObject'));
  }
});

GTCA.PatientIndexController = Ember.ObjectController.extend({
});

GTCA.ApplicationRoute = Ember.Route.extend({
});
<commit_msg>Informative Bad drug message<commit_after>GTCA = Ember.Application.create();
GTCA.ApplicationController = Ember.Controller.extend({
});

GTCA.Router.map(function() {
  this.resource('patient', { path: '/patient/:patient_id' }, function() {
    this.route("dosing");
  });
});

GTCA.IndexRoute = Ember.Route.extend({
  redirect: function() {
    this.transitionTo('patient', { id: 'huAC827A' });
  }
});

GTCA.PatientDosingRoute = Ember.Route.extend({
  model: function() {
    return [];
  }
});

GTCA.PatientRoute = Ember.Route.extend({
  renderTemplate: function() {
    this.render();
    this.render('patient-sidebar', {
                  into: 'patient',
                  outlet: 'patient_view'
                });
  },
  model: function(params) {
    return {
      id: 'huAC827A',
      first_name: 'John',
      last_name: 'Dou',
      birth_date: '3/10/1960',
      gender: 'Male',
      mr_id: 123213,
      acct_id: 13123
    }
  }
});

GTCA.DrugTextField = Ember.TextField.extend({
  insertNewline: function() {
    this.get('controller').send('add_drug');
  }
});

GTCA.PatientDosingController = Ember.ArrayController.extend({
  init: function() {
    this.set('condition', "");
  },

  condition_specified: function() {
    return this.get('condition') != "";
  }.property('condition'),

  add_drug: function() {
    switch(this.get('drug').toLowerCase()) {
      case 'warfarin':
        this.addObject({
          title: 'Warfarin',
          dosage: '2mg',
          typical_dosage: '1mg',
          factors: [
            { name: 'CYP2C9', type: 'SNP', effect: 0.5 },
            { name: 'Asian', type: 'Ethnicity', effect: -0.2 },
            { name: 'Heart Surgery', type: 'Condition', effect: 0.3 },
          ]
        });
        break;
      case 'heparin':
        this.addObject({
          title: 'Heparin',
          dosage: '3mg',
          typical_dosage: '4mg',
          factors: [
            { name: 'Asian', type: 'Ethnicity', effect: -0.2 },
            { name: 'Heart Surgery', type: 'Condition', effect: 0.3 },
            { name: 'CYP2C9', type: 'SNP', effect: 0.5 },
          ]
        });
        break;
      case '':
        break;
      default:
        alert('Bad drug: only Warfarin and Heparin currently supported');
    }
    this.set('drug', "");
    this.set('selection', this.get('lastObject'));
  }
});

GTCA.PatientIndexController = Ember.ObjectController.extend({
});

GTCA.ApplicationRoute = Ember.Route.extend({
});
<|endoftext|>


<commit_before>

var App;
var RaphaelElement;

var ActivityElements = new ActivityList;
var StartElements = new StartList;
var EndElements = new EndList;
var SwimlaneElements = new SwimlaneList;
var GatewayElements = new GatewayList;
var RelationElements = new RelationList;
RaphaelObjects = [];

window.onload = function() {

    connections = [];

    RaphaelElement = Raphael(10, 120, "100%", "100%");
    App = new AppView;
    setUpApplication();

};

function setUpApplication(){
    function renderActivities() {

       for(var i=0; i<ActivityElements.length; i++){
        activityElements = new ActivityView({model: ActivityElements.models[i]});
        activityElements.render();
        };

   }

  function renderStarts(){
        for(var i=0; i<StartElements.length; i++){
        startsViewElement = new StartsView({model: StartElements.models[i]});
        startsViewElement.render();
        };

  }

  function renderEnds(){
        for(var i=0; i<EndElements.length; i++){
        endsViewElement = new endsView({model: EndElements.models[i]});
        endsViewElement.render();
        };
  }

  function renderSwimlanes(){
       for(var i=0; i<SwimlaneElements.length; i++){
        swimlanesElement = new swimlanesView({model: SwimlaneElements.models[i]});
        swimlanesElement.render();
        };
  }

  function renderGateways(){
       for(var i=0; i<GatewayElements.length; i++){
        gatewayElement = new gatewayView({model: GatewayElements.models[i]});
        gatewayElement.render();
        };
  }

  function renderRelations(){

      for(var i=0; i<RelationElements.length; i++){
        relationViewElement = new relationView({model: RelationElements.models[i]});

        relationViewElement.render();
        };

  }

    $.when(ActivityElements.fetch({success: renderActivities}),
    StartElements.fetch({success: renderStarts}),
    EndElements.fetch({success: renderEnds}),
    SwimlaneElements.fetch({success: renderSwimlanes}),
    GatewayElements.fetch({success: renderGateways}))
    .then(function() {
        RelationElements.fetch({success: renderRelations});
    });

}

function updateall(){

	for (var i=0; i<ActivityElements.length; i++) {
		ActivityElements.at(i).save();

	}
	for (var i=0; i<StartElements.length; i++) {
		StartElements.at(i).save();
	}
	for (var i=0; i<EndElements.length; i++) {
		EndElements.at(i).save();
	}
	for (var i=0; i<GatewayElements.length; i++) {
		GatewayElements.at(i).save();
	}

    console.log("Elements hopefully saved, now refresh page.");
}

function changeText(id, text) {
	var elem = getBackboneModelById(2);
	elem.set({value: "Rawr2"});
	elem.save();
}

function getBackboneModelById(id) {
	    if(ActivityElements.get(id) != null) return ActivityElements.get(id);
	    else if(StartElements.get(id) != null) return StartElements.get(id);
	    else if(EndElements.get(id) != null) return EndElements.get(id);
	    else if(SwimlaneElements.get(id) != null) return SwimlaneElements.get(id);
	    else if(GatewayElements.get(id) != null) return GatewayElements.get(id);
}

function newActivity() {
    activity = new activity();
    view = new ActivityView({model: activity});
    activity.save();
    activityElements.push(activity);
};
<commit_msg>muutoksia<commit_after>

var App;
var RaphaelElement;

var ActivityElements = new ActivityList;
var StartElements = new StartList;
var EndElements = new EndList;
var SwimlaneElements = new SwimlaneList;
var GatewayElements = new GatewayList;
var RelationElements = new RelationList;
RaphaelObjects = [];

window.onload = function() {

    connections = [];

    RaphaelElement = Raphael(10, 120, "100%", "100%");
    App = new AppView;
    setUpApplication();

     setInterval(function() {
         console.log("testi");
         refresh(); }, 4000);

};

function setUpApplication(){
    function renderActivities() {

       for(var i=0; i<ActivityElements.length; i++){
        activityElements = new ActivityView({model: ActivityElements.models[i]});
        activityElements.render();
        };

   }

  function renderStarts(){
        for(var i=0; i<StartElements.length; i++){
        startsViewElement = new StartsView({model: StartElements.models[i]});
        startsViewElement.render();
        };

  }

  function renderEnds(){
        for(var i=0; i<EndElements.length; i++){
        endsViewElement = new endsView({model: EndElements.models[i]});
        endsViewElement.render();
        };
  }

  function renderSwimlanes(){
       for(var i=0; i<SwimlaneElements.length; i++){
        swimlanesElement = new swimlanesView({model: SwimlaneElements.models[i]});
        swimlanesElement.render();
        };
  }

  function renderGateways(){
       for(var i=0; i<GatewayElements.length; i++){
        gatewayElement = new gatewayView({model: GatewayElements.models[i]});
        gatewayElement.render();
        };
  }

  function renderRelations(){

      for(var i=0; i<RelationElements.length; i++){
        relationViewElement = new relationView({model: RelationElements.models[i]});

        relationViewElement.render();
        };

  }

    $.when(ActivityElements.fetch({success: renderActivities}),
    StartElements.fetch({success: renderStarts}),
    EndElements.fetch({success: renderEnds}),
    SwimlaneElements.fetch({success: renderSwimlanes}),
    GatewayElements.fetch({success: renderGateways}))
    .then(function() {
        RelationElements.fetch({success: renderRelations});
    });

}

function updateall(){

	for (var i=0; i<ActivityElements.length; i++) {
		ActivityElements.at(i).save();

	}
	for (var i=0; i<StartElements.length; i++) {
		StartElements.at(i).save();
	}
	for (var i=0; i<EndElements.length; i++) {
		EndElements.at(i).save();
	}
	for (var i=0; i<GatewayElements.length; i++) {
		GatewayElements.at(i).save();
	}

    console.log("Elements hopefully saved, now refresh page.");
}

function changeText(id, text) {
	var elem = getBackboneModelById(2);
	elem.set({value: "Rawr2"});
	elem.save();
}

function getBackboneModelById(id) {
	    if(ActivityElements.get(id) != null) return ActivityElements.get(id);
	    else if(StartElements.get(id) != null) return StartElements.get(id);
	    else if(EndElements.get(id) != null) return EndElements.get(id);
	    else if(SwimlaneElements.get(id) != null) return SwimlaneElements.get(id);
	    else if(GatewayElements.get(id) != null) return GatewayElements.get(id);
}

function newActivity() {
    activity = new activity();
    view = new ActivityView({model: activity});
    activity.save();
    activityElements.push(activity);
};
<|endoftext|>


<commit_before>/* globals $ */
$(function () {
  'use strict'

  const $tableBody = $('table#studentlist tbody')
  const fn = function (data) {
    data.rows
      .filter(function (row) {
        return row.doc.roles.indexOf('teacher') === -1 && row.doc.roles.indexOf('_admin') === -1
      })
      .forEach(function (row) {
        const u = row.id.split(':')[1]
        const id = 'confirm-delete-' + u.replace(/ /g, '')
        $tableBody.append([
          '
' + u + '	',
          'consulter	',
          '',
          '<button type="button" class="button warning" data-toggle="' + id + '">effacer</button>',
          '
',
          '<button type="button" class="confirm button alert">Effacer ' + u + '</button>',
          '
',
          '
'
        ].join(''))
      })
    $tableBody.foundation()
  }
  const query = {
    include_docs: true,
    startkey: '"org.couchdb.user:"',
    endkey: '"org.couchdb.user:\ufff0"'
  }
  $.getJSON('/_users/_all_docs', query, fn)

  $tableBody.on('click', 'button.confirm', function (ev) {
    $(this).parents('.dropdown-pane').foundation('close')
    const $row = $(this).parents('tr').addClass('callout alert')
    const uid = $row.data('uid')
    const rev = $row.data('rev')
    $.ajax({
      url: '/_users/org.couchdb.user:' + uid + '?rev=' + rev,
      method: 'DELETE',
      error: function () { $row.addClass('callout secondary') },
      success: function () { $row.fadeOut(500, function () { $row.remove() }) }
    })
  })
})
<commit_msg>Touchups.<commit_after>/* globals $ */
$(function () {
  'use strict'

  const $tableBody = $('table#studentlist tbody')
  const fn = function (data) {
    data.rows
      .filter(function (row) { return row.doc.roles.indexOf('teacher') === -1 && row.doc.roles.indexOf('_admin') === -1 })
      .forEach(function (row) {
        const u = row.id.split(':')[1]
        const id = 'confirm-delete-' + u.replace(/ /g, '')
        $tableBody.append([
          '
' + u + '	',
          'consulter	',
          '',
          '<button type="button" class="button warning" data-toggle="' + id + '">effacer</button>',
          '
',
          '<button type="button" class="confirm button alert">Effacer ' + u + '</button>',
          '
',
          '
'
        ].join(''))
      })
    $tableBody.foundation()
  }
  const query = {
    include_docs: true,
    startkey: '"org.couchdb.user:"',
    endkey: '"org.couchdb.user:\ufff0"'
  }
  $.getJSON('/_users/_all_docs', query, fn)

  $tableBody.on('click', 'button.confirm', function (ev) {
    $(this).parents('.dropdown-pane').foundation('close')
    const $row = $(this).parents('tr').addClass('callout alert')
    const uid = $row.data('uid')
    const rev = $row.data('rev')
    // TODO: delete rendus de référence
    $.ajax({
      url: '/_users/org.couchdb.user:' + uid + '?rev=' + rev,
      method: 'DELETE',
      error: function () { $row.removeClass('alert').addClass('secondary') },
      success: function () { $row.fadeOut(500, function () { $row.remove() }) }
    })
  })
})
<|endoftext|>


<commit_before>// @flow

/**
 * CSS to style the selection psuedo-element.
 *
 * @example
 * // Styles as object usage
 * const styles = {
 *   ...placeholder({'color': 'blue'})
 * }
 *
 * // styled-components usage
 * const div = styled.input`
 *    ${placeholder({'color': 'blue'})}
 * `
 *
 * // CSS as JS Output
 *
 * 'input': {
 *   '&:-moz-placeholder': {
 *     'color': 'blue',
 *   },
 *   '&:-ms-input-placeholder': {
 *     'color': 'blue',
 *   },
 *   '&::-moz-placeholder': {
 *     'color': 'blue',
 *   },
 *   '&::-webkit-input-placeholder': {
 *     'color': 'blue',
 *   },
 * },
 */

function placeholder(styles: Object, parent?: string = '&'): Object {
  return {
    [`${parent}::-webkit-input-placeholder`]: {
      ...styles,
    },
    [`${parent}:-moz-placeholder`]: {
      ...styles,
    },
    [`${parent}::-moz-placeholder`]: {
      ...styles,
    },
    [`${parent}:-ms-input-placeholder`]: {
      ...styles,
    },
  }
}

export default placeholder
<commit_msg>Correct the documentation for the placeholder mixin (#247)<commit_after>// @flow

/**
 * CSS to style the placeholder psuedo-element.
 *
 * @example
 * // Styles as object usage
 * const styles = {
 *   ...placeholder({'color': 'blue'})
 * }
 *
 * // styled-components usage
 * const div = styled.input`
 *    ${placeholder({'color': 'blue'})}
 * `
 *
 * // CSS as JS Output
 *
 * 'input': {
 *   '&:-moz-placeholder': {
 *     'color': 'blue',
 *   },
 *   '&:-ms-input-placeholder': {
 *     'color': 'blue',
 *   },
 *   '&::-moz-placeholder': {
 *     'color': 'blue',
 *   },
 *   '&::-webkit-input-placeholder': {
 *     'color': 'blue',
 *   },
 * },
 */

function placeholder(styles: Object, parent?: string = '&'): Object {
  return {
    [`${parent}::-webkit-input-placeholder`]: {
      ...styles,
    },
    [`${parent}:-moz-placeholder`]: {
      ...styles,
    },
    [`${parent}::-moz-placeholder`]: {
      ...styles,
    },
    [`${parent}:-ms-input-placeholder`]: {
      ...styles,
    },
  }
}

export default placeholder
<|endoftext|>


<commit_before>'use strict';

// Author: Oğuzhan TÜRK

// Scrobbling for: http://www.trtturku.net/

/* global Connector, MetadataFilter */

function toTitleCase(str) {
	var tempArray = str.toLowerCase().split(' ');
 	var realArray = [];
	var i = 0;

	for(i = 0; i < tempArray.length; ++i){
		var innerTempArray = tempArray[i].split('-');

		for(var j = 0; ;){
			realArray.push(innerTempArray[j]);

			if(++j >= innerTempArray.length){
				break;
			}

			realArray.push('-');
		}
	}

	for(i = 0; i < realArray.length; ++i){
		realArray[i] = realArray[i].split('');
		realArray[i][0] = realArray[i][0] === 'i' ? 'İ' : realArray[i][0].toUpperCase();
		realArray[i] = realArray[i].join('');
	}

	return realArray.join(' ');
 }

Connector.playerSelector = '.jwplayer';

Connector.isPlaying = function () {
	return $('.jwplay.jwtoggle').length === 1;
};

Connector.durationSelector = '.jwduration';

Connector.currentTimeSelector = '.jwelapsed';

Connector.filter = new MetadataFilter({
	all: [MetadataFilter.trim, toTitleCase]
});

function setupRadioPlayer() {
	Connector.artistSelector = '#besa_mp3_play_area tr:nth-child(2) > td:nth-child(2)';
	Connector.trackSelector = '#besa_mp3_play_area tr:nth-child(3) > td:nth-child(2)';
}

function setupPlaylistPlayer() {
	Connector.getArtist = function () {
		return $('.jwitem.active .jwtitle').text().split(' - ')[0];
	};

	Connector.getTrack = function () {
		return $('.jwitem.active .jwtitle').text().split(' - ')[1];
	};
}

function isRadioPlayer() {
	return $('#besa_mp3_play_area').length === 1;
}

function isPlaylistPlayer() {
	return $('.jwitem.active .jwtitle').length === 1;
}

function setupConnector() {
	if (isRadioPlayer()){
		setupRadioPlayer();
	}
	else if (isPlaylistPlayer()){
		setupPlaylistPlayer();
	}
}

setupConnector();
<commit_msg>Unexpected space errors have been fixed.<commit_after>'use strict';

// Author: Oğuzhan TÜRK

// Scrobbling for: http://www.trtturku.net/

/* global Connector, MetadataFilter */

function toTitleCase(str) {
	var tempArray = str.toLowerCase().split(' ');
	var realArray = [];
	var i = 0;

	for(i = 0; i < tempArray.length; ++i){
		var innerTempArray = tempArray[i].split('-');

		for(var j = 0; ;){
			realArray.push(innerTempArray[j]);

			if(++j >= innerTempArray.length){
				break;
			}

			realArray.push('-');
		}
	}

	for(i = 0; i < realArray.length; ++i){
		realArray[i] = realArray[i].split('');
		realArray[i][0] = realArray[i][0] === 'i' ? 'İ' : realArray[i][0].toUpperCase();
		realArray[i] = realArray[i].join('');
	}

	return realArray.join(' ');
}

Connector.playerSelector = '.jwplayer';

Connector.isPlaying = function () {
	return $('.jwplay.jwtoggle').length === 1;
};

Connector.durationSelector = '.jwduration';

Connector.currentTimeSelector = '.jwelapsed';

Connector.filter = new MetadataFilter({
	all: [MetadataFilter.trim, toTitleCase]
});

function setupRadioPlayer() {
	Connector.artistSelector = '#besa_mp3_play_area tr:nth-child(2) > td:nth-child(2)';
	Connector.trackSelector = '#besa_mp3_play_area tr:nth-child(3) > td:nth-child(2)';
}

function setupPlaylistPlayer() {
	Connector.getArtist = function () {
		return $('.jwitem.active .jwtitle').text().split(' - ')[0];
	};

	Connector.getTrack = function () {
		return $('.jwitem.active .jwtitle').text().split(' - ')[1];
	};
}

function isRadioPlayer() {
	return $('#besa_mp3_play_area').length === 1;
}

function isPlaylistPlayer() {
	return $('.jwitem.active .jwtitle').length === 1;
}

function setupConnector() {
	if (isRadioPlayer()){
		setupRadioPlayer();
	}
	else if (isPlaylistPlayer()){
		setupPlaylistPlayer();
	}
}

setupConnector();
<|endoftext|>


<commit_before>import React from 'react';

import AuthUserContext from './context';
import { withFirebase } from '../Firebase';

const needsEmailVerification = authUser =>
  authUser &&
  !authUser.emailVerified &&
  authUser.providerData
    .map(provider => provider.providerId)
    .includes('password');

const withEmailVerification = Component => {
  class WithEmailVerification extends React.Component {
    constructor(props) {
      super(props);

      this.state = { isSent: false };
    }

    onSendEmailVerification = () => {
      this.props.firebase
        .doSendEmailVerification()
        .then(() => this.setState({ isSent: true }));
    };

    render() {
      return (
        <AuthUserContext.Consumer>
          {authUser =>
            needsEmailVerification(authUser) ? (

                {this.state.isSent ? (

                    E-Mail confirmation sent: Check you E-Mails (Spam
                    folder included) for a confirmation E-Mail.
                    Refresh this page once you confirmed your E-Mail.

                ) : (

                    Verify your E-Mail: Check you E-Mails (Spam folder
                    included) for a confirmation E-Mail or send
                    another confirmation E-Mail.

                )}

                <button
                  type="button"
                  onClick={this.onSendEmailVerification}
                  disabled={this.state.isSent}
                >
                  Send confirmation E-Mail
                </button>

            ) : (
              <Component {...this.props} />
            )
          }
        </AuthUserContext.Consumer>
      );
    }
  }

  return withFirebase(WithEmailVerification);
};

export default withEmailVerification;
<commit_msg>Fix typos in message.<commit_after>import React from 'react';

import AuthUserContext from './context';
import { withFirebase } from '../Firebase';

const needsEmailVerification = authUser =>
  authUser &&
  !authUser.emailVerified &&
  authUser.providerData
    .map(provider => provider.providerId)
    .includes('password');

const withEmailVerification = Component => {
  class WithEmailVerification extends React.Component {
    constructor(props) {
      super(props);

      this.state = { isSent: false };
    }

    onSendEmailVerification = () => {
      this.props.firebase
        .doSendEmailVerification()
        .then(() => this.setState({ isSent: true }));
    };

    render() {
      return (
        <AuthUserContext.Consumer>
          {authUser =>
            needsEmailVerification(authUser) ? (

                {this.state.isSent ? (

                    Email confirmation sent: Check your emails (Spam
                    folder included) for a confirmation email.
                    Refresh this page once you confirmed your email.

                ) : (

                    Verify your email: Check your email (Spam folder
                    included) for a confirmation email or send
                    another confirmation email.

                )}

                <button
                  type="button"
                  onClick={this.onSendEmailVerification}
                  disabled={this.state.isSent}
                >
                  Send confirmation E-Mail
                </button>

            ) : (
              <Component {...this.props} />
            )
          }
        </AuthUserContext.Consumer>
      );
    }
  }

  return withFirebase(WithEmailVerification);
};

export default withEmailVerification;
<|endoftext|>


<commit_before>/*global define*/
/*jslint white:true,browser:true,nomen:true*/

define([
    'bluebird',
    'uuid',
    'common/ui',
    'kb_common/html'
], function (Promise, Uuid, UI, html) {
    'use strict';

    var t = html.tag,
        div = t('div');

    function formatError(errorInfo) {
        var errorId = new Uuid(4).format(),
            errorType, errorMessage, errorDetail;
        if (errorInfo.error) {
            // Classic KBase rpc error message
            errorType = errorInfo.name;
            errorMessage = errorInfo.message;
            errorDetail = errorInfo.error;
        } else if (errorInfo.name) {
            errorType = 'unknown';
            errorMessage = errorInfo.name + ' (code: ' + String(errorInfo.code) + ')';
            errorDetail = 'This error occurred during execution of the app job.';
        } else {
            errorType = 'unknown';
            errorMessage = 'Unknown error (check console for ' + errorId + ')';
            errorDetail = 'There is no further information about this error';
        }

        return {
            location: 'job execution',
            type: errorType,
            message: errorMessage,
            detail: errorDetail
        };
    }

    function renderErrorLayout() {
        return div([
            div({style: {fontWeight: 'bold'}}, [
                'Type'
            ]),
            div({dataElement: 'type'}),
            div({style: {fontWeight: 'bold', marginTop: '1em'}}, [
                'Message'
            ]),
            div({dataElement: 'message'}),
            div({style: {fontWeight: 'bold', marginTop: '1em'}}, [
                'Detail'
            ]),
            div({dataElement: 'detail',
                style: {
                    border: '0px silver solid',
                    padding: '4px',
                    xoverflowY: 'auto',
                    wordBreak: 'break-word'
                }})
        ]);
    }

    function factory(config) {
        var container, ui, model = config.model;
        function start(arg) {
            return Promise.try(function () {
                container = arg.node;

                // Very simple for now, just render the results json in a prettier than normal fashion.

                container.innerHTML = renderErrorLayout();

                ui = UI.make({node: container});

                var viewModel = formatError(model.getItem('exec.jobState.error'));

                ui.updateFromViewModel(viewModel);
            });
        }

        function stop() {
            return Promise.try(function () {
                container.innerHTML = 'Bye from error';
            });
        }

        return {
            start: start,
            stop: stop
        };
    }

    return {
        make: function (config) {
            return factory(config);
        }
    };
});<commit_msg>error tab now handles internal errors as well as job errors. more to do on error display formatting<commit_after>/*global define*/
/*jslint white:true,browser:true,nomen:true*/

define([
    'bluebird',
    'uuid',
    'common/ui',
    'kb_common/html'
], function (Promise, Uuid, UI, html) {
    'use strict';

    var t = html.tag,
        div = t('div'), ul = t('ul'), li = t('li');

    function convertJobError(errorInfo) {
        var errorId = new Uuid(4).format(),
            errorType, errorMessage, errorDetail;
        if (errorInfo.error) {
            // Classic KBase rpc error message
            errorType = errorInfo.name;
            errorMessage = errorInfo.message;
            errorDetail = errorInfo.error;
        } else if (errorInfo.name) {
            errorType = 'unknown';
            errorMessage = errorInfo.name + ' (code: ' + String(errorInfo.code) + ')';
            errorDetail = 'This error occurred during execution of the app job.';
        } else {
            errorType = 'unknown';
            errorMessage = 'Unknown error (check console for ' + errorId + ')';
            errorDetail = 'There is no further information about this error';
        }

        return {
            location: 'job execution',
            type: errorType,
            message: errorMessage,
            detail: errorDetail
        };
    }

    function convertInternalError(errorInfo) {
        return {
            location: 'app cell',
            type: errorInfo.title,
            message: errorInfo.message,
            advice: ul({style: {paddingLeft: '1.2em'}}, errorInfo.advice.map(function (adv) {
                return li(adv);
            })),
            detail: errorInfo.detail
                // info:  errorInfo ? html.makeObjTable(errorInfo.info, {rotated: true, classes: []}) : null
        };
    }

    function renderErrorLayout() {
        return div([
            div({style: {fontWeight: 'bold'}}, [
                'Type'
            ]),
            div({dataElement: 'type'}),
            div({style: {fontWeight: 'bold', marginTop: '1em'}}, [
                'Message'
            ]),
            div({dataElement: 'message'}),
            div({style: {fontWeight: 'bold', marginTop: '1em'}}, [
                'Advice'
            ]),
            div({dataElement: 'advice'}),
            div({style: {fontWeight: 'bold', marginTop: '1em'}}, [
                'Detail'
            ]),
            div({dataElement: 'detail',
                style: {
                    border: '0px silver solid',
                    padding: '4px',
                    xoverflowY: 'auto',
                    wordBreak: 'break-word'
                }}),
            div({style: {fontWeight: 'bold', marginTop: '1em'}}, [
                'Info'
            ]),
            div({dataElement: 'info'})
        ]);
    }

    function factory(config) {
        var container, ui, model = config.model;
        function start(arg) {
            return Promise.try(function () {
                container = arg.node;

                // Very simple for now, just render the results json in a prettier than normal fashion.

                container.innerHTML = renderErrorLayout();

                ui = UI.make({node: container});

                var viewModel;
                if (model.hasItem('exec.jobState.error')) {
                    viewModel = convertJobError(model.getItem('exec.jobState.error'));
                } else if (model.hasItem('internalError')) {
                    viewModel = convertInternalError(model.getItem('internalError'));
                } else {
                    viewModel = {
                        location: 'unknown',
                        type: 'unknown',
                        message: 'An unknown error was detected',
                        detail: ''
                    };
                }
                console.log('to err...', viewModel);

                ui.updateFromViewModel(viewModel);
            });
        }

        function stop() {
            return Promise.try(function () {
                container.innerHTML = 'Bye from error';
            });
        }

        return {
            start: start,
            stop: stop
        };
    }

    return {
        make: function (config) {
            return factory(config);
        }
    };
});<|endoftext|>


<commit_before>import React, {Component, Children, cloneElement} from 'react';
import {findDOMNode} from 'react-dom';
import PropTypes from 'prop-types';

import './Waterfall.css';

export default class Waterfall extends Component {

    constructor(props) {

        super(props);

        this.shouldRender = false;

        this.state = {
            dom: null
        };

        this.generateTempColumns = this::this.generateTempColumns;
        this.renderChildren = this::this.renderChildren;

    }

    initTempColumns(column) {

        if (!column || column.length < 1) {
            return;
        }

        const result = [];

        for (let i = 0; i < column; i++) {
            result.push({
                heightCount: 0,
                children: []
            });
        }

        return result;

    }

    getMinHeightColumn(columns) {

        if (!columns || columns.length < 1) {
            return;
        }

        let minItem = columns[0],
            min = minItem.heightCount;

        for (let i = 1, len = columns.length; i < len; i++) {
            if (columns[i].heightCount < min) {
                minItem = columns[i];
                min = columns[i].heightCount;
            }
        }

        return minItem;

    }

    generateTempColumns(props = this.props) {

        const {column, children} = props,
            tempColumns = this.initTempColumns(column);

        let el, elHeight, item;

        Children.forEach(children, (child, index) => {

            el = findDOMNode(this.refs[`waterfallTempChild${index}`]);
            if (el) {
                elHeight = parseInt(getComputedStyle(el).height);
                if (elHeight) {
                    item = this.getMinHeightColumn(tempColumns);
                    item.heightCount += elHeight;
                    item.children.push(child);
                }
            }

        });

        return tempColumns;

    }

    renderChildren(props = this.props) {

        const {column} = props,
            tempColumns = this.generateTempColumns(props),
            columnStyle = {
                width: `${100 / column}%`
            },
            result = [];

        for (let i = 0; i < column; i++) {
            result.push(

                    {tempColumns[i] && tempColumns[i].children}

            );
        }

        return result;

    }

    componentDidMount() {
        this.setState({
            dom: this.renderChildren()
        });
    }

    componentWillReceiveProps() {
        this.shouldRender = true;
    }

    componentDidUpdate(nextProps) {
        if (this.shouldRender) {
            this.shouldRender = false;
            this.setState({
                dom: this.renderChildren(nextProps)
            });
        }
    }

    render() {

        const {children} = this.props,
            {dom} = this.state;

        return (

                {dom}

                    {
                        children.map((child, index) => {
                            return cloneElement(child, {
                                key: index,
                                ref: `waterfallTempChild${index}`
                            });
                        })
                    }

        );
    }

}

Waterfall.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * Column count of waterfall.
     */
    column: PropTypes.number

};

Waterfall.defaultProps = {

    className: '',
    style: null,

    column: 3

};<commit_msg>update Waterfall<commit_after>import React, {Component, Children, cloneElement} from 'react';
import {findDOMNode} from 'react-dom';
import PropTypes from 'prop-types';

import './Waterfall.css';

export default class Waterfall extends Component {

    constructor(props) {

        super(props);

        this.shouldRender = false;

        this.state = {
            dom: null
        };

        this.generateTempColumns = this::this.generateTempColumns;
        this.renderChildren = this::this.renderChildren;

    }

    initTempColumns(column) {

        if (!column || column.length < 1) {
            return;
        }

        const result = [];

        for (let i = 0; i < column; i++) {
            result.push({
                heightCount: 0,
                children: []
            });
        }

        return result;

    }

    getMinHeightColumn(columns) {

        if (!columns || columns.length < 1) {
            return;
        }

        let minItem = columns[0],
            min = minItem.heightCount;

        for (let i = 1, len = columns.length; i < len; i++) {
            if (columns[i].heightCount < min) {
                minItem = columns[i];
                min = columns[i].heightCount;
            }
        }

        return minItem;

    }

    generateTempColumns(props = this.props) {

        const {column, children} = props,
            tempColumns = this.initTempColumns(column);

        let el, elHeight, item;

        Children.forEach(children, (child, index) => {

            el = findDOMNode(this.refs[`waterfallTempChild${index}`]);
            if (el) {
                elHeight = parseInt(getComputedStyle(el).height);
                if (elHeight) {
                    item = this.getMinHeightColumn(tempColumns);
                    item.heightCount += elHeight;
                    item.children.push(child);
                }
            }

        });

        return tempColumns;

    }

    renderChildren(props = this.props) {

        const {column} = props,
            tempColumns = this.generateTempColumns(props),
            columnStyle = {
                width: `${100 / column}%`
            },
            result = [];

        for (let i = 0; i < column; i++) {
            result.push(

                    {tempColumns[i] && tempColumns[i].children}

            );
        }

        return result;

    }

    componentDidMount() {
        this.setState({
            dom: this.renderChildren()
        });
    }

    componentWillReceiveProps() {
        this.shouldRender = true;
    }

    componentDidUpdate(nextProps) {
        if (this.shouldRender) {
            this.shouldRender = false;
            this.setState({
                dom: this.renderChildren(nextProps)
            });
        }
    }

    render() {

        const {className, style, children} = this.props,
            {dom} = this.state;

        return (

                {dom}

                    {
                        children.map((child, index) => {
                            return cloneElement(child, {
                                key: index,
                                ref: `waterfallTempChild${index}`
                            });
                        })
                    }

        );
    }

}

Waterfall.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * Column count of waterfall.
     */
    column: PropTypes.number

};

Waterfall.defaultProps = {

    className: '',
    style: null,

    column: 3

};<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import {Hooks} from 'PluginSDK';

import Application from '../../structs/Application';
import Pod from '../../structs/Pod';

import {NEW_APP_DEFAULTS} from '../../constants/NewApplicationDefaults';
import {NEW_POD_DEFAULTS} from '../../constants/NewPodDefaults';

import FullScreenModal from '../../../../../../src/js/components/modals/FullScreenModal';
import FullScreenModalHeader from '../../../../../../src/js/components/modals/FullScreenModalHeader';
import FullScreenModalHeaderActions from '../../../../../../src/js/components/modals/FullScreenModalHeaderActions';
import FullScreenModalHeaderTitle from '../../../../../../src/js/components/modals/FullScreenModalHeaderTitle';
import NewCreateServiceModalServicePicker from './NewCreateServiceModalServicePicker';
import NewCreateServiceModalForm from './NewCreateServiceModalForm';
import CreateServiceJsonOnly from './CreateServiceJsonOnly';
import Service from '../../structs/Service';
import ServiceConfigDisplay from '../ServiceConfigDisplay';
import ServiceUtil from '../../utils/ServiceUtil';
import ToggleButton from '../../../../../../src/js/components/ToggleButton';
import Util from '../../../../../../src/js/utils/Util';

import ContainerServiceFormSection from '../forms/ContainerServiceFormSection';
import EnvironmentFormSection from '../forms/EnvironmentFormSection';
import GeneralServiceFormSection from '../forms/GeneralServiceFormSection';
import HealthChecksFormSection from '../forms/HealthChecksFormSection';
import VolumesFormSection from '../forms/VolumesFormSection';
import {combineParsers} from '../../../../../../src/js/utils/ParserUtil';
import {combineReducers} from '../../../../../../src/js/utils/ReducerUtil';
import JSONConfigReducers from '../../reducers/JSONConfigReducers';
import JSONParserReducers from '../../reducers/JSONParserReducers';

const METHODS_TO_BIND = [
  'handleGoBack',
  'handleClose',
  'handleJSONToggle',
  'handleServiceChange',
  'handleServiceErrorChange',
  'handleServiceReview',
  'handleServiceRun',
  'handleServiceSelection'
];

class NewServiceFormModal extends Component {
  constructor() {
    super(...arguments);

    this.state = this.getResetState();

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  /**
   * @override
   */
  componentWillUpdate(nextProps) {
    const requestCompleted = this.props.isPending && !nextProps.isPending;
    const shouldClose = requestCompleted && !nextProps.errors;

    if (shouldClose) {
      this.handleClose();
    }
  }

  /**
   * @override
   */
  componentWillReceiveProps(nextProps) {
    if (!ServiceUtil.isEqual(this.props.service, nextProps.service)) {
      this.setState({
        serviceConfig: this.getNormalizedServiceConfig(nextProps.service)
      });
    }
  }

  handleGoBack() {
    let {
      serviceFormActive,
      serviceJsonActive,
      servicePickerActive,
      serviceReviewActive
    } = this.state;

    // Close if picker is open, or if editing a service in the form
    if (servicePickerActive || (serviceFormActive && this.props.isEdit)) {
      this.handleClose();
      return;
    }

    if (serviceReviewActive) {
      // Just hide review screen. Form or JSON mode will be
      // activated automaticaly depending on their last state
      this.setState({
        serviceReviewActive: false
      });
      return;
    }

    if (serviceFormActive) {
      // Switch back from form to picker
      this.setState({
        servicePickerActive: true,
        serviceFormActive: false
      });
      return;
    }

    if (serviceJsonActive) {
      // Switch back from JSON to picker
      this.setState({
        servicePickerActive: true,
        serviceJsonActive: false
      });
      return;
    }
  }

  handleClose() {
    this.props.onClose();
    this.setState(this.getResetState());
  }

  handleJSONToggle() {
    this.setState({isJSONModeActive: !this.state.isJSONModeActive});
  }

  handleServiceChange(newService) {
    this.setState({
      serviceConfig: newService
    });
  }

  handleServiceErrorChange(hasErrors) {
    this.setState({
      serviceFormHasErrors: hasErrors
    });
  }

  handleServiceSelection({type}) {
    switch (type) {

      case 'app':
        this.setState({
          servicePickerActive: false,
          serviceFormActive: true,
          serviceConfig: new Application(
            Object.assign(
              {id: this.props.service.getId()},
              NEW_APP_DEFAULTS
            )
          )
        });
        break;

      case 'pod':
        this.setState({
          servicePickerActive: false,
          serviceFormActive: true,
          serviceConfig: new Pod(
            Object.assign(
              {id: this.props.service.getId()},
              NEW_POD_DEFAULTS
            )
          )
        });
        break;

      case 'json':
        this.setState({
          servicePickerActive: false,
          serviceJsonActive: true,
          serviceConfig: this.props.service
        });
        break;

    };
  }

  handleServiceReview() {
    this.setState({
      serviceReviewActive: true
    });
  }

  handleServiceRun() {
    let {marathonAction, service} = this.props;
    marathonAction(
      service,
      this.state.serviceConfig
    );
  }

  getHeader() {

    // NOTE: Always prioritize review screen check
    if (this.state.serviceReviewActive) {
      return (
        <FullScreenModalHeader>
          <FullScreenModalHeaderActions
            actions={this.getSecondaryActions()}
            type="secondary" />
          <FullScreenModalHeaderTitle>
            Review & Run Service
          </FullScreenModalHeaderTitle>
          <FullScreenModalHeaderActions
            actions={this.getPrimaryActions()}
            type="primary" />
        </FullScreenModalHeader>
      );
    }

    let title = 'Run a Service';
    let {isEdit, service} = this.props;
    let serviceName = service.getName();
    if (serviceName) {
      serviceName = `"${serviceName}"`;
    } else {
      serviceName = 'Service';
    }

    if (isEdit) {
      title = `Edit ${serviceName}`;
    }

    return (
      <FullScreenModalHeader>
        <FullScreenModalHeaderActions
          actions={this.getSecondaryActions()}
          type="secondary" />
        <FullScreenModalHeaderTitle>
          {title}
        </FullScreenModalHeaderTitle>
        <FullScreenModalHeaderActions
          actions={this.getPrimaryActions()}
          type="primary" />
      </FullScreenModalHeader>
    );
  }

  getModalContent() {
    // NOTE: Always prioritize review screen check
    if (this.state.serviceReviewActive) {
      return (
        <ServiceConfigDisplay appConfig={this.state.serviceConfig} />
      );
    }

    if (this.state.servicePickerActive) {
      return (
        <NewCreateServiceModalServicePicker
          onServiceSelect={this.handleServiceSelection} />
      );
    }

    if (this.state.serviceFormActive) {
      const SECTIONS = [
        ContainerServiceFormSection,
        EnvironmentFormSection,
        GeneralServiceFormSection,
        HealthChecksFormSection,
        VolumesFormSection
      ];

      const jsonParserReducers = combineParsers(
        Hooks.applyFilter('serviceCreateJsonParserReducers', JSONParserReducers)
      );
      const jsonConfigReducers = combineReducers(
        Hooks.applyFilter('serviceJsonConfigReducers', JSONConfigReducers)
      );
      const inputConfigReducers = combineReducers(
        Hooks.applyFilter('serviceInputConfigReducers',
          Object.assign({}, ...SECTIONS.map((item) => item.configReducers))
        )
      );

      return (
        <NewCreateServiceModalForm
          jsonParserReducers={jsonParserReducers}
          jsonConfigReducers={jsonConfigReducers}
          inputConfigReducers={inputConfigReducers}
          isJSONModeActive={this.state.isJSONModeActive}
          service={this.state.serviceConfig}
          onChange={this.handleServiceChange}
          onErrorStateChange={this.handleServiceErrorChange} />
      );
    }

    if (this.state.serviceJsonActive) {
      return (
        <CreateServiceJsonOnly
          service={this.state.serviceConfig}
          onChange={this.handleServiceChange}
          onErrorStateChange={this.handleServiceErrorChange} />
      );
    }

    return null;
  }

  getPrimaryActions() {
    let {
      serviceFormActive,
      serviceJsonActive,
      servicePickerActive,
      serviceReviewActive
    } = this.state;

    // NOTE: Always prioritize review screen check
    if (serviceReviewActive) {
      return [
        {
          className: 'button-primary flush-vertical',
          clickHandler: this.handleServiceRun,
          label: 'Run Service'
        }
      ];
    }

    if (servicePickerActive) {
      return null;
    }

    if (serviceFormActive) {
      return [
        {
          node: (
            <ToggleButton
              className="flush"
              checkboxClassName="toggle-button"
              checked={this.state.isJSONModeActive}
              onChange={this.handleJSONToggle}
              key="json-editor">
              JSON Editor
            </ToggleButton>
          )
        },
        {
          className: 'button-primary flush-vertical',
          clickHandler: this.handleServiceReview,
          disabled: this.state.serviceFormHasErrors,
          label: 'Review & Run'
        }
      ];
    }

    if (serviceJsonActive) {
      return [
        {
          className: 'button-primary flush-vertical',
          clickHandler: this.handleServiceReview,
          disabled: this.state.serviceFormHasErrors,
          label: 'Review & Run'
        }
      ];
    }

    return [];
  }

  getResetState(nextProps = this.props) {
    let newState = {
      isJSONModeActive: false,
      serviceConfig: this.getNormalizedServiceConfig(nextProps.service),
      serviceFormActive: false,
      serviceJsonActive: false,
      servicePickerActive: true,
      serviceReviewActive: false,
      serviceFormHasErrors: false
    };

    // Switch directly to form if edit
    if (nextProps.isEdit) {
      newState.servicePickerActive = false;
      newState.serviceFormActive = true;
    }

    return newState;
  }

  getSecondaryActions() {
    let {servicePickerActive, serviceFormActive} = this.state;
    let label = 'Back';
    if (servicePickerActive || (serviceFormActive && this.props.isEdit)) {
      label = 'Cancel';
    }

    return [
      {
        className: 'button-stroke',
        clickHandler: this.handleGoBack,
        label
      }
    ];
  }

  /**
   * Normalize the given `service` instance/config in order to match the
   * specifications required by the editing/reviewing components
   *
   * @param {Pod|Application|Object} service - The service to normalize
   * @returns {Pod|Application} Returns a pod or an application
   */
  getNormalizedServiceConfig(service) {
    // A Pod is defined by it's specifications, *NOT* by it's state. Therefore
    // we must extract and operate upon the `PodSpec` from the `Pod`.
    if (service instanceof Pod) {
      return service.getSpec();
    }

    return service;
  }

  render() {
    let {props} = this;

    return (
      <FullScreenModal
        header={this.getHeader()}
        onClose={this.handleClose}
        {...Util.omit(props, Object.keys(NewServiceFormModal.propTypes))}>
        {this.getModalContent()}
      </FullScreenModal>
    );
  }
}

NewServiceFormModal.propTypes = {
  errors: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.string
  ]),
  isEdit: PropTypes.bool,
  isPending: PropTypes.bool.isRequired,
  marathonAction: PropTypes.func.isRequired,
  onClose: PropTypes.func,
  service: PropTypes.instanceOf(Service).isRequired
};

module.exports = NewServiceFormModal;
<commit_msg>User service spec directly<commit_after>import React, {Component, PropTypes} from 'react';
import {Hooks} from 'PluginSDK';

import Application from '../../structs/Application';
import Pod from '../../structs/Pod';

import {NEW_APP_DEFAULTS} from '../../constants/NewApplicationDefaults';
import {NEW_POD_DEFAULTS} from '../../constants/NewPodDefaults';

import FullScreenModal from '../../../../../../src/js/components/modals/FullScreenModal';
import FullScreenModalHeader from '../../../../../../src/js/components/modals/FullScreenModalHeader';
import FullScreenModalHeaderActions from '../../../../../../src/js/components/modals/FullScreenModalHeaderActions';
import FullScreenModalHeaderTitle from '../../../../../../src/js/components/modals/FullScreenModalHeaderTitle';
import NewCreateServiceModalServicePicker from './NewCreateServiceModalServicePicker';
import NewCreateServiceModalForm from './NewCreateServiceModalForm';
import CreateServiceJsonOnly from './CreateServiceJsonOnly';
import Service from '../../structs/Service';
import ServiceConfigDisplay from '../ServiceConfigDisplay';
import ServiceUtil from '../../utils/ServiceUtil';
import ToggleButton from '../../../../../../src/js/components/ToggleButton';
import Util from '../../../../../../src/js/utils/Util';

import ContainerServiceFormSection from '../forms/ContainerServiceFormSection';
import EnvironmentFormSection from '../forms/EnvironmentFormSection';
import GeneralServiceFormSection from '../forms/GeneralServiceFormSection';
import HealthChecksFormSection from '../forms/HealthChecksFormSection';
import VolumesFormSection from '../forms/VolumesFormSection';
import {combineParsers} from '../../../../../../src/js/utils/ParserUtil';
import {combineReducers} from '../../../../../../src/js/utils/ReducerUtil';
import JSONConfigReducers from '../../reducers/JSONConfigReducers';
import JSONParserReducers from '../../reducers/JSONParserReducers';

const METHODS_TO_BIND = [
  'handleGoBack',
  'handleClose',
  'handleJSONToggle',
  'handleServiceChange',
  'handleServiceErrorChange',
  'handleServiceReview',
  'handleServiceRun',
  'handleServiceSelection'
];

class NewServiceFormModal extends Component {
  constructor() {
    super(...arguments);

    this.state = this.getResetState();

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  /**
   * @override
   */
  componentWillUpdate(nextProps) {
    const requestCompleted = this.props.isPending && !nextProps.isPending;
    const shouldClose = requestCompleted && !nextProps.errors;

    if (shouldClose) {
      this.handleClose();
    }
  }

  /**
   * @override
   */
  componentWillReceiveProps(nextProps) {
    if (!ServiceUtil.isEqual(this.props.service, nextProps.service)) {
      this.setState({
        serviceConfig: nextProps.service.getSpec()
      });
    }
  }

  handleGoBack() {
    let {
      serviceFormActive,
      serviceJsonActive,
      servicePickerActive,
      serviceReviewActive
    } = this.state;

    // Close if picker is open, or if editing a service in the form
    if (servicePickerActive || (serviceFormActive && this.props.isEdit)) {
      this.handleClose();
      return;
    }

    if (serviceReviewActive) {
      // Just hide review screen. Form or JSON mode will be
      // activated automaticaly depending on their last state
      this.setState({
        serviceReviewActive: false
      });
      return;
    }

    if (serviceFormActive) {
      // Switch back from form to picker
      this.setState({
        servicePickerActive: true,
        serviceFormActive: false
      });
      return;
    }

    if (serviceJsonActive) {
      // Switch back from JSON to picker
      this.setState({
        servicePickerActive: true,
        serviceJsonActive: false
      });
      return;
    }
  }

  handleClose() {
    this.props.onClose();
    this.setState(this.getResetState());
  }

  handleJSONToggle() {
    this.setState({isJSONModeActive: !this.state.isJSONModeActive});
  }

  handleServiceChange(newService) {
    this.setState({
      serviceConfig: newService
    });
  }

  handleServiceErrorChange(hasErrors) {
    this.setState({
      serviceFormHasErrors: hasErrors
    });
  }

  handleServiceSelection({type}) {
    switch (type) {

      case 'app':
        this.setState({
          servicePickerActive: false,
          serviceFormActive: true,
          serviceConfig: new Application(
            Object.assign(
              {id: this.props.service.getId()},
              NEW_APP_DEFAULTS
            )
          )
        });
        break;

      case 'pod':
        this.setState({
          servicePickerActive: false,
          serviceFormActive: true,
          serviceConfig: new Pod(
            Object.assign(
              {id: this.props.service.getId()},
              NEW_POD_DEFAULTS
            )
          )
        });
        break;

      case 'json':
        this.setState({
          servicePickerActive: false,
          serviceJsonActive: true,
          serviceConfig: this.props.service
        });
        break;

    };
  }

  handleServiceReview() {
    this.setState({
      serviceReviewActive: true
    });
  }

  handleServiceRun() {
    let {marathonAction, service} = this.props;
    marathonAction(
      service,
      this.state.serviceConfig
    );
  }

  getHeader() {

    // NOTE: Always prioritize review screen check
    if (this.state.serviceReviewActive) {
      return (
        <FullScreenModalHeader>
          <FullScreenModalHeaderActions
            actions={this.getSecondaryActions()}
            type="secondary" />
          <FullScreenModalHeaderTitle>
            Review & Run Service
          </FullScreenModalHeaderTitle>
          <FullScreenModalHeaderActions
            actions={this.getPrimaryActions()}
            type="primary" />
        </FullScreenModalHeader>
      );
    }

    let title = 'Run a Service';
    let {isEdit, service} = this.props;
    let serviceName = service.getName();
    if (serviceName) {
      serviceName = `"${serviceName}"`;
    } else {
      serviceName = 'Service';
    }

    if (isEdit) {
      title = `Edit ${serviceName}`;
    }

    return (
      <FullScreenModalHeader>
        <FullScreenModalHeaderActions
          actions={this.getSecondaryActions()}
          type="secondary" />
        <FullScreenModalHeaderTitle>
          {title}
        </FullScreenModalHeaderTitle>
        <FullScreenModalHeaderActions
          actions={this.getPrimaryActions()}
          type="primary" />
      </FullScreenModalHeader>
    );
  }

  getModalContent() {
    // NOTE: Always prioritize review screen check
    if (this.state.serviceReviewActive) {
      return (
        <ServiceConfigDisplay appConfig={this.state.serviceConfig} />
      );
    }

    if (this.state.servicePickerActive) {
      return (
        <NewCreateServiceModalServicePicker
          onServiceSelect={this.handleServiceSelection} />
      );
    }

    if (this.state.serviceFormActive) {
      const SECTIONS = [
        ContainerServiceFormSection,
        EnvironmentFormSection,
        GeneralServiceFormSection,
        HealthChecksFormSection,
        VolumesFormSection
      ];

      const jsonParserReducers = combineParsers(
        Hooks.applyFilter('serviceCreateJsonParserReducers', JSONParserReducers)
      );
      const jsonConfigReducers = combineReducers(
        Hooks.applyFilter('serviceJsonConfigReducers', JSONConfigReducers)
      );
      const inputConfigReducers = combineReducers(
        Hooks.applyFilter('serviceInputConfigReducers',
          Object.assign({}, ...SECTIONS.map((item) => item.configReducers))
        )
      );

      return (
        <NewCreateServiceModalForm
          jsonParserReducers={jsonParserReducers}
          jsonConfigReducers={jsonConfigReducers}
          inputConfigReducers={inputConfigReducers}
          isJSONModeActive={this.state.isJSONModeActive}
          service={this.state.serviceConfig}
          onChange={this.handleServiceChange}
          onErrorStateChange={this.handleServiceErrorChange} />
      );
    }

    if (this.state.serviceJsonActive) {
      return (
        <CreateServiceJsonOnly
          service={this.state.serviceConfig}
          onChange={this.handleServiceChange}
          onErrorStateChange={this.handleServiceErrorChange} />
      );
    }

    return null;
  }

  getPrimaryActions() {
    let {
      serviceFormActive,
      serviceJsonActive,
      servicePickerActive,
      serviceReviewActive
    } = this.state;

    // NOTE: Always prioritize review screen check
    if (serviceReviewActive) {
      return [
        {
          className: 'button-primary flush-vertical',
          clickHandler: this.handleServiceRun,
          label: 'Run Service'
        }
      ];
    }

    if (servicePickerActive) {
      return null;
    }

    if (serviceFormActive) {
      return [
        {
          node: (
            <ToggleButton
              className="flush"
              checkboxClassName="toggle-button"
              checked={this.state.isJSONModeActive}
              onChange={this.handleJSONToggle}
              key="json-editor">
              JSON Editor
            </ToggleButton>
          )
        },
        {
          className: 'button-primary flush-vertical',
          clickHandler: this.handleServiceReview,
          disabled: this.state.serviceFormHasErrors,
          label: 'Review & Run'
        }
      ];
    }

    if (serviceJsonActive) {
      return [
        {
          className: 'button-primary flush-vertical',
          clickHandler: this.handleServiceReview,
          disabled: this.state.serviceFormHasErrors,
          label: 'Review & Run'
        }
      ];
    }

    return [];
  }

  getResetState(nextProps = this.props) {
    let newState = {
      isJSONModeActive: false,
      serviceConfig: nextProps.service.getSpec(),
      serviceFormActive: false,
      serviceJsonActive: false,
      servicePickerActive: true,
      serviceReviewActive: false,
      serviceFormHasErrors: false
    };

    // Switch directly to form if edit
    if (nextProps.isEdit) {
      newState.servicePickerActive = false;
      newState.serviceFormActive = true;
    }

    return newState;
  }

  getSecondaryActions() {
    let {servicePickerActive, serviceFormActive} = this.state;
    let label = 'Back';
    if (servicePickerActive || (serviceFormActive && this.props.isEdit)) {
      label = 'Cancel';
    }

    return [
      {
        className: 'button-stroke',
        clickHandler: this.handleGoBack,
        label
      }
    ];
  }

  render() {
    let {props} = this;

    return (
      <FullScreenModal
        header={this.getHeader()}
        onClose={this.handleClose}
        {...Util.omit(props, Object.keys(NewServiceFormModal.propTypes))}>
        {this.getModalContent()}
      </FullScreenModal>
    );
  }
}

NewServiceFormModal.propTypes = {
  errors: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.string
  ]),
  isEdit: PropTypes.bool,
  isPending: PropTypes.bool.isRequired,
  marathonAction: PropTypes.func.isRequired,
  onClose: PropTypes.func,
  service: PropTypes.instanceOf(Service).isRequired
};

module.exports = NewServiceFormModal;
<|endoftext|>


<commit_before>define (["./datasource-component-plugin"], function (DataSourcePlugin) {
	var IgniteUIJSONPDataSourcePlugin = IgniteUIJSONPDataSourcePlugin || DataSourcePlugin.extend({
		init: function (options) {
			this._super(options);
		},
		getCodeEditorScriptSnippet: function (descriptor) {
			var code = "\t\t\t\twindow." + descriptor.id + " = new $.ig.JSONPDataSource({\n";
			code += "\t\t\t\t\ttype: \"json\",\n";
			var orderedReturnProps = [];
			// now write options / settings
			code += "\t\t\t\t});\n";
			orderedReturnProps.push({
				name: "type",
				value: "json",
				type: "string"
			});
			return {
				codeString: code,
				lineCount: 3,
				orderedProps: orderedReturnProps
			};
		},
		initComponent: function (descriptor) {
			window.frames[0][descriptor.id] = new $.ig.JSONPDataSource({
				type: "json"
			});
		},
		render: function (container, descriptor) {
			var ds = window.frames[0][descriptor.id], ide = this.settings.ide, locale = $.plugin.dataSource.locale,
				that = this, ide = this.settings.ide, dsval = ds.settings.dataSource, responseDataKey = ds.settings.responseDataKey,
				responseTotalRecCountKey = ds.settings.responseTotalRecCountKey, dscontainer, remoteContainer, localRemoteArea;
			//if (!(ds instanceof $.ig.DataSource)) {
			if (!(ds && ds._accumulatedTransactionLog)) {
				throw new Error("Object with ID " + descriptor.id + " is not an instance of IG Data Source");
			}
			descriptor.delayBind = 1000; // 1000 ms before the data source rebinds after a property has been changed

			container.empty(); // fix for 168980
			if (dsval === null) {
				dsval = "";
			}
			if (responseDataKey === null) {
				responseDataKey = "";
			}
			if (responseTotalRecCountKey === null) {
				responseTotalRecCountKey = "";
			}
			$(".adorner-summary-sheet").addClass("data-source-summary-sheet");
			container.children(".ds-diag-container").remove();
			dscontainer = $("

").prependTo(container).addClass("ds-diag-container");
			remoteContainer = $("

").appendTo(dscontainer).addClass("ds-diag-remotecontainer");
			localRemoteArea = $("

").addClass("ds-diag-dt").prependTo(dscontainer);
			// edit schema button
			$("" + locale.editSchema + "").addClass("btn btn-default ds-diag-editschema").wrap("
").parent().prependTo($(".adorner-custom-footer"));
			$("" + locale.urlEndpoint + "(" + locale.openTest + "" + ")" + "").addClass("ds-diag-urllabel").appendTo(remoteContainer);
			$("
<input type=\"text\" id=\"urlInput\" class=\"form-control\"/>").addClass("ds-diag-url").appendTo(remoteContainer);

			$("" + locale.responseDataKey + "").addClass("ds-diag-urllabel").appendTo(remoteContainer);
			$("
<input id=\"responseDataKeyInput\" type=\"text\" class=\"form-control\"/>
").addClass("ds-diag-url").appendTo(remoteContainer);
			$("" + locale.responseTotalRecCountKey + "").addClass("ds-diag-urllabel").appendTo(remoteContainer);
			$("
<input id=\"responseTotalRecCountKeyInput\" type=\"text\" class=\"form-control\"/>
").addClass("ds-diag-url").appendTo(remoteContainer);
			$("" + locale.setDataSource + "
").addClass("ds-diag-url").appendTo(remoteContainer);

			remoteContainer.find("#urlInput").val(dsval).keyup(function (event) {

				if (event.keyCode === 13) {
					descriptor.propName = "dataSource";
					descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
					descriptor.propType = "literal";
					descriptor.propValue = event.target.value.trim();
					that.update(descriptor);
				}
				event.preventDefault();
				event.stopPropagation();
			});
			remoteContainer.find("#responseDataKeyInput").val(responseDataKey).keyup(function (event) {
				// update the dataSource's url property
				//ds.settings.dataSource = event.target.value; // validate?
				//also update the code view
				if (event.keyCode === 13) {
					descriptor.propName = "responseDataKey";
					descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
					descriptor.propType = "string";
					descriptor.propValue = event.target.value.trim();
					that.update(descriptor);
				}
				event.preventDefault();
				event.stopPropagation();
			});
			remoteContainer.find("#responseTotalRecCountKeyInput").val(responseTotalRecCountKey).keyup(function (event) {
				// update the dataSource's url property
				//ds.settings.dataSource = event.target.value; // validate?
				//also update the code view
				if (event.keyCode === 13) {
					descriptor.propName = "responseTotalRecCountKey";
					descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
					descriptor.propType = "string";
					descriptor.propValue = event.target.value.trim();
					that.update(descriptor);
				}
				event.preventDefault();
				event.stopPropagation();
			});
			remoteContainer.find("#setButton").click(function (event) {
				var url = remoteContainer.find(".ds-diag-url > #urlInput").val(), testLabel = remoteContainer.find(".test-label"), locale = $.plugin.dataSource.locale;
				if (testLabel.length === 0) {
					testLabel = $("

").insertAfter(remoteContainer.find("#urlInput"));
				}
				if (url) {
					$.ajax({
						url: url,
						crossDomain: true,
						dataType: "jsonp"
					}).fail(function (jqXHR, textStatus, errorThrown) {
						var message;
						$("#modalDSError #errorDetails").css("display", "none");
						if (textStatus === "timeout") {
							message = locale.requestTimeout;
						} else if (textStatus === "parsererror") {
							message = locale.requestParserError;
							message = message.replace("{0}", "");
							message = message.replace("{1}", "");
						} else {
							message = locale.requestError;
							message = message.replace("{0}", jqXHR.status);
							message = message.replace("{1}", jqXHR.statusText);
							$("#modalDSError #responseerror").text(jqXHR.status);
							$("#modalDSError #responsestatus").text(jqXHR.statusText);
							$("#modalDSError #responsedatatype").text(jqXHR.responseXML ? "XML" : "Text");
							$("#modalDSError #responsecontent").text(jqXHR.responseXML ? jqXHR.responseXML : jqXHR.responseText);
							$("#modalDSError #errorDetails").css("display", "block");
						}
						$("#modalDSError #errorText").html(message);
						$("#modalDSError").dialog("open");
						$("[aria-describedby='modalDSError'").css("z-index", 20000);
						testLabel.addClass("test-fail").removeClass("test-success").text(locale.requestFailed);
					}).done(function () {
						descriptor.propName = "responseDataKey";
						descriptor.oldPropValue = "";
						descriptor.propType = "string";
						descriptor.propValue = $("#responseDataKeyInput").val().trim();
						that.update(descriptor);

						descriptor.propName = "responseTotalRecCountKey";
						descriptor.oldPropValue = "";
						descriptor.propType = "string";
						descriptor.propValue = $("#responseTotalRecCountKeyInput").val().trim();
						that.update(descriptor);

						descriptor.propName = "dataSource";
						descriptor.oldPropValue = "";
						descriptor.propType = "litearal";
						descriptor.propValue = remoteContainer.find(".ds-diag-url > #urlInput").val().trim();
						that.update(descriptor);
					});
				} else {
					testLabel.removeClass("test-fail").removeClass("test-success").text(locale.setValidUrl);
				}
			});
			remoteContainer.find("#openTestUrl").click(function () {
				var url = remoteContainer.find("#urlInput").val().trim();
				if (url && url !== "") {
					var win = window.open(url, "_blank");
					if (win) {
						win.focus();
					}
				}
			});
			// edit schema
			dscontainer.find(".ds-diag-editschema").click(function (event) {
				descriptor.compObject = ide.componentById(descriptor.id);
				descriptor.propName = "fields";
				descriptor.ide = ide;
				descriptor.propType = "array";
				descriptor.placeholder = descriptor.element; //TODO
				descriptor.provider = ide._codeProviders[descriptor.compObject.lib];
				var props = container.closest(".adorners").find("#propertyGrid").data("igGrid").dataSource.data();
				for (var i = 0; i < props.length; i++) {
					if (props[i].propName === "fields") {
						descriptor.schema = props[i].schema;
						descriptor.displayProp = props[i].displayProp;
						break;
					}
				}
				that.openCollectionEditor(descriptor);
			});
		}
	});
	return IgniteUIJSONPDataSourcePlugin;
});
<commit_msg>#169735 Update data source plug in to update the dataSource as a string value as the JSONP data Source accepts url as input<commit_after>define (["./datasource-component-plugin"], function (DataSourcePlugin) {
	var IgniteUIJSONPDataSourcePlugin = IgniteUIJSONPDataSourcePlugin || DataSourcePlugin.extend({
		init: function (options) {
			this._super(options);
		},
		getCodeEditorScriptSnippet: function (descriptor) {
			var code = "\t\t\t\twindow." + descriptor.id + " = new $.ig.JSONPDataSource({\n";
			code += "\t\t\t\t\ttype: \"json\"\n";
			var orderedReturnProps = [];
			// now write options / settings
			code += "\t\t\t\t});\n";
			orderedReturnProps.push({
				name: "type",
				value: "json",
				type: "string"
			});
			return {
				codeString: code,
				lineCount: 3,
				orderedProps: orderedReturnProps
			};
		},
		initComponent: function (descriptor) {
			window.frames[0][descriptor.id] = new $.ig.JSONPDataSource({
				type: "json"
			});
		},
		render: function (container, descriptor) {
			var ds = window.frames[0][descriptor.id], ide = this.settings.ide, locale = $.plugin.dataSource.locale,
				that = this, ide = this.settings.ide, dsval = ds.settings.dataSource, responseDataKey = ds.settings.responseDataKey,
				responseTotalRecCountKey = ds.settings.responseTotalRecCountKey, dscontainer, remoteContainer, localRemoteArea;
			//if (!(ds instanceof $.ig.DataSource)) {
			if (!(ds && ds._accumulatedTransactionLog)) {
				throw new Error("Object with ID " + descriptor.id + " is not an instance of IG Data Source");
			}
			descriptor.delayBind = 1000; // 1000 ms before the data source rebinds after a property has been changed

			container.empty(); // fix for 168980
			if (dsval === null) {
				dsval = "";
			}
			if (responseDataKey === null) {
				responseDataKey = "";
			}
			if (responseTotalRecCountKey === null) {
				responseTotalRecCountKey = "";
			}
			$(".adorner-summary-sheet").addClass("data-source-summary-sheet");
			container.children(".ds-diag-container").remove();
			dscontainer = $("

").prependTo(container).addClass("ds-diag-container");
			remoteContainer = $("

").appendTo(dscontainer).addClass("ds-diag-remotecontainer");
			localRemoteArea = $("

").addClass("ds-diag-dt").prependTo(dscontainer);
			// edit schema button
			$("" + locale.editSchema + "").addClass("btn btn-default ds-diag-editschema").wrap("
").parent().prependTo($(".adorner-custom-footer"));
			$("" + locale.urlEndpoint + "(" + locale.openTest + "" + ")" + "").addClass("ds-diag-urllabel").appendTo(remoteContainer);
			$("
<input type=\"text\" id=\"urlInput\" class=\"form-control\"/>").addClass("ds-diag-url").appendTo(remoteContainer);

			$("" + locale.responseDataKey + "").addClass("ds-diag-urllabel").appendTo(remoteContainer);
			$("
<input id=\"responseDataKeyInput\" type=\"text\" class=\"form-control\"/>
").addClass("ds-diag-url").appendTo(remoteContainer);
			$("" + locale.responseTotalRecCountKey + "").addClass("ds-diag-urllabel").appendTo(remoteContainer);
			$("
<input id=\"responseTotalRecCountKeyInput\" type=\"text\" class=\"form-control\"/>
").addClass("ds-diag-url").appendTo(remoteContainer);
			$("" + locale.setDataSource + "
").addClass("ds-diag-url").appendTo(remoteContainer);

			remoteContainer.find("#urlInput").val(dsval).keyup(function (event) {

				if (event.keyCode === 13) {
					descriptor.propName = "dataSource";
					descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
					descriptor.propType = "string";
					descriptor.propValue = event.target.value.trim();
					that.update(descriptor);
				}
				event.preventDefault();
				event.stopPropagation();
			});
			remoteContainer.find("#responseDataKeyInput").val(responseDataKey).keyup(function (event) {
				// update the dataSource's url property
				//ds.settings.dataSource = event.target.value; // validate?
				//also update the code view
				if (event.keyCode === 13) {
					descriptor.propName = "responseDataKey";
					descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
					descriptor.propType = "string";
					descriptor.propValue = event.target.value.trim();
					that.update(descriptor);
				}
				event.preventDefault();
				event.stopPropagation();
			});
			remoteContainer.find("#responseTotalRecCountKeyInput").val(responseTotalRecCountKey).keyup(function (event) {
				// update the dataSource's url property
				//ds.settings.dataSource = event.target.value; // validate?
				//also update the code view
				if (event.keyCode === 13) {
					descriptor.propName = "responseTotalRecCountKey";
					descriptor.oldPropValue = event.target.value ? event.target.value.substring(0, event.target.value.length - 1) : "";
					descriptor.propType = "string";
					descriptor.propValue = event.target.value.trim();
					that.update(descriptor);
				}
				event.preventDefault();
				event.stopPropagation();
			});
			remoteContainer.find("#setButton").click(function (event) {
				var url = remoteContainer.find(".ds-diag-url > #urlInput").val(), testLabel = remoteContainer.find(".test-label"), locale = $.plugin.dataSource.locale;
				if (testLabel.length === 0) {
					testLabel = $("

").insertAfter(remoteContainer.find("#urlInput"));
				}
				if (url) {
					$.ajax({
						url: url,
						crossDomain: true,
						dataType: "jsonp"
					}).fail(function (jqXHR, textStatus, errorThrown) {
						var message;
						$("#modalDSError #errorDetails").css("display", "none");
						if (textStatus === "timeout") {
							message = locale.requestTimeout;
						} else if (textStatus === "parsererror") {
							message = locale.requestParserError;
							message = message.replace("{0}", "");
							message = message.replace("{1}", "");
						} else {
							message = locale.requestError;
							message = message.replace("{0}", jqXHR.status);
							message = message.replace("{1}", jqXHR.statusText);
							$("#modalDSError #responseerror").text(jqXHR.status);
							$("#modalDSError #responsestatus").text(jqXHR.statusText);
							$("#modalDSError #responsedatatype").text(jqXHR.responseXML ? "XML" : "Text");
							$("#modalDSError #responsecontent").text(jqXHR.responseXML ? jqXHR.responseXML : jqXHR.responseText);
							$("#modalDSError #errorDetails").css("display", "block");
						}
						$("#modalDSError #errorText").html(message);
						$("#modalDSError").dialog("open");
						$("[aria-describedby='modalDSError'").css("z-index", 20000);
						testLabel.addClass("test-fail").removeClass("test-success").text(locale.requestFailed);
					}).done(function () {
						descriptor.propName = "responseDataKey";
						descriptor.oldPropValue = "";
						descriptor.propType = "string";
						descriptor.propValue = $("#responseDataKeyInput").val().trim();
						that.update(descriptor);

						descriptor.propName = "responseTotalRecCountKey";
						descriptor.oldPropValue = "";
						descriptor.propType = "string";
						descriptor.propValue = $("#responseTotalRecCountKeyInput").val().trim();
						that.update(descriptor);

						descriptor.propName = "dataSource";
						descriptor.oldPropValue = "";
						descriptor.propType = "string";
						descriptor.propValue = remoteContainer.find(".ds-diag-url > #urlInput").val().trim();
						that.update(descriptor);
					});
				} else {
					testLabel.removeClass("test-fail").removeClass("test-success").text(locale.setValidUrl);
				}
			});
			remoteContainer.find("#openTestUrl").click(function () {
				var url = remoteContainer.find("#urlInput").val().trim();
				if (url && url !== "") {
					var win = window.open(url, "_blank");
					if (win) {
						win.focus();
					}
				}
			});
			// edit schema
			dscontainer.find(".ds-diag-editschema").click(function (event) {
				descriptor.compObject = ide.componentById(descriptor.id);
				descriptor.propName = "fields";
				descriptor.ide = ide;
				descriptor.propType = "array";
				descriptor.placeholder = descriptor.element; //TODO
				descriptor.provider = ide._codeProviders[descriptor.compObject.lib];
				var props = container.closest(".adorners").find("#propertyGrid").data("igGrid").dataSource.data();
				for (var i = 0; i < props.length; i++) {
					if (props[i].propName === "fields") {
						descriptor.schema = props[i].schema;
						descriptor.displayProp = props[i].displayProp;
						break;
					}
				}
				that.openCollectionEditor(descriptor);
			});
		}
	});
	return IgniteUIJSONPDataSourcePlugin;
});
<|endoftext|>