<commit_before>'use strict';

var assertionUrl = 'https://3pp.io:4343/persona';
var postCommentUrl = 'https://3pp.io:4343/post/comment';
var serviceListUrl = 'https://3pp.io:4343/get/services';

$(document).ready(function(){
	var loggedInUser = null;

	function logout(){
		loggedInUser = null;
		var response = $.post(assertionUrl + '/logout');
		response.always(showPersona);
	}

	function verify(assertion){
		var response = $.ajax(assertionUrl + '/verify', {data: {assertion: assertion}, type: 'POST', xhrFields: {withCredentials: true}});
		response.done(login);
		response.fail(function(){
			navigator.id.logout();
		});
	}

	function login(data){
		showCommentForm(data.email);
	}

	navigator.id.watch({
		loggedInUser: loggedInUser,
		onlogin: verify,
		onlogout: logout
	});

	function showPersona(){
		$('#comment').html('
To comment, please sign in — you can use an existing email address.

');
		$('.signinButton').click(function(){ navigator.id.request(); }).css('cursor', 'pointer');
	}

	function showCommentForm(email){
		$('#comment').html('
Commenting as ' + email + ' (Not your email address?)
<form class="commentForm"><fieldset>
Title<input type="text" id="titleField" name="title" required />

<input type="radio" required name="point" id="pointBad" value="bad" />Bad<input type="radio" name="point" id="pointNeutral" value="neutral" />Neutral<input type="radio" name="point" id="pointGood" value="good" />Good

Service(s)<input id="servicesField" name="services" required class="input-large" />

Comment<textarea name="comment" id="commentField" required class="input-xxlarge"></textarea>

<button class="btn btn-primary" id="postComment">Send</button>
</fieldset></form>');

        var response = $.get(serviceListUrl, 'json');
        response.done(function(services){
            // Note: the width should be 'element', but for some reason it receives a different width than other input elements
            $('#servicesField').select2({tags: services, width: '220px', containerCss: {'border-radius': '4px'}});
        });

		$('.commentForm').submit(function(e){
			var response = $.ajax(postCommentUrl, {data: {title: $('#titleField').val(), point: $('input[name=point]:checked', '.commentForm').val(), services: $('#servicesField').val(), comment: $('#commentField').val()}, type: 'POST', xhrFields: {withCredentials: true}});
			response.done(showConfirmation);
			response.fail(showError);
			e.preventDefault();
		});
		$('.signoutButton').click(function(){ navigator.id.logout(); });
	}

	function showConfirmation(){
		$('#comment').html('Your comment has been submitted. Thank you!');
	}

	function showError(){
		$('#comment').prepend('
<button type="button" class="close" data-dismiss="alert">×</button>Something went wrong saving your comment, did you fill in all the fields?
');
	}

	showPersona();
});
<commit_msg>testing over http for now<commit_after>'use strict';

var assertionUrl = 'http://3pp.io:4343/persona';
var postCommentUrl = 'http://3pp.io:4343/post/comment';
var serviceListUrl = 'http://3pp.io:4343/get/services';

$(document).ready(function(){
	var loggedInUser = null;

	function logout(){
		loggedInUser = null;
		var response = $.post(assertionUrl + '/logout');
		response.always(showPersona);
	}

	function verify(assertion){
		var response = $.ajax(assertionUrl + '/verify', {data: {assertion: assertion}, type: 'POST', xhrFields: {withCredentials: true}});
		response.done(login);
		response.fail(function(){
			navigator.id.logout();
		});
	}

	function login(data){
		showCommentForm(data.email);
	}

	navigator.id.watch({
		loggedInUser: loggedInUser,
		onlogin: verify,
		onlogout: logout
	});

	function showPersona(){
		$('#comment').html('
To comment, please sign in — you can use an existing email address.

');
		$('.signinButton').click(function(){ navigator.id.request(); }).css('cursor', 'pointer');
	}

	function showCommentForm(email){
		$('#comment').html('
Commenting as ' + email + ' (Not your email address?)
<form class="commentForm"><fieldset>
Title<input type="text" id="titleField" name="title" required />

<input type="radio" required name="point" id="pointBad" value="bad" />Bad<input type="radio" name="point" id="pointNeutral" value="neutral" />Neutral<input type="radio" name="point" id="pointGood" value="good" />Good

Service(s)<input id="servicesField" name="services" required class="input-large" />

Comment<textarea name="comment" id="commentField" required class="input-xxlarge"></textarea>

<button class="btn btn-primary" id="postComment">Send</button>
</fieldset></form>');

        var response = $.get(serviceListUrl, 'json');
        response.done(function(services){
            // Note: the width should be 'element', but for some reason it receives a different width than other input elements
            $('#servicesField').select2({tags: services, width: '220px', containerCss: {'border-radius': '4px'}});
        });

		$('.commentForm').submit(function(e){
			var response = $.ajax(postCommentUrl, {data: {title: $('#titleField').val(), point: $('input[name=point]:checked', '.commentForm').val(), services: $('#servicesField').val(), comment: $('#commentField').val()}, type: 'POST', xhrFields: {withCredentials: true}});
			response.done(showConfirmation);
			response.fail(showError);
			e.preventDefault();
		});
		$('.signoutButton').click(function(){ navigator.id.logout(); });
	}

	function showConfirmation(){
		$('#comment').html('Your comment has been submitted. Thank you!');
	}

	function showError(){
		$('#comment').prepend('
<button type="button" class="close" data-dismiss="alert">×</button>Something went wrong saving your comment, did you fill in all the fields?
');
	}

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


<commit_before>var assert = require('assert');
var fs = require('fs');
var utils  = require('./testutils');
var Meta = utils.load_module('meta').Meta;

// Pay 100 XRP from rKmB to rLDY to create rLDY account
var createAccountBalanceChanges = [
  { address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '100',
      currency: 'XRP',
      issuer: ''
    }
  },
  { address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
    balance_change: {
      value: '-100.012',
      currency: 'XRP',
      issuer: ''
    },
  }
];

// Pay 0.01 USD from rKmB to rLDY where rLDY starts with no USD
var usdFirstPaymentBalanceChanges = [
  { address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
    balance_change: {
      value: '-0.01',
      currency: 'USD',
      issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
    }
  },
  { address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '0.01',
      currency: 'USD',
      issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
    }
  },
  { address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
    balance_change: {
      value: '-0.012',
      currency: 'XRP',
      issuer: ''
    }
  }
];

// Pay 0.2 USD from rLDY to rKmB where rLDY starts with 0.2 USD
var usdFullPaymentBalanceChanges = [
  { address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
    balance_change: {
      value: '0.2',
      currency: 'USD',
      issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
    }
  },
  { address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '-0.2',
      currency: 'USD',
      issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
    }
  },
  { address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '-0.012',
      currency: 'XRP',
      issuer: ''
    }
  }
];

// Pay 0.01 USD from rKmB to rLDY where rLDY starts with 0.01 USD
var usdPaymentBalanceChanges = usdFirstPaymentBalanceChanges;

// Set trust limit to 200 USD on rLDY when it has a trust limit of 100 USD
// and has a balance of 0.02 USD
var setTrustlineBalanceChanges = [
  {
    address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '-0.012',
      currency: 'XRP',
      issuer: ''
    }
  }
];

// Set trust limit to 100 USD on rLDY when it has no trustline
var createTrustlineBalanceChanges = setTrustlineBalanceChanges;

// Pay 0.02 USD from rLDY to rKmB when rLDY has a trust limit of 0
// for USD, but still has a balance of 0.02 USD; which closes the trustline
var deleteTrustlineBalanceChanges = [
    {
      address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
      balance_change: {
        value: '0.02',
        currency: 'USD',
        issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
      }
    },
    {
      address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
      balance_change: {
        value: '-0.02',
        currency: 'USD',
        issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
      }
    },
    {
      address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
      balance_change: {
        value: '-0.012',
        currency: 'XRP',
        issuer: ''
      }
    }
];

// Set trust limit to zero on rLDY when it has a balance of 0.02 USD
var removeTrustBalanceChanges = setTrustlineBalanceChanges;

function loadFixture(filename) {
  var path = __dirname + '/fixtures/' + filename;
  return JSON.parse(fs.readFileSync(path));
}

function parseBalanceChanges(metadata) {
  var meta = new Meta(metadata);
  return JSON.parse(JSON.stringify(meta.parseBalanceChanges()));
}

describe('parseBalanceChanges', function() {
  it('XRP create account', function() {
    var paymentResponse = loadFixture('payment-xrp-create-account.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, createAccountBalanceChanges);
  });
  it('USD payment to account with no USD', function() {
    var filename = 'payment-iou-destination-no-balance.json';
    var paymentResponse = loadFixture(filename);
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, usdFirstPaymentBalanceChanges);
  });
  it('USD payment of all USD in source account', function() {
    var paymentResponse = loadFixture('payment-iou-spend-full-balance.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, usdFullPaymentBalanceChanges);
  });
  it('USD payment to account with USD', function() {
    var paymentResponse = loadFixture('payment-iou.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, usdPaymentBalanceChanges);
  });
  it('Set trust limit to 0 with balance remaining', function() {
    var paymentResponse = loadFixture('trustline-set-limit-to-zero.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, removeTrustBalanceChanges);
  });
  it('Create trustline', function() {
    var paymentResponse = loadFixture('trustline-create.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, createTrustlineBalanceChanges);
  });
  it('Set trustline', function() {
    var paymentResponse = loadFixture('trustline-set-limit.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, setTrustlineBalanceChanges);
  });
  it('Delete trustline', function() {
    var paymentResponse = loadFixture('trustline-delete.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, deleteTrustlineBalanceChanges);
  });
});
<commit_msg>[TEST] fix Meta require<commit_after>var assert = require('assert');
var fs = require('fs');
var Meta = require('ripple-lib').Meta;

// Pay 100 XRP from rKmB to rLDY to create rLDY account
var createAccountBalanceChanges = [
  { address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '100',
      currency: 'XRP',
      issuer: ''
    }
  },
  { address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
    balance_change: {
      value: '-100.012',
      currency: 'XRP',
      issuer: ''
    },
  }
];

// Pay 0.01 USD from rKmB to rLDY where rLDY starts with no USD
var usdFirstPaymentBalanceChanges = [
  { address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
    balance_change: {
      value: '-0.01',
      currency: 'USD',
      issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
    }
  },
  { address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '0.01',
      currency: 'USD',
      issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
    }
  },
  { address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
    balance_change: {
      value: '-0.012',
      currency: 'XRP',
      issuer: ''
    }
  }
];

// Pay 0.2 USD from rLDY to rKmB where rLDY starts with 0.2 USD
var usdFullPaymentBalanceChanges = [
  { address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
    balance_change: {
      value: '0.2',
      currency: 'USD',
      issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
    }
  },
  { address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '-0.2',
      currency: 'USD',
      issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
    }
  },
  { address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '-0.012',
      currency: 'XRP',
      issuer: ''
    }
  }
];

// Pay 0.01 USD from rKmB to rLDY where rLDY starts with 0.01 USD
var usdPaymentBalanceChanges = usdFirstPaymentBalanceChanges;

// Set trust limit to 200 USD on rLDY when it has a trust limit of 100 USD
// and has a balance of 0.02 USD
var setTrustlineBalanceChanges = [
  {
    address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
    balance_change: {
      value: '-0.012',
      currency: 'XRP',
      issuer: ''
    }
  }
];

// Set trust limit to 100 USD on rLDY when it has no trustline
var createTrustlineBalanceChanges = setTrustlineBalanceChanges;

// Pay 0.02 USD from rLDY to rKmB when rLDY has a trust limit of 0
// for USD, but still has a balance of 0.02 USD; which closes the trustline
var deleteTrustlineBalanceChanges = [
    {
      address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
      balance_change: {
        value: '0.02',
        currency: 'USD',
        issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
      }
    },
    {
      address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
      balance_change: {
        value: '-0.02',
        currency: 'USD',
        issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q'
      }
    },
    {
      address: 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K',
      balance_change: {
        value: '-0.012',
        currency: 'XRP',
        issuer: ''
      }
    }
];

// Set trust limit to zero on rLDY when it has a balance of 0.02 USD
var removeTrustBalanceChanges = setTrustlineBalanceChanges;

function loadFixture(filename) {
  var path = __dirname + '/fixtures/' + filename;
  return JSON.parse(fs.readFileSync(path));
}

function parseBalanceChanges(metadata) {
  var meta = new Meta(metadata);
  return JSON.parse(JSON.stringify(meta.parseBalanceChanges()));
}

describe('parseBalanceChanges', function() {
  it('XRP create account', function() {
    var paymentResponse = loadFixture('payment-xrp-create-account.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, createAccountBalanceChanges);
  });
  it('USD payment to account with no USD', function() {
    var filename = 'payment-iou-destination-no-balance.json';
    var paymentResponse = loadFixture(filename);
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, usdFirstPaymentBalanceChanges);
  });
  it('USD payment of all USD in source account', function() {
    var paymentResponse = loadFixture('payment-iou-spend-full-balance.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, usdFullPaymentBalanceChanges);
  });
  it('USD payment to account with USD', function() {
    var paymentResponse = loadFixture('payment-iou.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, usdPaymentBalanceChanges);
  });
  it('Set trust limit to 0 with balance remaining', function() {
    var paymentResponse = loadFixture('trustline-set-limit-to-zero.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, removeTrustBalanceChanges);
  });
  it('Create trustline', function() {
    var paymentResponse = loadFixture('trustline-create.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, createTrustlineBalanceChanges);
  });
  it('Set trustline', function() {
    var paymentResponse = loadFixture('trustline-set-limit.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, setTrustlineBalanceChanges);
  });
  it('Delete trustline', function() {
    var paymentResponse = loadFixture('trustline-delete.json');
    var result = parseBalanceChanges(paymentResponse.metadata);
    assert.deepEqual(result, deleteTrustlineBalanceChanges);
  });
});
<|endoftext|>


<commit_before>const { ProvidePlugin } = require('webpack')
const CopyPlugin = require('copy-webpack-plugin')

module.exports = {
  plugins: [
    new ProvidePlugin({
      PouchDB: 'pouchdb',
      pouchdbFind: 'pouchdb-find',
      pouchdbAdapterCordovaSqlite: 'pouchdb-adapter-cordova-sqlite'
    }),
    new CopyPlugin([
      {
        from: 'src/drive/mobile/assets/fonts/',
        to: 'app/'
      }
    ])
  ]
}
<commit_msg>refactor: Remove unsued global pouch<commit_after>const CopyPlugin = require('copy-webpack-plugin')

module.exports = {
  plugins: [
    new CopyPlugin([
      {
        from: 'src/drive/mobile/assets/fonts/',
        to: 'app/'
      }
    ])
  ]
}
<|endoftext|>


<commit_before>// Memory game //

// variables
var choix1 = [];
var choix2 = [];
var compare = 0;
var images = ["img/Movie1.jpg", "img/Movie1.jpg", "img/Movie2.jpg", "img/Movie2.jpg", "img/Movie3.jpg", "img/Movie3.jpg", "img/Movie4.jpg", "img/Movie4.jpg", "img/Movie5.jpg", "img/Movie5.jpg", "img/Movie6.jpg", "img/Movie6.jpg", "img/Movie7.jpg", "img/Movie7.jpg"];
var imageDom = document.getElementsByClassName('card');

for (var position = images.length - 1; position >= 1; position--) {
    var hasard = Math.floor(Math.random() * (position + 1));
    var sauve = images[position];
    images[position] = images[hasard];
    images[hasard] = sauve;

}

//for images melanger
for (var i = 0; i < imageDom.length; i++) {

    imageDom[i].className += " " + images[i];
}
for (var i = 0; i < images.length; i++) {
    imageDom[i].firstChild.src = images[i];
    console.log(images);
}

function stock(obj) {
    //obj.
    choix1.push(obj.classList[1]);
    choix2.push(obj.id);
    console.log(choix2);
    console.log(choix1);
}

// function
function play(obj) {
    if (compare == 0) {
        //mettre ce qui se passe au premier click
        stock(obj);
        console.log(choix1);
        //style
        obj.firstChild.style.opacity = "1";
        console.log(compare);
        compare++;

    } else {
        //ce qui se passe au deuxieme click
        stock(obj);
        //styles
        obj.firstChild.style.opacity = "1";
        console.log(compare);
        //compare
        if (choix1[0] == choix1[1]) {
            console.log(choix1);

            alert("oui");
						choix2 = [];
            choix1=[];
        } else {
            console.log(choix1);
            choix1 = [];
            alert("no");
            console.log("choix2: " + choix2);

            for (var i = 0; i < choix2.length; i++) {
                // obj.firstChild.style.opacity="0";
                console.log(document.getElementById(choix2[i]));

                document.getElementById(choix2[i]).firstChild.style.opacity = "0";
            }
						choix2 = [];
        }
        compare = 0;
    }

    console.log(choix1);

};

// function

// script

// Memory game //
<commit_msg>Modification in the script in order to make it cleaner<commit_after>// Memory game //

var choix1 = [];
var choix2 = [];
var compare = 0;
var images = ["img/Movie1.jpg", "img/Movie1.jpg", "img/Movie2.jpg", "img/Movie2.jpg", "img/Movie3.jpg", "img/Movie3.jpg", "img/Movie4.jpg", "img/Movie4.jpg", "img/Movie5.jpg", "img/Movie5.jpg", "img/Movie6.jpg", "img/Movie6.jpg", "img/Movie7.jpg", "img/Movie7.jpg"];
var imageDom = document.getElementsByClassName('card');

for (var position = images.length - 1; position >= 1; position--) {
    var hasard = Math.floor(Math.random() * (position + 1));
    var sauve = images[position];
    images[position] = images[hasard];
    images[hasard] = sauve;

}

for (var i = 0; i < imageDom.length; i++) {

    imageDom[i].className += " " + images[i];
}
for (var i = 0; i < images.length; i++) {
    imageDom[i].firstChild.src = images[i];
    console.log(images);
}

function stock(obj) {

    choix1.push(obj.classList[1]);
    choix2.push(obj.id);
    console.log(choix2);
    console.log(choix1);
}

function play(obj) {
    if (compare == 0) {

        stock(obj);
        console.log(choix1);

        obj.firstChild.style.opacity = "1";
        console.log(compare);
        compare++;

    } else {

        stock(obj);

        obj.firstChild.style.opacity = "1";
        console.log(compare);

        if (choix1[0] == choix1[1]) {
            console.log(choix1);

            alert("Good Game! Keep going ...");
						choix2 = [];
            choix1=[];
        } else {
            console.log(choix1);
            choix1 = [];
            alert("Damn!!! Born to be a Loser? TRY AGAIN !");
            console.log("choix2: " + choix2);

            for (var i = 0; i < choix2.length; i++) {
                console.log(document.getElementById(choix2[i]));

                document.getElementById(choix2[i]).firstChild.style.opacity = "0";
            }
						choix2 = [];
        }
        compare = 0;
    }

    console.log(choix1);

};

// Memory game //
<|endoftext|>


<commit_before>$.extend(Operation, {
  exec: function(script, players, location, callback) {
    var site = location.split(' ')[0].resource();
    var loc = site.id.resource_type() == 'Landmark' ? site.title : '-';
    var params = {
      script:   script,
      items:    players,
      location: location,
      city:     This.city_id,
      lat:  site.lat,
      lng:  site.lng,
      loc:  loc
    };

    if (demo || test) return alert("CEML exec: " + $.param(params));
    if (!App.stream_role_organizer()) return Notifier.error("You must be an organizer on this squad to run operations.");

    if (window.sms_remaining <= 0) {
      $.post('/api/bugreport', {issue: window.current_stream + ' has run out of text messages!'});
      alert('You have reached your limit on text messages!  ' +
        'Please contact Groundcrew support to purchase more.');
      return false;
    }

    return $.post_with_squad('/exec', params, function(op_javascript){
      most_recent_op = null;
      eval(op_javascript);
      if (callback) callback(most_recent_op);
      if (most_recent_op) go('@' + most_recent_op.id);
    }, 'text');
  }
});
<commit_msg>fixed execing op w/out agents or loc<commit_after>$.extend(Operation, {
  exec: function(script, players, location, callback) {
    var site = location && location.split(' ')[0].resource();
    var loc = site && (site.id.resource_type() == 'Landmark' ? site.title : '-');
    var params = {
      script:   script,
      items:    players           || undefined,
      location: location          || undefined,
      city:     This.city_id      || undefined,
      lat:      site && site.lat  || undefined,
      lng:      site && site.lng  || undefined,
      loc:      loc               || undefined
    };

    if (demo || test) return alert("CEML exec: " + $.param(params));
    if (!App.stream_role_organizer()) return Notifier.error("You must be an organizer on this squad to run operations.");

    if (window.sms_remaining <= 0) {
      $.post('/api/bugreport', {issue: window.current_stream + ' has run out of text messages!'});
      alert('You have reached your limit on text messages!  ' +
        'Please contact Groundcrew support to purchase more.');
      return false;
    }

    return $.post_with_squad('/exec', params, function(op_javascript){
      most_recent_op = null;
      eval(op_javascript);
      if (callback) callback(most_recent_op);
      if (most_recent_op) go('@' + most_recent_op.id);
    }, 'text');
  }
});
<|endoftext|>


<commit_before>
angular.module('codingBarrierApp').controller('contactController', function ($rootScope, $scope, $http) {
    $rootScope.header = 'Contact';
    $rootScope.message = 'This will be my contact page!';

    $scope.clear = function () {
        $scope.form.name = '';
        $scope.form.email = '';
        $scope.form.subject = '';
        $scope.form.message = '';
    };

    $scope.sendEmail = function () {
        $http({
            method: 'POST',
            url: '/mail/',
            data: $.param($scope.form), // pass in data as strings
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })
                .success(function () {

                });
    };
});<commit_msg>Server sends depending on website domain.<commit_after>
angular.module('codingBarrierApp').controller('contactController', function ($rootScope, $scope, $http) {
    $rootScope.header = 'Contact';
    $rootScope.message = 'This will be my contact page!';

    $scope.clear = function (form) {
        if (form) {
            form.$setPristine();
            form.$setUntouched();
        }
        $scope.user = {};
    };

    $scope.sendEmail = function () {
        if ($rootScope.siteName.indexOf("Coding") > 0) {
            $scope.user.to="Anthony B <anthony@codingbarrier.com>";
        } else {
            $scope.user.to="Anthony B <mail@anthonybarrera.com>";
        }
        console.log($.param($scope.user));
        $http({
            method: 'POST',
            url: '/mail/',
            data: $.param($scope.user), // pass in data as strings
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })
                .success(function () {

                });
    };

    $scope.clear();
});<|endoftext|>


<commit_before>"use strict";

var TextPropertyManager = require('../../../document/text_property_manager');
var sample = require('../../fixtures/container_anno_sample');

var manager;
var doc;
var textProp1, textProp2, textProp3;

var MockTextProperty = function(path) {
  this.path = path;
  this.setFragments = sinon.spy();
  this.update = sinon.spy();
  this.getPath = function() {
    return this.path;
  };
};

function _textProp1() {
  textProp1 = new MockTextProperty(["p1", "content"]);
  manager.registerProperty(textProp1);
}
function _textProp2() {
  textProp2 = new MockTextProperty(["p2", "content"]);
  manager.registerProperty(textProp2);
}
function _textProp3() {
  textProp3 = new MockTextProperty(["p3", "content"]);
  manager.registerProperty(textProp3);
}

QUnit.module('Substance.Document/TextPropertManager', {
  beforeEach: function() {
    doc = sample();
    manager = new TextPropertyManager(doc, 'main');
    _textProp1();
  },
  afterEach: function() {
    manager = null;
    textProp1 = null;
    textProp2 = null;
    textProp3 = null;
  }
});

QUnit.test("Manager should load existing container annotations.", function(assert) {
  assert.equal(manager.getFragments(['p1', 'content']).length, 1, "There should be one fragment for p1.content.");
  assert.equal(manager.getFragments(['p2', 'content']).length, 1, "There should be one fragment for p2.content.");
  assert.equal(manager.getFragments(['p3', 'content']).length, 1, "There should be one fragment for p3.content.");
});

QUnit.test("Call update when property is updated.", function(assert) {
  doc.transaction(function(tx) {
    tx.update(textProp1.path, { "insert": { offset: 0, value: 'a' } } );
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
});

QUnit.test("Call update when an annotation is created.", function(assert) {
  doc.transaction(function(tx) {
    tx.create({
      id: "test-anno",
      type: "annotation",
      path: textProp1.path,
      startOffset: 0,
      endOffset: 1
    });
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
});

QUnit.test("Call update when an annotation is removed.", function(assert) {
  doc.transaction(function(tx) {
    tx.delete("a2");
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
});

QUnit.test("Call update when an annotation has been updated.", function(assert) {
  doc.transaction(function(tx) {
    tx.set(["a2", "startOffset"], 1);
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
  textProp1.update.reset();
  doc.transaction(function(tx) {
    tx.set(["a2", "endOffset"], 7);
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
});

QUnit.test("Call update when an annotation has been transferred.", function(assert) {
  _textProp2();

  doc.transaction(function(tx) {
    tx.set(["a2", "path"], ["p2", "content"]);
  });
  assert.equal(textProp1.update.callCount, 1, "First property should have been updated.");
  assert.equal(textProp2.update.callCount, 1, "Second component should have been updated.");
});

QUnit.test("Set fragments when a container annotation has been created.", function(assert) {
  _textProp2();
  _textProp3();

  doc.transaction(function(tx) {
    tx.create({
      id: "test-ca",
      type: "test-container-anno",
      container: "main",
      startPath: ["p1", "content"],
      startOffset: 0,
      endPath: ["p3", "content"],
      endOffset: 5
    });
  });
  assert.equal(textProp1.setFragments.callCount, 1, "first.setFragments should have been called.");
  assert.equal(textProp1.setFragments.args[0][0].length, 2, "First property should have received two fragments.");
  assert.equal(textProp2.setFragments.callCount, 1, "second.setFragments should have been called.");
  assert.equal(textProp1.setFragments.args[0][0].length, 2, "Second property should have received two fragments.");
  assert.equal(textProp3.setFragments.callCount, 1, "third.setFragments should have been called.");
  assert.equal(textProp1.setFragments.args[0][0].length, 2, "Second property should have received two fragments.");
});
<commit_msg>Added a test revealing that TextPropertyManager is called too early.<commit_after>"use strict";

var TextPropertyManager = require('../../../document/text_property_manager');
var sample = require('../../fixtures/container_anno_sample');

var manager;
var doc;
var textProp1, textProp2, textProp3;

var MockTextProperty = function(path) {
  this.path = path;
  this.setFragments = sinon.spy();
  this.update = sinon.spy();
  this.getPath = function() {
    return this.path;
  };
};

function _textProp1() {
  textProp1 = new MockTextProperty(["p1", "content"]);
  manager.registerProperty(textProp1);
}
function _textProp2() {
  textProp2 = new MockTextProperty(["p2", "content"]);
  manager.registerProperty(textProp2);
}
function _textProp3() {
  textProp3 = new MockTextProperty(["p3", "content"]);
  manager.registerProperty(textProp3);
}

QUnit.module('Substance.Document/TextPropertManager', {
  beforeEach: function() {
    doc = sample();
    TextPropertyManager.prototype.onDocumentChange = sinon.spy(TextPropertyManager.prototype.onDocumentChange);
    manager = new TextPropertyManager(doc, 'main');
    _textProp1();
  },
  afterEach: function() {
    manager = null;
    textProp1 = null;
    textProp2 = null;
    textProp3 = null;
  }
});

QUnit.test("Manager should load existing container annotations.", function(assert) {
  assert.equal(manager.getFragments(['p1', 'content']).length, 1, "There should be one fragment for p1.content.");
  assert.equal(manager.getFragments(['p2', 'content']).length, 1, "There should be one fragment for p2.content.");
  assert.equal(manager.getFragments(['p3', 'content']).length, 1, "There should be one fragment for p3.content.");
});

QUnit.test("Call update when property is updated.", function(assert) {
  doc.transaction(function(tx) {
    tx.update(textProp1.path, { "insert": { offset: 0, value: 'a' } } );
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
});

QUnit.test("Call update when an annotation is created.", function(assert) {
  doc.transaction(function(tx) {
    tx.create({
      id: "test-anno",
      type: "annotation",
      path: textProp1.path,
      startOffset: 0,
      endOffset: 1
    });
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
});

QUnit.test("Call update when an annotation is removed.", function(assert) {
  doc.transaction(function(tx) {
    tx.delete("a2");
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
});

QUnit.test("Call update when an annotation has been updated.", function(assert) {
  doc.transaction(function(tx) {
    tx.set(["a2", "startOffset"], 1);
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
  textProp1.update.reset();
  doc.transaction(function(tx) {
    tx.set(["a2", "endOffset"], 7);
  });
  assert.equal(textProp1.update.callCount, 1, "Property should have been updated.");
});

QUnit.test("Call update when an annotation has been transferred.", function(assert) {
  _textProp2();

  doc.transaction(function(tx) {
    tx.set(["a2", "path"], ["p2", "content"]);
  });
  assert.equal(textProp1.update.callCount, 1, "First property should have been updated.");
  assert.equal(textProp2.update.callCount, 1, "Second component should have been updated.");
});

QUnit.test("Set fragments when a container annotation has been created.", function(assert) {
  _textProp2();
  _textProp3();

  doc.transaction(function(tx) {
    tx.create({
      id: "test-ca",
      type: "test-container-anno",
      container: "main",
      startPath: ["p1", "content"],
      startOffset: 0,
      endPath: ["p3", "content"],
      endOffset: 5
    });
  });
  assert.equal(textProp1.setFragments.callCount, 1, "first.setFragments should have been called.");
  assert.equal(textProp1.setFragments.args[0][0].length, 2, "First property should have received two fragments.");
  assert.equal(textProp2.setFragments.callCount, 1, "second.setFragments should have been called.");
  assert.equal(textProp1.setFragments.args[0][0].length, 2, "Second property should have received two fragments.");
  assert.equal(textProp3.setFragments.callCount, 1, "third.setFragments should have been called.");
  assert.equal(textProp1.setFragments.args[0][0].length, 2, "Second property should have received two fragments.");
});

// For instance, updating a ContainerNode might lead to new rendered
// properties. TextPropertyManager should not process changes for those
// after they could register.
// TODO: this seems a bit hacky still
QUnit.test("TextPropertyManager is updated after other Components.", function(assert) {
  var other = sinon.spy();
  // registering another listener, which could be another component, such as ContainerNode
  doc.on('document:changed', other);
  // debugger;
  doc.transaction(function(tx) {
    tx.update(textProp1.path, { "insert": { offset: 0, value: 'a' } } );
  });
  assert.ok(other.calledBefore(manager.onDocumentChange), "TextPropertyManager should have been called later.");
});
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';
import t from 'tcomb';
import { props } from 'tcomb-react';
import omit from 'lodash/omit';
import DatePicker from './DatePicker';
import { Value } from './utils/model';
import { format, valueLink, skinnable } from './utils';
import cx from 'classnames';
import Input from './Input';

const INVALID = 'Invalid date';
const ENTER_KEYCODE = 13;

export const Props = {
  value: t.maybe(Value),
  valueLink: t.maybe(t.interface({
    value: t.maybe(Value),
    requestChange: t.Function
  })),
  onChange: t.maybe(t.Function),
  onShow: t.maybe(t.Function),
  onHide: t.maybe(t.Function),
  onClear: t.maybe(t.Function),
  small: t.maybe(t.Boolean),
  defaultValue: t.maybe(Value),
  minDate: t.maybe(Value),
  maxDate: t.maybe(Value),
  locale: t.maybe(t.String),
  startMode: t.maybe(t.enums.of(['day', 'month', 'year'])),
  fixedMode: t.maybe(t.Boolean),
  displayFormat: t.maybe(t.String),
  returnFormat: t.maybe(t.String),
  format: t.maybe(t.String),
  validationFormat: t.maybe(t.String),
  showOnInputClick: t.maybe(t.Boolean),
  closeOnClickOutside: t.maybe(t.Boolean),
  showInputButton: t.maybe(t.Boolean),
  autoClose: t.maybe(t.Boolean),
  floating: t.maybe(t.Boolean),
  iconClassName: t.maybe(t.String),
  iconClearClassName: t.maybe(t.String),
  className: t.maybe(t.String), // used to omit from inputProps
  style: t.maybe(t.Object) // used to omit from inputProps
};

/** A decent and pretty date picker to be used with React
 * @param value - current date
 * @param valueLink - valueLink object to replace "value" and "onChange"
 * @param onChange - called when value changes
 * @param onShow - called when datepicker is opened
 * @param onHide - called when datepicker is closed
 * @param onClear - called when value is cleared
 * @param small - whether it's small or not
 * @param defaultValue - default date
 * @param minDate - minimum date selectable by the user
 * @param maxDate - maximum date selectable by the user
 * @param locale - locale used for translations
 * @param startMode - the start view of the datepicker
 * @param fixedMode - whether the user can use multiple views or not
 * @param displayFormat - MomentJS format used to display current date
 * @param returnFormat - MomentJS format used to format date before returing through "onChange"
 * @param format - MomentJS format used to format date before returing through "onChange"
 * @param validationFormat - MomentJS format used to format date before returing through "onChange"
 * @param showOnInputClick - whether the datepicker should open when user click on the input
 * @param closeOnClickOutside - whether the datepicker should close when user clicks outside of it
 * @param showInputButton - whether the input-button should be rendered
 * @param autoClose - pass true if you want the datepicker to close automatically after the user selects a value
 * @param floating - whether the datepicker should float over the page content (absolute position)
 * @param iconClassName - classname used for the icon
 * @param iconClearClassName - classname used for the clear icon
 */

@format
@valueLink
@skinnable()
@props(Props, { strict: false })
export default class DatePickerInput extends React.Component {

  static defaultProps = {
    onShow: () => {},
    onHide: () => {},
    startMode: 'day',
    autoClose: true,
    closeOnClickOutside: true,
    floating: true,
    small: false,
    showInputButton: true,
    iconClassName: '',
    iconClearClassName: '',
    className: '',
    style: {}
  }

  constructor(props) {
    super(props);
    const _date = this.getValueLink().value || props.defaultValue;
    const date = typeof _date === 'string' ? this.parsePropDateString(_date) : moment(_date);
    this.state = {
      date: _date ? date : undefined,
      hasValue: !!_date,
      dateString: _date ? this.formatDisplayedDate(date) : '',
      showing: false
    };
  }

  componentDidMount() {
    if (this.props.closeOnClickOutside) {
      this.addOnClickListener();
    }
  }

  addOnClickListener = () => {
    if (window.attachEvent) {
      //Internet Explorer
      window.attachEvent('onclick', this.hideOnClickOutside);
    } else if (window.addEventListener) {
      window.addEventListener('click', this.hideOnClickOutside, false);
    }
  }

  removeOnClickListener = () => {
    if (window.detachEvent) {
      //Internet Explorer
      window.detachEvent('onclick', this.hideOnClickOutside);
    } else if (window.removeEventListener) {
      window.removeEventListener('click', this.hideOnClickOutside, false);
    }
  }

  getDatePickerInput = () => {
    return ReactDOM.findDOMNode(this.refs.datePickerInput);
  }

  isEventInsideDatePickerInput = (el) => {
    if (el === this.getDatePickerInput()) {
      return true;
    } else if (el.parentNode) {
      return this.isEventInsideDatePickerInput(el.parentNode);
    } else {
      return false;
    }
  }

  hideOnClickOutside = (e) => {
    if (!this.isEventInsideDatePickerInput(e.target) && this.state.showing) {
      this.hide();
    }
  }

  hide = () => {
    this.setState({ showing: false }, this.props.onHide);
  }

  show = () => {
    if (!this.state.showing) {
      this.setState({ showing: true }, this.props.onShow);
    }
  }

  toggleDatePicker = () => {
    const callback = this.state.showing ? this.props.onHide : this.props.onShow;
    this.setState({ showing: !this.state.showing }, callback);
  }

  hideOnEnterKey = (e) => {
    if (e.keyCode === ENTER_KEYCODE) {
      this.hide();
    }
  }

  onClear = () => {
    const _date = this.props.defaultValue;
    const date = typeof _date === 'string' ? this.parsePropDateString(_date) : moment(_date);
    this.setState(
      {
        date: _date ? date : undefined,
        dateString: _date ? this.formatDisplayedDate(date) : '',
        showing: false
      },
      this.props.onClear
    );
  }

  _onChangeDate = (jsDate) => {
    const newDate = moment(jsDate);
    const newDateString = this.formatDisplayedDate(newDate);
    if (this.props.autoClose) {
      this.hide();
    }
    this.getValueLink().requestChange(jsDate, this.formatReturnedDate(newDate));
    if (newDateString !== this.state.dateString) {
      this.setState({
        hasValue: true,
        date: newDate,
        dateString: newDateString
      });
    }
  }

  onChangeInput = ({ target: { value: dateString } }) => {
    if (dateString || this.state.date) {
      const parsedDate = this.parseInputDateString(dateString);
      const date = parsedDate.isValid() ? parsedDate : this.state.date;

      const jsDate = parsedDate.isValid() ? parsedDate.toDate() : INVALID;
      const returnedDateString = jsDate ? this.formatReturnedDate(parsedDate) : INVALID;

      this.setState({
        dateString,
        date,
        hasValue: parsedDate.isValid()
      }, () => this.getValueLink().requestChange(jsDate, returnedDateString));
    } else if (!dateString) {
      this.setState({ dateString });
    }
  }

  getLocals(props) {
    const {
      showInputButton,
      iconClassName,
      showOnInputClick,
      onClear,
      small,
      iconClearClassName,
      defaultValue,
      minDate, maxDate,
      locale,
      startMode,
      fixedMode,
      floating,
      closeOnClickOutside,
      className,
      style
    } = props;
    const { showing: active, hasValue, dateString: value, date } = this.state;

    const inputProps = omit(props, Object.keys(propTypes));
    const onInputClick = showOnInputClick ? this.show : undefined;
    const onButtonClick = showInputButton ? this.toggleDatePicker : undefined;
    const onInputClear = onClear ? this.onClear : undefined;

    return {
      style,
      className: cx('react-datepicker-component', className),
      inputProps: {
        value,
        small, active, hasValue,
        iconClassName, iconClearClassName,
        onInputClick, onButtonClick, onInputClear,
        onInputChange: this.onChangeInput,
        onInputKeyUp: this.hideOnEnterKey,
        ...inputProps
      },
      datePickerProps: active && {
        defaultValue,
        minDate,
        maxDate,
        locale,
        startMode,
        fixedMode,
        floating,
        closeOnClickOutside,
        value: date ? date.toDate() : undefined,
        onChange: this._onChangeDate
      }
    };
  }

  template({ className, style, inputProps, datePickerProps }) {
    return (
      <div {...{ style, className }} ref='datePickerInput'>
        <Input {...inputProps} />
        {datePickerProps && <DatePicker {...datePickerProps} />}
      </div>
    );
  }

  componentWillReceiveProps(nextProps) {
    const { value } = this.getValueLink(nextProps);
    if (value !== INVALID && value !== this.getValueLink().value) {
      if (value) {
        const date = typeof value === 'string' ?
          this.parsePropDateString(value, nextProps) : moment(value);
        this.setState({
          date,
          dateString: date.isValid() ?
            this.formatDisplayedDate(date, nextProps) : this.state.dateString
        });
      } else {
        this.setState({
          date: undefined,
          dateString: ''
        });
      }
    }
  }

  componentWillUnmount() {
    if (this.props.closeOnClickOutside) {
      this.removeOnClickListener();
    }
  }
}
<commit_msg>fix undefined variable<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';
import t from 'tcomb';
import { props } from 'tcomb-react';
import omit from 'lodash/omit';
import DatePicker from './DatePicker';
import { Value } from './utils/model';
import { format, valueLink, skinnable } from './utils';
import cx from 'classnames';
import Input from './Input';

const INVALID = 'Invalid date';
const ENTER_KEYCODE = 13;

export const Props = {
  value: t.maybe(Value),
  valueLink: t.maybe(t.interface({
    value: t.maybe(Value),
    requestChange: t.Function
  })),
  onChange: t.maybe(t.Function),
  onShow: t.maybe(t.Function),
  onHide: t.maybe(t.Function),
  onClear: t.maybe(t.Function),
  small: t.maybe(t.Boolean),
  defaultValue: t.maybe(Value),
  minDate: t.maybe(Value),
  maxDate: t.maybe(Value),
  locale: t.maybe(t.String),
  startMode: t.maybe(t.enums.of(['day', 'month', 'year'])),
  fixedMode: t.maybe(t.Boolean),
  displayFormat: t.maybe(t.String),
  returnFormat: t.maybe(t.String),
  format: t.maybe(t.String),
  validationFormat: t.maybe(t.String),
  showOnInputClick: t.maybe(t.Boolean),
  closeOnClickOutside: t.maybe(t.Boolean),
  showInputButton: t.maybe(t.Boolean),
  autoClose: t.maybe(t.Boolean),
  floating: t.maybe(t.Boolean),
  iconClassName: t.maybe(t.String),
  iconClearClassName: t.maybe(t.String),
  className: t.maybe(t.String), // used to omit from inputProps
  style: t.maybe(t.Object) // used to omit from inputProps
};

/** A decent and pretty date picker to be used with React
 * @param value - current date
 * @param valueLink - valueLink object to replace "value" and "onChange"
 * @param onChange - called when value changes
 * @param onShow - called when datepicker is opened
 * @param onHide - called when datepicker is closed
 * @param onClear - called when value is cleared
 * @param small - whether it's small or not
 * @param defaultValue - default date
 * @param minDate - minimum date selectable by the user
 * @param maxDate - maximum date selectable by the user
 * @param locale - locale used for translations
 * @param startMode - the start view of the datepicker
 * @param fixedMode - whether the user can use multiple views or not
 * @param displayFormat - MomentJS format used to display current date
 * @param returnFormat - MomentJS format used to format date before returing through "onChange"
 * @param format - MomentJS format used to format date before returing through "onChange"
 * @param validationFormat - MomentJS format used to format date before returing through "onChange"
 * @param showOnInputClick - whether the datepicker should open when user click on the input
 * @param closeOnClickOutside - whether the datepicker should close when user clicks outside of it
 * @param showInputButton - whether the input-button should be rendered
 * @param autoClose - pass true if you want the datepicker to close automatically after the user selects a value
 * @param floating - whether the datepicker should float over the page content (absolute position)
 * @param iconClassName - classname used for the icon
 * @param iconClearClassName - classname used for the clear icon
 */

@format
@valueLink
@skinnable()
@props(Props, { strict: false })
export default class DatePickerInput extends React.Component {

  static defaultProps = {
    onShow: () => {},
    onHide: () => {},
    startMode: 'day',
    autoClose: true,
    closeOnClickOutside: true,
    floating: true,
    small: false,
    showInputButton: true,
    iconClassName: '',
    iconClearClassName: '',
    className: '',
    style: {}
  }

  constructor(props) {
    super(props);
    const _date = this.getValueLink().value || props.defaultValue;
    const date = typeof _date === 'string' ? this.parsePropDateString(_date) : moment(_date);
    this.state = {
      date: _date ? date : undefined,
      hasValue: !!_date,
      dateString: _date ? this.formatDisplayedDate(date) : '',
      showing: false
    };
  }

  componentDidMount() {
    if (this.props.closeOnClickOutside) {
      this.addOnClickListener();
    }
  }

  addOnClickListener = () => {
    if (window.attachEvent) {
      //Internet Explorer
      window.attachEvent('onclick', this.hideOnClickOutside);
    } else if (window.addEventListener) {
      window.addEventListener('click', this.hideOnClickOutside, false);
    }
  }

  removeOnClickListener = () => {
    if (window.detachEvent) {
      //Internet Explorer
      window.detachEvent('onclick', this.hideOnClickOutside);
    } else if (window.removeEventListener) {
      window.removeEventListener('click', this.hideOnClickOutside, false);
    }
  }

  getDatePickerInput = () => {
    return ReactDOM.findDOMNode(this.refs.datePickerInput);
  }

  isEventInsideDatePickerInput = (el) => {
    if (el === this.getDatePickerInput()) {
      return true;
    } else if (el.parentNode) {
      return this.isEventInsideDatePickerInput(el.parentNode);
    } else {
      return false;
    }
  }

  hideOnClickOutside = (e) => {
    if (!this.isEventInsideDatePickerInput(e.target) && this.state.showing) {
      this.hide();
    }
  }

  hide = () => {
    this.setState({ showing: false }, this.props.onHide);
  }

  show = () => {
    if (!this.state.showing) {
      this.setState({ showing: true }, this.props.onShow);
    }
  }

  toggleDatePicker = () => {
    const callback = this.state.showing ? this.props.onHide : this.props.onShow;
    this.setState({ showing: !this.state.showing }, callback);
  }

  hideOnEnterKey = (e) => {
    if (e.keyCode === ENTER_KEYCODE) {
      this.hide();
    }
  }

  onClear = () => {
    const _date = this.props.defaultValue;
    const date = typeof _date === 'string' ? this.parsePropDateString(_date) : moment(_date);
    this.setState(
      {
        date: _date ? date : undefined,
        dateString: _date ? this.formatDisplayedDate(date) : '',
        showing: false
      },
      this.props.onClear
    );
  }

  _onChangeDate = (jsDate) => {
    const newDate = moment(jsDate);
    const newDateString = this.formatDisplayedDate(newDate);
    if (this.props.autoClose) {
      this.hide();
    }
    this.getValueLink().requestChange(jsDate, this.formatReturnedDate(newDate));
    if (newDateString !== this.state.dateString) {
      this.setState({
        hasValue: true,
        date: newDate,
        dateString: newDateString
      });
    }
  }

  onChangeInput = ({ target: { value: dateString } }) => {
    if (dateString || this.state.date) {
      const parsedDate = this.parseInputDateString(dateString);
      const date = parsedDate.isValid() ? parsedDate : this.state.date;

      const jsDate = parsedDate.isValid() ? parsedDate.toDate() : INVALID;
      const returnedDateString = jsDate ? this.formatReturnedDate(parsedDate) : INVALID;

      this.setState({
        dateString,
        date,
        hasValue: parsedDate.isValid()
      }, () => this.getValueLink().requestChange(jsDate, returnedDateString));
    } else if (!dateString) {
      this.setState({ dateString });
    }
  }

  getLocals(props) {
    const {
      showInputButton,
      iconClassName,
      showOnInputClick,
      onClear,
      small,
      iconClearClassName,
      defaultValue,
      minDate, maxDate,
      locale,
      startMode,
      fixedMode,
      floating,
      closeOnClickOutside,
      className,
      style
    } = props;
    const { showing: active, hasValue, dateString: value, date } = this.state;

    const inputProps = omit(props, Object.keys(Props));
    const onInputClick = showOnInputClick ? this.show : undefined;
    const onButtonClick = showInputButton ? this.toggleDatePicker : undefined;
    const onInputClear = onClear ? this.onClear : undefined;

    return {
      style,
      className: cx('react-datepicker-component', className),
      inputProps: {
        value,
        small, active, hasValue,
        iconClassName, iconClearClassName,
        onInputClick, onButtonClick, onInputClear,
        onInputChange: this.onChangeInput,
        onInputKeyUp: this.hideOnEnterKey,
        ...inputProps
      },
      datePickerProps: active && {
        defaultValue,
        minDate,
        maxDate,
        locale,
        startMode,
        fixedMode,
        floating,
        closeOnClickOutside,
        value: date ? date.toDate() : undefined,
        onChange: this._onChangeDate
      }
    };
  }

  template({ className, style, inputProps, datePickerProps }) {
    return (
      <div {...{ style, className }} ref='datePickerInput'>
        <Input {...inputProps} />
        {datePickerProps && <DatePicker {...datePickerProps} />}
      </div>
    );
  }

  componentWillReceiveProps(nextProps) {
    const { value } = this.getValueLink(nextProps);
    if (value !== INVALID && value !== this.getValueLink().value) {
      if (value) {
        const date = typeof value === 'string' ?
          this.parsePropDateString(value, nextProps) : moment(value);
        this.setState({
          date,
          dateString: date.isValid() ?
            this.formatDisplayedDate(date, nextProps) : this.state.dateString
        });
      } else {
        this.setState({
          date: undefined,
          dateString: ''
        });
      }
    }
  }

  componentWillUnmount() {
    if (this.props.closeOnClickOutside) {
      this.removeOnClickListener();
    }
  }
}
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Skywriter.
 *
 * The Initial Developer of the Original Code is
 * Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Joe Walker (jwalker@mozilla.com) (original author)
 *      Julian Viereck (julian.viereck@gmail.com)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
var cliView = exports;

var console = require('gcli/util').console;
var event = require('gcli/util').event;
var dom = require('gcli/util').dom;

var Status = require('gcli/types').Status;
var Templater = require('gcli/ui/domtemplate').Templater;
var History = require('gcli/ui/history').History;

var inputterCss = require('text!gcli/ui/inputter.css');

/**
 * We only want to import inputterCss once so this tracks whether or not we have
 * done it. Note technically it's only once per document, so perhaps we should
 * have a list of documents into which we've imported the CSS?
 */
var inputterCssImported = false;

/**
 * A wrapper to take care of the functions concerning an input element
 */
function Inputter(options) {
    if (!inputterCssImported && !options.preStyled) {
        dom.importCssString(inputterCss, this.doc);
        inputterCssImported = true;
    }

    this.requ = options.requisition;

    // Suss out where the input element is
    this.element = options.inputElement || 'gcliInput';
    if (typeof this.element === 'string') {
        this.doc = options.document || document;
        var name = this.element;
        this.element = this.doc.getElementById(name);
        if (!this.element) {
            throw new Error('No element with id=' + name + '.');
        }
    }
    else {
        // Assume we've been passed in the correct node
        this.doc = this.element.ownerDocument;
    }

    this.element.spellcheck = false;

    // Used to distinguish focus from TAB in CLI. See onKeyUp()
    this.lastTabDownAt = 0;

    // Ensure that TAB/UP/DOWN isn't handled by the browser
    event.addCommandKeyListener(this.element, this.onCommandKey.bind(this));
    event.addListener(this.element, 'keyup', this.onKeyUp.bind(this));

    // Use our document if no other is supplied
    options.document = options.document || this.doc;

    if (options.completer == null) {
        options.completer = new Completer(options);
    }
    else if (typeof options.completer === 'function') {
        options.completer = new options.completer(options);
    }
    this.completer = options.completer;
    this.completer.decorate(this);

    // Use the provided history object, or instantiate our own.
    this.history = options.history = options.history || new History(options);
    this._scrollingThroughHistory = false;

    // cursor position affects hint severity.
    event.addListener(this.element, 'mouseup', function(ev) {
        this.completer.update();
    }.bind(this));

    this.requ.inputChange.add(this.onInputChange, this);
}

Inputter.prototype.onInputChange = function() {
    this.element.value = this.requ.toString();
    this.completer.update();
};

/**
 * When the input element gets/loses focus make sure we tell the popup so it
 * can show/hide accordingly.
 */
Inputter.prototype.sendFocusEventsToPopup = function(popup) {
    event.addListener(this.element, 'focus', popup.showOutput);
    event.addListener(this.element, 'blur', popup.hideOutput);
};

/**
 * Focus the input element
 */
Inputter.prototype.focus = function() {
    this.element.focus();
};

/**
 * A version of getBoundingClientRect that also tells us the width and height
 * of the input element.
 */
Inputter.prototype.getDimensionRect = function() {
    var rect = this.element.getBoundingClientRect();
    rect.width = rect.right - rect.left;
    rect.height = rect.bottom - rect.top;
    return rect;
};

/**
 * Utility to add an element into the DOM after the input element.
 */
Inputter.prototype.appendAfter = function(element) {
    this.element.parentNode.insertBefore(element, this.element.nextSibling);
};

/**
 * Ensure certain keys (arrows, tab, etc) that we would like to handle
 * are not handled by the browser
 */
Inputter.prototype.onCommandKey = function(ev, hashId, keyCode) {
    if (keyCode === 38 /*UP*/ || keyCode === 40 /*DOWN*/) {
        event.stopEvent(ev);
    }
    if (keyCode === 9 /*TAB*/) {
        this.lastTabDownAt = 0;
        if (!ev.shiftKey) {
            event.stopEvent(ev);
            // Record the timestamp of this TAB down so onKeyUp can distinguish
            // focus from TAB in the CLI.
            this.lastTabDownAt = ev.timeStamp;
        }
        if (ev.metaKey || ev.altKey || ev.crtlKey) {
            if (this.doc.commandDispatcher) {
                this.doc.commandDispatcher.advanceFocus();
            }
            else {
                this.element.blur();
            }
        }
    }
};

/**
 * Just set the input field to a value without executing anything
 */
Inputter.prototype.setInput = function(str) {
    this.element.value = str;
    this.update();
};

/**
 * The main keyboard processing loop
 */
Inputter.prototype.onKeyUp = function(ev) {
    // RETURN does a special exec/highlight thing
    if (ev.keyCode === 13 /*RETURN*/) {
        var worst = this.requ.getStatus();
        // Deny RETURN unless the command might work
        if (worst === Status.VALID) {
            this.requ.exec();
            this._scrollingThroughHistory = false;
            this.history.add(this.element.value);
            this.element.value = '';
        }
        // See bug 664135 - On pressing return with an invalid input, GCLI
        // should select the incorrect input for an easy fix

        this.update();
    }
    else if (ev.keyCode === 9 /*TAB*/ && !ev.shiftKey) {
        // If the TAB keypress took the cursor from another field to this one,
        // then they get the keydown/keypress, and we get the keyup. In this
        // case we don't want to do any completion.
        // If the time of the keydown/keypress of TAB was close (i.e. within
        // 1 second) to the time of the keyup then we assume that we got them
        // both, and do the completion.
        if (this.lastTabDownAt + 1000 > ev.timeStamp) {
            this.getCurrentAssignment().complete();
        }
        this.lastTabDownAt = 0;
        this._scrollingThroughHistory = false;
    }
    else if (ev.keyCode === 38 /*UP*/) {
        if (this.element.value === '' || this._scrollingThroughHistory) {
            this._scrollingThroughHistory = true;
            this.element.value = this.history.backward();
            this.update();
            dom.setSelectionStart(this.element, 0);
            dom.setSelectionEnd(this.element, this.element.value.length);
        } else {
            this.getCurrentAssignment().increment();
        }
    }
    else if (ev.keyCode === 40 /*DOWN*/) {
        if (this.element.value === '' || this._scrollingThroughHistory) {
            this._scrollingThroughHistory = true;
            this.element.value = this.history.forward();
            this.update();
            dom.setSelectionStart(this.element, 0);
            dom.setSelectionEnd(this.element, this.element.value.length);
        } else {
            this.getCurrentAssignment().decrement();
        }
    }
    else {
        this._scrollingThroughHistory = false;
        this.update();
    }
};

/**
 * Accessor for the assignment at the cursor.
 * i.e Requisition.getAssignmentAt(cursorPos);
 */
Inputter.prototype.getCurrentAssignment = function() {
    var start = dom.getSelectionStart(this.element);
    return this.requ.getAssignmentAt(start);
};

/**
 * Actually parse the input and make sure we're all up to date
 */
Inputter.prototype.update = function() {
    this.updateCli();
    this.completer.update();
};

/**
 * Update the requisition with the contents of the input element
 */
Inputter.prototype.updateCli = function() {
    var input = {
        typed: this.element.value,
        cursor: {
            start: dom.getSelectionStart(this.element),
            end: dom.getSelectionEnd(this.element.selectionEnd)
        }
    };

    this.requ.update(input);
};

cliView.Inputter = Inputter;

/**
 * Completer is an 'input-like' element that sits  an input element annotating
 * it with visual goodness.
 * @param {object} options An object that contains various options which
 * customizes how the completer functions.
 * Properties on the options object:
 * - document (required) DOM document to be used in creating elements
 * - requisition (required) A GCLI Requisition object whose state is monitored
 * - completeElement (optional) An element to use
 */
function Completer(options) {
    this.doc = options.document;
    this.requ = options.requisition;
    this.elementCreated = false;

    this.element = options.completeElement || 'gcliComplete';
    if (typeof this.element === 'string') {
        var name = this.element;
        this.element = this.doc.getElementById(name);

        if (!this.element) {
            this.elementCreated = true;
            this.element = dom.createElement('div', null, this.doc);
            this.element.className = 'gcliCompletion gcliVALID';
            this.element.setAttribute('tabindex', '-1');
            this.element.setAttribute('aria-live', 'polite');
        }
    }

    if (options.inputBackgroundElement) {
        this.backgroundElement = options.inputBackgroundElement;
    }
    else {
        this.backgroundElement = this.element;
    }
}

/**
 * A list of the styles that decorate() should copy to make the completion
 * element look like the input element. backgroundColor is a spiritual part of
 * this list, but see comment in decorate().
 */
Completer.copyStyles = [
    'color', 'fontSize', 'fontFamily', 'fontWeight', 'fontStyle'
];

/**
 * Make ourselves visually similar to the input element, and make the input
 * element transparent so our background shines through
 */
Completer.prototype.decorate = function(inputter) {
    this.inputter = inputter;
    this.input = inputter.element;

    // If we were told which element to use, then assume it is already
    // correctly positioned. Otherwise insert it alongside the input element
    if (this.elementCreated) {
        this.inputter.appendAfter(this.element);

        Completer.copyStyles.forEach(function(style) {
            this.element.style[style] = dom.computedStyle(this.input, style);
        }, this);

        // If there is a separate backgroundElement, then we make the element
        // transparent, otherwise it inherits the color of the input node
        // It's not clear why backgroundColor doesn't work when used from
        // computedStyle, but it doesn't. Patches welcome!
        this.element.style.backgroundColor = (this.backgroundElement != this.element) ?
              'transparent' :
              this.input.style.backgroundColor;
        this.input.style.backgroundColor = 'transparent';

        // Make room for the prompt
        this.input.style.paddingLeft = '16px';

        var resizer = this.resizer.bind(this);
        event.addListener(this.doc.defaultView, 'resize', resizer);
        resizer();
    }
};

/**
 * Ensure that the completion element is the same size and the inputter element
 */
Completer.prototype.resizer = function() {
    var rect = this.inputter.getDimensionRect();
    if (!rect) {
        console.log('Skipping resize, missing getClientRects');
        return;
    }

    this.element.style.top = rect.top + 'px';
    this.element.style.height = rect.height + 'px';
    this.element.style.lineHeight = rect.height + 'px';
    this.element.style.left = rect.left + 'px';
    this.element.style.width = rect.width + 'px';
};

/**
 * Bring the completion element up to date with what the requisition says
 */
Completer.prototype.update = function() {
    var start = dom.getSelectionStart(this.input);
    var current = this.requ.getAssignmentAt(start);
    var predictions = current.getPredictions();

    // Update the completer element with prompt/error marker/TAB info
    dom.removeCssClass(this.backgroundElement, 'gcli' + Status.VALID.toString());
    dom.removeCssClass(this.backgroundElement, 'gcli' + Status.INCOMPLETE.toString());
    dom.removeCssClass(this.backgroundElement, 'gcli' + Status.ERROR.toString());

    var completion = '> ';
    if (this.input.value.length > 0) {
        var scores = this.requ.getInputStatusMarkup();
        completion += this.markupStatusScore(scores);
    }

    // Display the '-> prediction' at the end of the completer element
    if (this.input.value.length > 0 && predictions.length > 0) {
        var tab = predictions[0];
        tab = tab.name ? tab.name : tab;
        completion += '  ⇥ ' +
                tab + '';
    }
    dom.setInnerHtml(this.element, '' + completion + '');
    var status = this.requ.getStatus();

    dom.addCssClass(this.backgroundElement, 'gcli' + status.toString());
};

/**
 * Mark-up an array of Status values with spans
 */
Completer.prototype.markupStatusScore = function(scores) {
    var completion = '';
    // Create mark-up
    var i = 0;
    var lastStatus = -1;
    while (true) {
        if (lastStatus !== scores[i]) {
            completion += '';
            lastStatus = scores[i];
        }
        completion += this.input.value[i];
        i++;
        if (i === this.input.value.length) {
            completion += '';
            break;
        }
        if (lastStatus !== scores[i]) {
            completion += '';
        }
    }

    return completion;
};

cliView.Completer = Completer;

});
<commit_msg>Matching existing style<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Skywriter.
 *
 * The Initial Developer of the Original Code is
 * Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Joe Walker (jwalker@mozilla.com) (original author)
 *      Julian Viereck (julian.viereck@gmail.com)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
var cliView = exports;

var console = require('gcli/util').console;
var event = require('gcli/util').event;
var dom = require('gcli/util').dom;

var Status = require('gcli/types').Status;
var Templater = require('gcli/ui/domtemplate').Templater;
var History = require('gcli/ui/history').History;

var inputterCss = require('text!gcli/ui/inputter.css');

/**
 * We only want to import inputterCss once so this tracks whether or not we have
 * done it. Note technically it's only once per document, so perhaps we should
 * have a list of documents into which we've imported the CSS?
 */
var inputterCssImported = false;

/**
 * A wrapper to take care of the functions concerning an input element
 */
function Inputter(options) {
    if (!inputterCssImported && !options.preStyled) {
        dom.importCssString(inputterCss, this.doc);
        inputterCssImported = true;
    }

    this.requ = options.requisition;

    // Suss out where the input element is
    this.element = options.inputElement || 'gcliInput';
    if (typeof this.element === 'string') {
        this.doc = options.document || document;
        var name = this.element;
        this.element = this.doc.getElementById(name);
        if (!this.element) {
            throw new Error('No element with id=' + name + '.');
        }
    }
    else {
        // Assume we've been passed in the correct node
        this.doc = this.element.ownerDocument;
    }

    this.element.spellcheck = false;

    // Used to distinguish focus from TAB in CLI. See onKeyUp()
    this.lastTabDownAt = 0;

    // Ensure that TAB/UP/DOWN isn't handled by the browser
    event.addCommandKeyListener(this.element, this.onCommandKey.bind(this));
    event.addListener(this.element, 'keyup', this.onKeyUp.bind(this));

    // Use our document if no other is supplied
    options.document = options.document || this.doc;

    if (options.completer == null) {
        options.completer = new Completer(options);
    }
    else if (typeof options.completer === 'function') {
        options.completer = new options.completer(options);
    }
    this.completer = options.completer;
    this.completer.decorate(this);

    // Use the provided history object, or instantiate our own.
    this.history = options.history = options.history || new History(options);
    this._scrollingThroughHistory = false;

    // cursor position affects hint severity.
    event.addListener(this.element, 'mouseup', function(ev) {
        this.completer.update();
    }.bind(this));

    this.requ.inputChange.add(this.onInputChange, this);
}

Inputter.prototype.onInputChange = function() {
    this.element.value = this.requ.toString();
    this.completer.update();
};

/**
 * When the input element gets/loses focus make sure we tell the popup so it
 * can show/hide accordingly.
 */
Inputter.prototype.sendFocusEventsToPopup = function(popup) {
    event.addListener(this.element, 'focus', popup.showOutput);
    event.addListener(this.element, 'blur', popup.hideOutput);
};

/**
 * Focus the input element
 */
Inputter.prototype.focus = function() {
    this.element.focus();
};

/**
 * A version of getBoundingClientRect that also tells us the width and height
 * of the input element.
 */
Inputter.prototype.getDimensionRect = function() {
    var rect = this.element.getBoundingClientRect();
    rect.width = rect.right - rect.left;
    rect.height = rect.bottom - rect.top;
    return rect;
};

/**
 * Utility to add an element into the DOM after the input element.
 */
Inputter.prototype.appendAfter = function(element) {
    this.element.parentNode.insertBefore(element, this.element.nextSibling);
};

/**
 * Ensure certain keys (arrows, tab, etc) that we would like to handle
 * are not handled by the browser
 */
Inputter.prototype.onCommandKey = function(ev, hashId, keyCode) {
    if (keyCode === 38 /*UP*/ || keyCode === 40 /*DOWN*/) {
        event.stopEvent(ev);
    }
    if (keyCode === 9 /*TAB*/) {
        this.lastTabDownAt = 0;
        if (!ev.shiftKey) {
            event.stopEvent(ev);
            // Record the timestamp of this TAB down so onKeyUp can distinguish
            // focus from TAB in the CLI.
            this.lastTabDownAt = ev.timeStamp;
        }
        if (ev.metaKey || ev.altKey || ev.crtlKey) {
            if (this.doc.commandDispatcher) {
                this.doc.commandDispatcher.advanceFocus();
            }
            else {
                this.element.blur();
            }
        }
    }
};

/**
 * Just set the input field to a value without executing anything
 */
Inputter.prototype.setInput = function(str) {
    this.element.value = str;
    this.update();
};

/**
 * The main keyboard processing loop
 */
Inputter.prototype.onKeyUp = function(ev) {
    // RETURN does a special exec/highlight thing
    if (ev.keyCode === 13 /*RETURN*/) {
        var worst = this.requ.getStatus();
        // Deny RETURN unless the command might work
        if (worst === Status.VALID) {
            this.requ.exec();
            this._scrollingThroughHistory = false;
            this.history.add(this.element.value);
            this.element.value = '';
        }
        // See bug 664135 - On pressing return with an invalid input, GCLI
        // should select the incorrect input for an easy fix

        this.update();
    }
    else if (ev.keyCode === 9 /*TAB*/ && !ev.shiftKey) {
        // If the TAB keypress took the cursor from another field to this one,
        // then they get the keydown/keypress, and we get the keyup. In this
        // case we don't want to do any completion.
        // If the time of the keydown/keypress of TAB was close (i.e. within
        // 1 second) to the time of the keyup then we assume that we got them
        // both, and do the completion.
        if (this.lastTabDownAt + 1000 > ev.timeStamp) {
            this.getCurrentAssignment().complete();
        }
        this.lastTabDownAt = 0;
        this._scrollingThroughHistory = false;
    }
    else if (ev.keyCode === 38 /*UP*/) {
        if (this.element.value === '' || this._scrollingThroughHistory) {
            this._scrollingThroughHistory = true;
            this.element.value = this.history.backward();
            this.update();
            dom.setSelectionStart(this.element, 0);
            dom.setSelectionEnd(this.element, this.element.value.length);
        }
        else {
            this.getCurrentAssignment().increment();
        }
    }
    else if (ev.keyCode === 40 /*DOWN*/) {
        if (this.element.value === '' || this._scrollingThroughHistory) {
            this._scrollingThroughHistory = true;
            this.element.value = this.history.forward();
            this.update();
            dom.setSelectionStart(this.element, 0);
            dom.setSelectionEnd(this.element, this.element.value.length);
        }
        else {
            this.getCurrentAssignment().decrement();
        }
    }
    else {
        this._scrollingThroughHistory = false;
        this.update();
    }
};

/**
 * Accessor for the assignment at the cursor.
 * i.e Requisition.getAssignmentAt(cursorPos);
 */
Inputter.prototype.getCurrentAssignment = function() {
    var start = dom.getSelectionStart(this.element);
    return this.requ.getAssignmentAt(start);
};

/**
 * Actually parse the input and make sure we're all up to date
 */
Inputter.prototype.update = function() {
    this.updateCli();
    this.completer.update();
};

/**
 * Update the requisition with the contents of the input element
 */
Inputter.prototype.updateCli = function() {
    var input = {
        typed: this.element.value,
        cursor: {
            start: dom.getSelectionStart(this.element),
            end: dom.getSelectionEnd(this.element.selectionEnd)
        }
    };

    this.requ.update(input);
};

cliView.Inputter = Inputter;

/**
 * Completer is an 'input-like' element that sits  an input element annotating
 * it with visual goodness.
 * @param {object} options An object that contains various options which
 * customizes how the completer functions.
 * Properties on the options object:
 * - document (required) DOM document to be used in creating elements
 * - requisition (required) A GCLI Requisition object whose state is monitored
 * - completeElement (optional) An element to use
 */
function Completer(options) {
    this.doc = options.document;
    this.requ = options.requisition;
    this.elementCreated = false;

    this.element = options.completeElement || 'gcliComplete';
    if (typeof this.element === 'string') {
        var name = this.element;
        this.element = this.doc.getElementById(name);

        if (!this.element) {
            this.elementCreated = true;
            this.element = dom.createElement('div', null, this.doc);
            this.element.className = 'gcliCompletion gcliVALID';
            this.element.setAttribute('tabindex', '-1');
            this.element.setAttribute('aria-live', 'polite');
        }
    }

    if (options.inputBackgroundElement) {
        this.backgroundElement = options.inputBackgroundElement;
    }
    else {
        this.backgroundElement = this.element;
    }
}

/**
 * A list of the styles that decorate() should copy to make the completion
 * element look like the input element. backgroundColor is a spiritual part of
 * this list, but see comment in decorate().
 */
Completer.copyStyles = [
    'color', 'fontSize', 'fontFamily', 'fontWeight', 'fontStyle'
];

/**
 * Make ourselves visually similar to the input element, and make the input
 * element transparent so our background shines through
 */
Completer.prototype.decorate = function(inputter) {
    this.inputter = inputter;
    this.input = inputter.element;

    // If we were told which element to use, then assume it is already
    // correctly positioned. Otherwise insert it alongside the input element
    if (this.elementCreated) {
        this.inputter.appendAfter(this.element);

        Completer.copyStyles.forEach(function(style) {
            this.element.style[style] = dom.computedStyle(this.input, style);
        }, this);

        // If there is a separate backgroundElement, then we make the element
        // transparent, otherwise it inherits the color of the input node
        // It's not clear why backgroundColor doesn't work when used from
        // computedStyle, but it doesn't. Patches welcome!
        this.element.style.backgroundColor = (this.backgroundElement != this.element) ?
              'transparent' :
              this.input.style.backgroundColor;
        this.input.style.backgroundColor = 'transparent';

        // Make room for the prompt
        this.input.style.paddingLeft = '16px';

        var resizer = this.resizer.bind(this);
        event.addListener(this.doc.defaultView, 'resize', resizer);
        resizer();
    }
};

/**
 * Ensure that the completion element is the same size and the inputter element
 */
Completer.prototype.resizer = function() {
    var rect = this.inputter.getDimensionRect();
    if (!rect) {
        console.log('Skipping resize, missing getClientRects');
        return;
    }

    this.element.style.top = rect.top + 'px';
    this.element.style.height = rect.height + 'px';
    this.element.style.lineHeight = rect.height + 'px';
    this.element.style.left = rect.left + 'px';
    this.element.style.width = rect.width + 'px';
};

/**
 * Bring the completion element up to date with what the requisition says
 */
Completer.prototype.update = function() {
    var start = dom.getSelectionStart(this.input);
    var current = this.requ.getAssignmentAt(start);
    var predictions = current.getPredictions();

    // Update the completer element with prompt/error marker/TAB info
    dom.removeCssClass(this.backgroundElement, 'gcli' + Status.VALID.toString());
    dom.removeCssClass(this.backgroundElement, 'gcli' + Status.INCOMPLETE.toString());
    dom.removeCssClass(this.backgroundElement, 'gcli' + Status.ERROR.toString());

    var completion = '> ';
    if (this.input.value.length > 0) {
        var scores = this.requ.getInputStatusMarkup();
        completion += this.markupStatusScore(scores);
    }

    // Display the '-> prediction' at the end of the completer element
    if (this.input.value.length > 0 && predictions.length > 0) {
        var tab = predictions[0];
        tab = tab.name ? tab.name : tab;
        completion += '  ⇥ ' +
                tab + '';
    }
    dom.setInnerHtml(this.element, '' + completion + '');
    var status = this.requ.getStatus();

    dom.addCssClass(this.backgroundElement, 'gcli' + status.toString());
};

/**
 * Mark-up an array of Status values with spans
 */
Completer.prototype.markupStatusScore = function(scores) {
    var completion = '';
    // Create mark-up
    var i = 0;
    var lastStatus = -1;
    while (true) {
        if (lastStatus !== scores[i]) {
            completion += '';
            lastStatus = scores[i];
        }
        completion += this.input.value[i];
        i++;
        if (i === this.input.value.length) {
            completion += '';
            break;
        }
        if (lastStatus !== scores[i]) {
            completion += '';
        }
    }

    return completion;
};

cliView.Completer = Completer;

});
<|endoftext|>


<commit_before>(function ( $ ) {
	$( '#contact-form' ).submit(function () {
		$.post( 'http://danieldesira.site88.net/index.php', {
			name: $( '#name' ).val(),
			email: $( '#email' ).val(),
			subject: $( '#subject' ).val(),
			message: $( '#message' ).val(),
			hidden: $( '#hidden' ).val()
		}, function ( data ) {
			if ( data.charAt( 0 ) === '1' ) {
				$( '#success' ).modal( 'show' );
			} else {
				$( '#failure' ).modal( 'show' );
			}
		});
		return false;
	});
})( jQuery );<commit_msg>clear form on successful outcome<commit_after>(function ( $ ) {
	$( '#contact-form' ).submit(function () {
		$.post( 'http://danieldesira.site88.net/index.php', {
			name: $( '#name' ).val(),
			email: $( '#email' ).val(),
			subject: $( '#subject' ).val(),
			message: $( '#message' ).val(),
			hidden: $( '#hidden' ).val()
		}, function ( data ) {
			if ( data.charAt( 0 ) === '1' ) {
				$( '#success' ).modal( 'show' );

				// Clear form.
				$( '#name, #email, #subject, #message' ).val( '' );
			} else {
				$( '#failure' ).modal( 'show' );
			}
		});
		return false;
	});
})( jQuery );
<|endoftext|>


<commit_before>module.exports = {
  projects: [
    // { name:     'shout',           repoOwner: 'saitodisse', branch: 'azkfile' },
    // { name:     'cloudtunes',      repoOwner: 'saitodisse', branch: 'azkfile' },
    // { name:     'dashboard',       repoOwner: 'saitodisse', branch: 'azkfile' },
    // { name:     'dillinger',       repoOwner: 'saitodisse', branch: 'azkfile' },
    // { name:     'discourse',       repoOwner: 'saitodisse', branch: 'azkfile' },
    // { name:     'habitrpg',        repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'huginn',          repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'stringer',        repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'lets-chat',       repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'regexr',          repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'isomorphic500',   repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'paperwork',       repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'platform',        repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'diaspora',        repoOwner: 'fearenales', branch: 'azkfile' },
    { name:     'jekyll',          repoOwner: 'fearenales', branch: 'master' },
    { name:     'azkdemo',         repoOwner: 'azukiapp',   branch: 'final' },
    { name:     'selfstarter',     repoOwner: 'azukiapp',   branch: 'master' },
    { name:     'task-cerebral',   repoOwner: 'saitodisse', branch: 'master' },
    { name:     'feedbin',         repoOwner: 'azukiapp',   branch: 'azkfile' },
  ]
}
<commit_msg>faster on top<commit_after>module.exports = {
  projects: [
    { name:     'azkdemo',         repoOwner: 'azukiapp',   branch: 'final' },
    { name:     'task-cerebral',   repoOwner: 'saitodisse', branch: 'master' },
    { name:     'isomorphic500',   repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'platform',        repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'cloudtunes',      repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'dashboard',       repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'dillinger',       repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'shout',           repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'huginn',          repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'lets-chat',       repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'stringer',        repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'habitrpg',        repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'regexr',          repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'paperwork',       repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'discourse',       repoOwner: 'saitodisse', branch: 'azkfile' },
    { name:     'selfstarter',     repoOwner: 'azukiapp',   branch: 'master' },
    { name:     'jekyll',          repoOwner: 'fearenales', branch: 'master' },
    { name:     'feedbin',         repoOwner: 'azukiapp',   branch: 'azkfile' },
    { name:     'diaspora',        repoOwner: 'fearenales', branch: 'azkfile' },
  ]
}
<|endoftext|>