<commit_before>var xmlrpc = require("xmlrpc");
var async = require("async");

var USER_AGENT = "OpenSRTJS";

var client = xmlrpc.createClient({ host: 'api.opensubtitles.org', port: 80, path: '/xml-rpc'})

var token = "";

exports.getToken = function getToken(cb) {
	client.methodCall('LogIn', ['', '', 'en', USER_AGENT], function (err, res) {
		if(err) return cb(err, null);
		token = res.token;
		cb(null, res.token);
  })
},

exports.searchEpisode = function(data, cb) {
	if(!data.token) {
		exports.getToken(function(err, token) {
			if(err) {
				return cb(err, null);
			}
			data.token = token;
			return searchEpisode(data, cb);
		});
	}

	else {
		return searchEpisode(data, cb);
	}
}

function searchEpisode(data, cb) {
	client.methodCall('SearchSubtitles', [
			data.token,
			[
				{
					sublanaguageid: "all",
					imdbid: data.imdbid.replace("tt", ""),
					season: data.season,
					episode: data.episode,
					tag: data.filename
				}
			]
		],
		function(err, res){
			if(err) return cb(err, null);
			var subs = {};
			async.eachSeries(res.data, function(sub, callback) {
				var tmp = {};
				tmp.url = sub.SubDownloadLink.replace(".gz", ".srt");
				tmp.lang = sub.ISO639;
				tmp.downloads = sub.SubDownloadsCnt;
				tmp.byTag = (sub.MatchedBy == "tag");
				if(!subs[tmp.lang]) {
					subs[tmp.lang] = tmp;
				}
				else {
					if((tmp.byTag && !subs[tmp.lang].byTag) ||
					(tmp.downloads > subs[tmp.lang].downloads && tmp.byTag)) {
					// Get most download with tag match taking precedence
						subs[tmp.lang] = tmp;
					}
				}
				return callback();
			},
			function(err) {
				return cb(err, subs);
			})
		})
	}
<commit_msg>Updated logic<commit_after>var xmlrpc = require("xmlrpc");
var async = require("async");

var USER_AGENT = "OpenSRTJS";

var client = xmlrpc.createClient({ host: 'api.opensubtitles.org', port: 80, path: '/xml-rpc'})

var token = "";

exports.getToken = function getToken(cb) {
	client.methodCall('LogIn', ['', '', 'en', USER_AGENT], function (err, res) {
		if(err) return cb(err, null);
		token = res.token;
		cb(null, res.token);
  })
},

exports.searchEpisode = function(data, cb) {
	if(!data.token) {
		exports.getToken(function(err, token) {
			if(err) {
				return cb(err, null);
			}
			data.token = token;
			return searchEpisode(data, cb);
		});
	}

	else {
		return searchEpisode(data, cb);
	}
}

function searchEpisode(data, cb) {
	client.methodCall('SearchSubtitles', [
			data.token,
			[
				{
					sublanaguageid: "all",
					imdbid: data.imdbid.replace("tt", ""),
					season: data.season,
					episode: data.episode,
					tag: data.filename
				}
			]
		],
		function(err, res){
			if(err) return cb(err, null);
			var subs = {};
			async.eachSeries(res.data, function(sub, callback) {
				var tmp = {};
				tmp.url = sub.SubDownloadLink.replace(".gz", ".srt");
				tmp.lang = sub.ISO639;
				tmp.downloads = sub.SubDownloadsCnt;
				tmp.byTag = (sub.MatchedBy == "tag");
				if(!subs[tmp.lang]) {
					subs[tmp.lang] = tmp;
				}
				else {
					if((tmp.byTag && !subs[tmp.lang].byTag) ||
					(tmp.downloads > subs[tmp.lang].downloads && (!tmp.byTag && !subs[tmp.lang].byTag)) {
					// Get most download with tag match taking precedence
						subs[tmp.lang] = tmp;
					}
				}
				return callback();
			},
			function(err) {
				return cb(err, subs);
			})
		})
	}
<|endoftext|>


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

  function saveOptions () {
    var weapons = document.getElementById('items').value;
    var rate = document.getElementById('rate').value;

    chrome.storage.sync.set({
      weapons: weapons,
      rate: rate
    }, function() {
      var status = document.getElementById('status');
      status.textContent = 'Options saved.';
      setTimeout(function() {
        status.textContent = '';
      }, 750);
    });
  }

  function restoreOptions () {
    chrome.storage.sync.get({
      weapons: 'knife,karambit,bayonet,awp,m4a4,m4a1,ak-47,glock-18',
      rate: 200
    }, function(data) {
      document.getElementById('items').value = data.weapons;
      document.getElementById('rate').value = data.rate;
    });
  }

  document.addEventListener('DOMContentLoaded', restoreOptions);
  document.getElementById('save').addEventListener('click', saveOptions);

})();
<commit_msg>cleanup<commit_after>(function () {
  'use strict';

  function saveOptions () {
    var weapons = document.getElementById('items').value;
    var rate = document.getElementById('rate').value;

    chrome.storage.sync.set({
      weapons: weapons,
      rate: rate
    }, function () {
      var status = document.getElementById('status');
      status.textContent = 'Options saved.';
      setTimeout(function () {
        status.textContent = '';
      }, 750);
    });
  }

  function restoreOptions () {
    chrome.storage.sync.get({
      weapons: 'knife,karambit,bayonet,awp,m4a4,m4a1,ak-47,glock-18',
      rate: 200
    }, function (data) {
      document.getElementById('items').value = data.weapons;
      document.getElementById('rate').value = data.rate;
    });
  }

  document.addEventListener('DOMContentLoaded', restoreOptions);
  document.getElementById('save').addEventListener('click', saveOptions);

})();
<|endoftext|>


<commit_before>console.log('options.js');
document.addEventListener('DOMContentLoaded', function () {
  init();
});

function openAuthUrl() {
  console.log('openAuthUrl');
  openAndCloseTab(buildAuthUrl());
}

function endAuth() {
  localStorage.clear();
  openAndCloseTab('/options.html');
}

function buildAuthUrl() {
  return config.authorizeUrl + '?client_id=' + config.clientId + '&response_type=token&redirect_uri=' + location.href + '&scope=' + config.apiScope;
}

function init() {
  $('#content').on('click', '.end-auth', endAuth);
  $('#content').on('click', '.start-auth', openAuthUrl);

  if (isCallback()) {
    $('#account').html('

');
    window.accessToken = saveAccessToken(parseAccessToken());
    openAndCloseTab('/options.html');
    return;
  }

  if (localStorage.getItem('accessToken')) {
    console.log('accessToken');
    $('#account').html('

');
    window.accessToken = localStorage.getItem('accessToken');
    window.account = new Account();
    window.account.set({ accessToken: window.accessToken });
    window.account.fetch({ success: accountFetch });
    return;
  }
}

function accountFetch(account) {
  console.log('account')
  console.log(account)
  $('#account').html('
@' + account.get('username') + ' <button class="btn end-auth btn-danger">Sign out</button>
');
}

function saveAccessToken(accessToken) {
  localStorage.setItem('accessToken', accessToken);
  return accessToken;
}

function parseAccessToken() {
  var hash = location.hash;
  // TODO: refactor this hack
  return location.hash.split('#')[1].split('=')[1];
}

function isCallback() {
  return location.hash.indexOf('#access_token=') === 0;
}

function openAndCloseTab(url) {
  chrome.tabs.create({ url: url });
  window.close();
}<commit_msg>send message to background when account authenticated<commit_after>console.log('options.js');
document.addEventListener('DOMContentLoaded', function () {
  init();
});

function openAuthUrl() {
  openAndCloseTab(buildAuthUrl());
}

function endAuth() {
  localStorage.clear();
  openAndCloseTab('/options.html');
}

function buildAuthUrl() {
  return config.authorizeUrl + '?client_id=' + config.clientId + '&response_type=token&redirect_uri=' + location.href + '&scope=' + config.apiScope;
}

function init() {
  $('#content').on('click', '.end-auth', endAuth);
  $('#content').on('click', '.start-auth', openAuthUrl);

  if (isCallback()) {
    $('#account').html('

');
    window.accessToken = saveAccessToken(parseAccessToken());
    openAndCloseTab('/options.html');
    return;
  }

  if (localStorage.getItem('accessToken')) {
    $('#account').html('

');
    window.accessToken = localStorage.getItem('accessToken');
    window.account = new Account();
    window.account.set({ accessToken: window.accessToken });
    window.account.fetch({ success: accountFetch });
    return;
  }
}

function accountFetch(account) {
  chrome.extension.sendMessage({ method: 'put', action: 'oauth/authenticate'}, function(response) { });
  $('#account').html('
@' + account.get('username') + ' <button class="btn end-auth btn-danger">Sign out</button>
');
}

function saveAccessToken(accessToken) {
  localStorage.setItem('accessToken', accessToken);
  return accessToken;
}

function parseAccessToken() {
  var hash = location.hash;
  // TODO: refactor this hack
  return location.hash.split('#')[1].split('=')[1];
}

function isCallback() {
  return location.hash.indexOf('#access_token=') === 0;
}

function openAndCloseTab(url) {
  chrome.tabs.create({ url: url });
  window.close();
}<|endoftext|>


<commit_before>'use strict';

/**
 * The processor handling an entire result.
 */

var Q = require('q');

var processAsset = require('./asset');

var ASSETS_PER_REQUEST = 100;

var ADDITIONAL_FIELDS = [
  '{af4b2e71-5f6a-11d2-8f20-0000c0e166dc}', // Related Sub Assets
  '{af4b2e72-5f6a-11d2-8f20-0000c0e166dc}' // Related Master Assets
];

function getResultPage(state, result, pointer, rowCount) {
  return state.cip.request([
    'metadata',
    'getfieldvalues',
    'web'
  ], {
    collection: result.collection_id,
    startindex: pointer,
    maxreturned: rowCount,
    field: ADDITIONAL_FIELDS
  }).then(function(response) {
    if (response === null || typeof(response.body.items) === 'undefined') {
      console.error('Unexpected response:', response);
      throw new Error('The request for field values returned an empty result.');
    } else {
      var result = [];
      for (var i = 0; i < response.body.items.length; i++) {
        result.push(response.body.items[i]);
      }
      return result;
    }
  });
}

/**
 * Process a specific result page, with assets.
 */
function processResultPage(state, result, pageIndex) {
  var catalog = result.catalog;

  var totalPages = Math.ceil(result.total_rows / ASSETS_PER_REQUEST);
  console.log('Queuing page number',
              pageIndex + 1,
              'of',
              totalPages,
              'in the',
              catalog.alias,
              'catalog.');

  return getResultPage(state,
                       result,
                       pageIndex * ASSETS_PER_REQUEST,
                       ASSETS_PER_REQUEST)
  .then(function(assetsOnPage) {
    console.log('Got metadata of page',
                pageIndex + 1,
                'from the',
                result.catalog.alias,
                'catalog.');
    var assetPromises = assetsOnPage.map(function(asset) {
      asset.catalog = catalog.alias;
      var assetPromise = processAsset(state, asset);
      return assetPromise;
    });
    return Q.all(assetPromises);
  });
}

/**
 * Recursively handle the assets on pages, giving a breath first traversal
 * of the CIP webservice.
 */
function processNextResultPage(state, result, indexedAssetsIds) {
  // If the function was called without a value for the indexedAssetIds.
  if (!indexedAssetsIds) {
    indexedAssetsIds = [];
  }
  // Do we still have pages in the result?
  if (result.pageIndex * ASSETS_PER_REQUEST < result.total_rows) {
    return processResultPage(state, result, result.pageIndex)
    .then(function(newIndexedAssetIds) {
      // Increment the page index of this catalog
      result.pageIndex++;
      // Let's concat the newly index asset ids.
      indexedAssetsIds = indexedAssetsIds.concat(newIndexedAssetIds);
      return processNextResultPage(state, result, indexedAssetsIds);
    });
  } else {
    // No more pages in the result, let's return the final array of indexed
    // asset ids.
    return new Q(indexedAssetsIds);
  }
}

function processResult(state, result) {
  console.log('Processing a result of', result.total_rows, 'assets');
  // TODO: Support an offset defined by state.catalogPageIndex
  if (!result.pageIndex) {
    result.pageIndex = 0;
  }
  // Start handling the result's page recursively.
  return processNextResultPage(state, result);
}

module.exports = processResult;
<commit_msg>The body might be empty<commit_after>'use strict';

/**
 * The processor handling an entire result.
 */

var Q = require('q');

var processAsset = require('./asset');

var ASSETS_PER_REQUEST = 100;

var ADDITIONAL_FIELDS = [
  '{af4b2e71-5f6a-11d2-8f20-0000c0e166dc}', // Related Sub Assets
  '{af4b2e72-5f6a-11d2-8f20-0000c0e166dc}' // Related Master Assets
];

function getResultPage(state, result, pointer, rowCount) {
  return state.cip.request([
    'metadata',
    'getfieldvalues',
    'web'
  ], {
    collection: result.collection_id,
    startindex: pointer,
    maxreturned: rowCount,
    field: ADDITIONAL_FIELDS
  }).then(function(response) {
    if (!response ||
        !response.body ||
        typeof(response.body.items) === 'undefined') {
      console.error('Unexpected response:', response);
      throw new Error('The request for field values returned an empty result.');
    } else {
      var result = [];
      for (var i = 0; i < response.body.items.length; i++) {
        result.push(response.body.items[i]);
      }
      return result;
    }
  });
}

/**
 * Process a specific result page, with assets.
 */
function processResultPage(state, result, pageIndex) {
  var catalog = result.catalog;

  var totalPages = Math.ceil(result.total_rows / ASSETS_PER_REQUEST);
  console.log('Queuing page number',
              pageIndex + 1,
              'of',
              totalPages,
              'in the',
              catalog.alias,
              'catalog.');

  return getResultPage(state,
                       result,
                       pageIndex * ASSETS_PER_REQUEST,
                       ASSETS_PER_REQUEST)
  .then(function(assetsOnPage) {
    console.log('Got metadata of page',
                pageIndex + 1,
                'from the',
                result.catalog.alias,
                'catalog.');
    var assetPromises = assetsOnPage.map(function(asset) {
      asset.catalog = catalog.alias;
      var assetPromise = processAsset(state, asset);
      return assetPromise;
    });
    return Q.all(assetPromises);
  });
}

/**
 * Recursively handle the assets on pages, giving a breath first traversal
 * of the CIP webservice.
 */
function processNextResultPage(state, result, indexedAssetsIds) {
  // If the function was called without a value for the indexedAssetIds.
  if (!indexedAssetsIds) {
    indexedAssetsIds = [];
  }
  // Do we still have pages in the result?
  if (result.pageIndex * ASSETS_PER_REQUEST < result.total_rows) {
    return processResultPage(state, result, result.pageIndex)
    .then(function(newIndexedAssetIds) {
      // Increment the page index of this catalog
      result.pageIndex++;
      // Let's concat the newly index asset ids.
      indexedAssetsIds = indexedAssetsIds.concat(newIndexedAssetIds);
      return processNextResultPage(state, result, indexedAssetsIds);
    });
  } else {
    // No more pages in the result, let's return the final array of indexed
    // asset ids.
    return new Q(indexedAssetsIds);
  }
}

function processResult(state, result) {
  console.log('Processing a result of', result.total_rows, 'assets');
  // TODO: Support an offset defined by state.catalogPageIndex
  if (!result.pageIndex) {
    result.pageIndex = 0;
  }
  // Start handling the result's page recursively.
  return processNextResultPage(state, result);
}

module.exports = processResult;
<|endoftext|>


<commit_before>function saveOptions(e) {
  e.preventDefault();

  var defaultUser = document.getElementById('defaultUser').value;
  var quietHours = document.getElementById('quietHours').value;
  var pollInterval = document.getElementById('pollInterval').value;

  chrome.storage.sync.set({
    defaultUser: defaultUser,
    quietHours: quietHours,
    pollInterval: pollInterval
  }, function() {
    // Update status to let user know options were saved.
    var status = document.getElementById('status');
    status.textContent = 'Options saved.';
    setTimeout(function() {
      status.textContent = '';
    }, 3000);
  });

  return false;
}

function restoreOptions() {
  chrome.storage.sync.get({
    defaultUser: '0',
    quietHours: '',
    pollInterval: 0
  }, function(items) {
    document.getElementById('defaultUser').value = items.defaultUser;
    document.getElementById('quietHours').value = items.quietHours;
      document.getElementById('pollInterval').value = items.pollInterval;
  });
}

function defaultOptions() {
  document.getElementById('defaultUser').value = 0;
  document.getElementById('quietHours').value = '';
  document.getElementById('pollInterval').value = 1;
}

function main() {
  if (!chrome || !chrome.storage || !chrome.storage.sync) {
    var status = document.getElementById('status');
    status.style.cssText = 'color:red;';
    status.textContent = 'Error: Could not load settings. Please upgrade Chrome.';
    return;
  }
  document.addEventListener('DOMContentLoaded', restoreOptions);
  document.getElementById('defaults').addEventListener('click', defaultOptions);
  document.getElementById('optionsForm').addEventListener('submit', saveOptions);
}

main();
<commit_msg>Default polling interval to '1'.<commit_after>function saveOptions(e) {
  e.preventDefault();

  var defaultUser = document.getElementById('defaultUser').value;
  var quietHours = document.getElementById('quietHours').value;
  var pollInterval = document.getElementById('pollInterval').value;

  chrome.storage.sync.set({
    defaultUser: defaultUser,
    quietHours: quietHours,
    pollInterval: pollInterval
  }, function() {
    // Update status to let user know options were saved.
    var status = document.getElementById('status');
    status.textContent = 'Options saved.';
    setTimeout(function() {
      status.textContent = '';
    }, 3000);
  });

  return false;
}

function restoreOptions() {
  chrome.storage.sync.get({
    defaultUser: '0',
    quietHours: '',
    pollInterval: '1'
  }, function(items) {
    document.getElementById('defaultUser').value = items.defaultUser;
    document.getElementById('quietHours').value = items.quietHours;
      document.getElementById('pollInterval').value = items.pollInterval || 1;
  });
}

function defaultOptions() {
  document.getElementById('defaultUser').value = 0;
  document.getElementById('quietHours').value = '';
  document.getElementById('pollInterval').value = 1;
}

function main() {
  if (!chrome || !chrome.storage || !chrome.storage.sync) {
    var status = document.getElementById('status');
    status.style.cssText = 'color:red;';
    status.textContent = 'Error: Could not load settings. Please upgrade Chrome.';
    return;
  }
  document.addEventListener('DOMContentLoaded', restoreOptions);
  document.getElementById('defaults').addEventListener('click', defaultOptions);
  document.getElementById('optionsForm').addEventListener('submit', saveOptions);
}

main();
<|endoftext|>


<commit_before>(function() {
  var chokidar, colors, fs, helpers, iced, inquirer, mkdirp, path, request, sass, __iced_k, __iced_k_noop;

  iced = require('iced-runtime');
  __iced_k = __iced_k_noop = function() {};

  helpers = require('./helpers');

  chokidar = require('chokidar');

  inquirer = require('inquirer');

  colors = require('colors');

  fs = require('fs');

  path = require('path');

  request = require('request');

  mkdirp = require('mkdirp');

  sass = require('node-sass');

  exports.run = function(argv, done) {
    var config, err, target, watcher, ___iced_passed_deferral, __iced_deferrals, __iced_k;
    __iced_k = __iced_k_noop;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    (function(_this) {
      return (function(__iced_k) {
        __iced_deferrals = new iced.Deferrals(__iced_k, {
          parent: ___iced_passed_deferral,
          filename: "lib/watch.iced",
          funcname: "run"
        });
        helpers.loadConfig(__iced_deferrals.defer({
          assign_fn: (function() {
            return function() {
              err = arguments[0];
              return config = arguments[1];
            };
          })(),
          lineno: 14
        }));
        __iced_deferrals._fulfill();
      });
    })(this)((function(_this) {
      return function() {
        if (typeof err !== "undefined" && err !== null) {
          done(err);
        }
        (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "lib/watch.iced",
            funcname: "run"
          });
          helpers.getTarget(config, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return target = arguments[1];
              };
            })(),
            lineno: 17
          }));
          __iced_deferrals._fulfill();
        })(function() {
          if (typeof err !== "undefined" && err !== null) {
            done(err);
          }
          watcher = chokidar.watch('./', {
            ignored: /[\/\\]\./,
            persistent: true,
            ignoreInitial: true,
            usePolling: true,
            interval: 250,
            binaryInterval: 250,
            cwd: process.cwd()
          });
          watcher.on('all', function(event, filepath) {
            var assetsBody, data, err, extension, mainscss, res, result, targetscss, ___iced_passed_deferral1, __iced_deferrals, __iced_k;
            __iced_k = __iced_k_noop;
            ___iced_passed_deferral1 = iced.findDeferral(arguments);
            extension = path.extname(filepath).substr(1);
            if (filepath.match(/^quickshot.json$/)) {
              return;
            }
            switch (event) {
              case 'add':
              case 'change':
                if (filepath.match(/[\(\)]/)) {
                  return console.log(colors.red("Filename may not contain parentheses, please rename - \"" + filepath + "\""));
                }
                (function(_this) {
                  return (function(__iced_k) {
                    if (config.compile_scss && filepath.match(/\.scss$/)) {
                      mainscss = config.primary_scss_file;
                      targetscss = mainscss.replace('.scss', '.css');
                      console.log(colors.yellow("Compiling Sass: \"" + mainscss + "\" -> \"" + targetscss + "\""));
                      (function(__iced_k) {
                        __iced_deferrals = new iced.Deferrals(__iced_k, {
                          parent: ___iced_passed_deferral1,
                          filename: "lib/watch.iced"
                        });
                        sass.render({
                          file: mainscss,
                          outFile: targetscss
                        }, __iced_deferrals.defer({
                          assign_fn: (function() {
                            return function() {
                              err = arguments[0];
                              return result = arguments[1];
                            };
                          })(),
                          lineno: 45
                        }));
                        __iced_deferrals._fulfill();
                      })(function() {
                        if (err != null) {
                          done(err);
                        }
                        (function(__iced_k) {
                          __iced_deferrals = new iced.Deferrals(__iced_k, {
                            parent: ___iced_passed_deferral1,
                            filename: "lib/watch.iced"
                          });
                          fs.writeFile(targetscss, result.css, __iced_deferrals.defer({
                            assign_fn: (function() {
                              return function() {
                                return err = arguments[0];
                              };
                            })(),
                            lineno: 47
                          }));
                          __iced_deferrals._fulfill();
                        })(function() {
                          return __iced_k(err != null ? done(err) : void 0);
                        });
                      });
                    } else {
                      return __iced_k();
                    }
                  });
                })(this)((function(_this) {
                  return function() {
                    (function(__iced_k) {
                      __iced_deferrals = new iced.Deferrals(__iced_k, {
                        parent: ___iced_passed_deferral1,
                        filename: "lib/watch.iced"
                      });
                      fs.readFile(filepath, __iced_deferrals.defer({
                        assign_fn: (function() {
                          return function() {
                            err = arguments[0];
                            return data = arguments[1];
                          };
                        })(),
                        lineno: 50
                      }));
                      __iced_deferrals._fulfill();
                    })(function() {
                      (function(__iced_k) {
                        __iced_deferrals = new iced.Deferrals(__iced_k, {
                          parent: ___iced_passed_deferral1,
                          filename: "lib/watch.iced"
                        });
                        helpers.shopifyRequest({
                          filepath: filepath,
                          method: 'put',
                          url: "https://" + target.api_key + ":" + target.password + "@" + target.domain + ".myshopify.com/admin/themes/" + target.theme_id + "/assets.json",
                          json: {
                            asset: {
                              key: filepath,
                              attachment: data.toString('base64')
                            }
                          }
                        }, __iced_deferrals.defer({
                          assign_fn: (function() {
                            return function() {
                              err = arguments[0];
                              res = arguments[1];
                              return assetsBody = arguments[2];
                            };
                          })(),
                          lineno: 61
                        }));
                        __iced_deferrals._fulfill();
                      })(function() {
                        if (typeof err !== "undefined" && err !== null) {
                          done(err);
                        }
                        return __iced_k(console.log(colors.green("Added/Updated " + filepath)));
                      });
                    });
                  };
                })(this));
                break;
              case 'unlink':
                (function(_this) {
                  return (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral1,
                      filename: "lib/watch.iced"
                    });
                    helpers.shopifyRequest({
                      method: 'delete',
                      url: "https://" + target.api_key + ":" + target.password + "@" + target.domain + ".myshopify.com/admin/themes/" + target.theme_id + "/assets.json",
                      qs: {
                        asset: {
                          key: filepath
                        }
                      }
                    }, __iced_deferrals.defer({
                      assign_fn: (function() {
                        return function() {
                          err = arguments[0];
                          res = arguments[1];
                          return assetsBody = arguments[2];
                        };
                      })(),
                      lineno: 72
                    }));
                    __iced_deferrals._fulfill();
                  });
                })(this)((function(_this) {
                  return function() {
                    if (err != null) {
                      done(err);
                    }
                    return __iced_k(console.log(colors.green("Deleted " + filepath)));
                  };
                })(this));
                break;
              default:
                return __iced_k();
            }
          });
          return console.log("Watching Files...");
        });
      };
    })(this));
  };

}).call(this);
<commit_msg>recompile watch<commit_after>(function() {
  var chokidar, colors, fs, helpers, iced, inquirer, mkdirp, parser, path, request, sass, __iced_k, __iced_k_noop;

  iced = require('iced-runtime');
  __iced_k = __iced_k_noop = function() {};

  helpers = require('./helpers');

  chokidar = require('chokidar');

  inquirer = require('inquirer');

  colors = require('colors');

  fs = require('fs');

  path = require('path');

  request = require('request');

  mkdirp = require('mkdirp');

  sass = require('node-sass');

  parser = require('gitignore-parser');

  exports.run = function(argv, done) {
    var config, err, ignore, target, watcher, ___iced_passed_deferral, __iced_deferrals, __iced_k;
    __iced_k = __iced_k_noop;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    (function(_this) {
      return (function(__iced_k) {
        __iced_deferrals = new iced.Deferrals(__iced_k, {
          parent: ___iced_passed_deferral,
          filename: "lib/watch.iced",
          funcname: "run"
        });
        helpers.loadConfig(__iced_deferrals.defer({
          assign_fn: (function() {
            return function() {
              err = arguments[0];
              return config = arguments[1];
            };
          })(),
          lineno: 15
        }));
        __iced_deferrals._fulfill();
      });
    })(this)((function(_this) {
      return function() {
        if (typeof err !== "undefined" && err !== null) {
          done(err);
        }
        ignore = parser.compile(fs.readFileSync(config.ignore_file, 'utf8'));
        (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "lib/watch.iced",
            funcname: "run"
          });
          helpers.getTarget(config, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return target = arguments[1];
              };
            })(),
            lineno: 20
          }));
          __iced_deferrals._fulfill();
        })(function() {
          if (typeof err !== "undefined" && err !== null) {
            done(err);
          }
          watcher = chokidar.watch('./', {
            ignored: /[\/\\]\./,
            persistent: true,
            ignoreInitial: true,
            usePolling: true,
            interval: 250,
            binaryInterval: 250,
            cwd: process.cwd()
          });
          watcher.on('all', function(event, filepath) {
            var assetsBody, data, err, extension, mainscss, res, result, targetscss, ___iced_passed_deferral1, __iced_deferrals, __iced_k;
            __iced_k = __iced_k_noop;
            ___iced_passed_deferral1 = iced.findDeferral(arguments);
            extension = path.extname(filepath).substr(1);
            if (filepath.match(/^quickshot.json$/)) {
              return;
            }
            if (filepath.match(/^\..*$/)) {
              return;
            }
            if (ignore.denies(filepath)) {
              return;
            }
            switch (event) {
              case 'add':
              case 'change':
                if (filepath.match(/[\(\)]/)) {
                  return console.log(colors.red("Filename may not contain parentheses, please rename - \"" + filepath + "\""));
                }
                (function(_this) {
                  return (function(__iced_k) {
                    if (config.compile_scss && filepath.match(/\.scss$/)) {
                      mainscss = config.primary_scss_file;
                      targetscss = mainscss.replace('.scss', '.css');
                      console.log(colors.yellow("Compiling Sass: \"" + mainscss + "\" -> \"" + targetscss + "\""));
                      (function(__iced_k) {
                        __iced_deferrals = new iced.Deferrals(__iced_k, {
                          parent: ___iced_passed_deferral1,
                          filename: "lib/watch.iced"
                        });
                        sass.render({
                          file: mainscss,
                          outFile: targetscss
                        }, __iced_deferrals.defer({
                          assign_fn: (function() {
                            return function() {
                              err = arguments[0];
                              return result = arguments[1];
                            };
                          })(),
                          lineno: 54
                        }));
                        __iced_deferrals._fulfill();
                      })(function() {
                        if (err != null) {
                          done(err);
                        }
                        (function(__iced_k) {
                          __iced_deferrals = new iced.Deferrals(__iced_k, {
                            parent: ___iced_passed_deferral1,
                            filename: "lib/watch.iced"
                          });
                          fs.writeFile(targetscss, result.css, __iced_deferrals.defer({
                            assign_fn: (function() {
                              return function() {
                                return err = arguments[0];
                              };
                            })(),
                            lineno: 56
                          }));
                          __iced_deferrals._fulfill();
                        })(function() {
                          return __iced_k(err != null ? done(err) : void 0);
                        });
                      });
                    } else {
                      return __iced_k();
                    }
                  });
                })(this)((function(_this) {
                  return function() {
                    (function(__iced_k) {
                      __iced_deferrals = new iced.Deferrals(__iced_k, {
                        parent: ___iced_passed_deferral1,
                        filename: "lib/watch.iced"
                      });
                      fs.readFile(filepath, __iced_deferrals.defer({
                        assign_fn: (function() {
                          return function() {
                            err = arguments[0];
                            return data = arguments[1];
                          };
                        })(),
                        lineno: 59
                      }));
                      __iced_deferrals._fulfill();
                    })(function() {
                      (function(__iced_k) {
                        __iced_deferrals = new iced.Deferrals(__iced_k, {
                          parent: ___iced_passed_deferral1,
                          filename: "lib/watch.iced"
                        });
                        helpers.shopifyRequest({
                          filepath: filepath,
                          method: 'put',
                          url: "https://" + target.api_key + ":" + target.password + "@" + target.domain + ".myshopify.com/admin/themes/" + target.theme_id + "/assets.json",
                          json: {
                            asset: {
                              key: filepath,
                              attachment: data.toString('base64')
                            }
                          }
                        }, __iced_deferrals.defer({
                          assign_fn: (function() {
                            return function() {
                              err = arguments[0];
                              res = arguments[1];
                              return assetsBody = arguments[2];
                            };
                          })(),
                          lineno: 70
                        }));
                        __iced_deferrals._fulfill();
                      })(function() {
                        if (typeof err !== "undefined" && err !== null) {
                          done(err);
                        }
                        return __iced_k(console.log(colors.green("Added/Updated " + filepath)));
                      });
                    });
                  };
                })(this));
                break;
              case 'unlink':
                (function(_this) {
                  return (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral1,
                      filename: "lib/watch.iced"
                    });
                    helpers.shopifyRequest({
                      method: 'delete',
                      url: "https://" + target.api_key + ":" + target.password + "@" + target.domain + ".myshopify.com/admin/themes/" + target.theme_id + "/assets.json",
                      qs: {
                        asset: {
                          key: filepath
                        }
                      }
                    }, __iced_deferrals.defer({
                      assign_fn: (function() {
                        return function() {
                          err = arguments[0];
                          res = arguments[1];
                          return assetsBody = arguments[2];
                        };
                      })(),
                      lineno: 81
                    }));
                    __iced_deferrals._fulfill();
                  });
                })(this)((function(_this) {
                  return function() {
                    if (err != null) {
                      done(err);
                    }
                    return __iced_k(console.log(colors.green("Deleted " + filepath)));
                  };
                })(this));
                break;
              default:
                return __iced_k();
            }
          });
          return console.log("Watching Files...");
        });
      };
    })(this));
  };

}).call(this);
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment'; // eslint-disable-line import/no-extraneous-dependencies

import DayPicker from './DayPicker';
import { getModifiersForDay } from './ModifiersUtils';
import MomentLocaleUtils from './addons/MomentLocaleUtils';
import { ESC } from './keys';

// When clicking on a day cell, overlay will be hidden after this timeout
export const HIDE_TIMEOUT = 100;

export default class DayPickerInput extends React.Component {
  static propTypes = {
    value: PropTypes.string,

    format: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.string),
      PropTypes.string,
    ]),

    dayPickerProps: PropTypes.object,
    hideOnDayClick: PropTypes.bool,
    clickUnselectsDay: PropTypes.bool,
    component: PropTypes.any,

    classNames: PropTypes.shape({
      container: PropTypes.string,
      overlayWrapper: PropTypes.string,
      overlay: PropTypes.string.isRequired,
    }),

    onDayChange: PropTypes.func,
    onChange: PropTypes.func,
    onClick: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    onKeyUp: PropTypes.func,
  };

  static defaultProps = {
    dayPickerProps: {},
    value: '',
    format: 'L',
    hideOnDayClick: true,
    clickUnselectsDay: false,
    component: 'input',
    classNames: {
      container: 'DayPickerInput',
      overlayWrapper: 'DayPickerInput-OverlayWrapper',
      overlay: 'DayPickerInput-Overlay',
    },
  };

  constructor(props) {
    super(props);
    this.state = this.getStateFromProps(props);
    this.state.showOverlay = false;
    this.hideAfterDayClick = this.hideAfterDayClick.bind(this);
    this.handleContainerMouseDown = this.handleContainerMouseDown.bind(this);
    this.handleInputClick = this.handleInputClick.bind(this);
    this.handleInputFocus = this.handleInputFocus.bind(this);
    this.handleInputBlur = this.handleInputBlur.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInputOnKeyUp = this.handleInputOnKeyUp.bind(this);
    this.handleDayClick = this.handleDayClick.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    const { dayPickerProps, value } = this.props;
    const currentMonth = dayPickerProps.month;
    const nextMonth = nextProps.dayPickerProps.month;
    const nextValue = nextProps.value;

    const shouldUpdateMonth =
      (nextMonth && !currentMonth) ||
      (nextMonth &&
        (nextMonth.getFullYear() !== currentMonth.getFullYear() ||
          nextMonth.getMonth() !== currentMonth.getMonth()));

    if (nextValue !== value && !shouldUpdateMonth) {
      this.setState(this.getStateFromProps(nextProps));
    } else if (shouldUpdateMonth) {
      this.setState({ month: nextMonth });
    }
  }

  componentWillUnmount() {
    clearTimeout(this.clickTimeout);
    clearTimeout(this.hideTimeout);
    clearTimeout(this.blurTimeout);
  }

  getStateFromProps(props) {
    const { dayPickerProps, format, value } = props;
    let month;
    if (value) {
      // Display the month specified in the value prop
      const m = moment(value, format, true);
      if (m.isValid()) {
        month = m.toDate();
      }
    } else {
      // Otherwise display the month coming from `dayPickerProps` or the current month
      month = dayPickerProps.initialMonth || dayPickerProps.month || new Date();
    }
    return {
      value,
      month,
      selectedDays: dayPickerProps.selectedDays,
    };
  }

  input = null;
  daypicker = null;
  clickedInside = false;
  clickTimeout = null;
  hideTimeout = null;

  /**
   * Update the component's state and fire the `onDayChange` event
   * passing the day's modifiers to it
   * @param {Date} day - Will be used for changing the month
   * @param {String} value - Input field value
   * @private
   */
  updateState(day, value) {
    const { dayPickerProps, onDayChange } = this.props;
    this.setState({ month: day, value }, () => {
      if (!onDayChange) {
        return;
      }
      const modifiersObj = {
        disabled: dayPickerProps.disabledDays,
        selected: dayPickerProps.selectedDays,
        ...dayPickerProps.modifiers,
      };
      const modifiers = getModifiersForDay(
        day,
        modifiersObj
      ).reduce((obj, modifier) => {
        const newObj = { ...obj };
        newObj[modifier] = true;
        return newObj;
      }, {});
      onDayChange(moment(day), modifiers);
    });
  }

  /**
   * Show the Day Picker overlay.
   *
   * @memberof DayPickerInput
   */
  showDayPicker() {
    this.setState({
      showOverlay: true,
    });
  }

  /**
   * Hide the Day Picker overlay
   *
   * @memberof DayPickerInput
   */
  hideDayPicker() {
    this.setState({
      showOverlay: false,
    });
  }

  hideAfterDayClick() {
    if (!this.props.hideOnDayClick) {
      return;
    }
    this.hideTimeout = setTimeout(() => this.hideDayPicker(), HIDE_TIMEOUT);
  }

  handleContainerMouseDown() {
    this.clickedInside = true;
    // The input's onBlur method is called from a queue right after the onMouseDown event.
    // setTimeout adds another callback in the queue, which is called after the onBlur event.
    this.clickTimeout = setTimeout(() => {
      this.clickedInside = false;
    }, 0);
  }

  handleInputClick(e) {
    this.showDayPicker();
    if (this.props.onClick) {
      e.persist();
      this.props.onClick(e);
    }
  }

  handleInputFocus(e) {
    this.showDayPicker();
    if (this.props.onFocus) {
      e.persist();
      this.props.onFocus(e);
    }
  }

  handleInputBlur(e) {
    this.setState({
      showOverlay: this.clickedInside,
    });
    // Force input's focus if blur event was caused by clicking inside the overlay
    if (this.clickedInside) {
      this.blurTimeout = setTimeout(() => this.input.focus(), 0);
    }
    if (this.props.onBlur) {
      e.persist();
      this.props.onBlur(e);
    }
  }

  handleInputChange(e) {
    const { onChange, onDayChange, format } = this.props;
    if (onChange) {
      e.persist();
      onChange(e);
    }
    const { value } = e.target;
    const m = moment(value, format, true);
    if (value.trim() === '') {
      this.setState({ value });
      if (onDayChange) {
        onDayChange(undefined, {});
      }
      return;
    }
    if (!m.isValid()) {
      this.setState({ value });
      return;
    }
    const day = m.toDate();
    this.updateState(day, value);
  }

  handleInputOnKeyUp(e) {
    // Hide the overlay if the ESC key is pressed
    this.setState({ showOverlay: e.keyCode !== ESC });
    if (this.props.onKeyUp) {
      e.persist();
      this.props.onKeyUp(e);
    }
  }

  handleDayClick(day, modifiers, e) {
    const {
      clickUnselectsDay,
      dayPickerProps,
      onDayChange,
      format,
    } = this.props;
    if (dayPickerProps.onDayClick) {
      dayPickerProps.onDayClick(day, modifiers, e);
    }

    // Do nothing if the day is disabled
    if (modifiers.disabled) {
      return;
    }

    // If the clicked day is already selected, remove the clicked day
    // from the selected days and empty the field value
    if (modifiers.selected && clickUnselectsDay) {
      let { selectedDays } = this.state;
      if (Array.isArray(selectedDays)) {
        selectedDays = selectedDays.slice(0);
        const selectedDayIdx = selectedDays.indexOf(day);
        selectedDays.splice(selectedDayIdx, 1);
      } else if (moment(selectedDays).isValid()) {
        selectedDays = null;
      }
      this.setState({ value: '', selectedDays }, this.hideAfterDayClick);
      if (onDayChange) {
        onDayChange(undefined, modifiers);
      }
      return;
    }

    const m = moment(day);
    const value = m.format(typeof format === 'string' ? format : format[0]);
    this.setState({ value, month: day }, () => {
      if (onDayChange) {
        onDayChange(m, modifiers);
      }
      this.hideAfterDayClick();
    });
  }

  renderOverlay() {
    const { format, classNames, dayPickerProps } = this.props;
    const { selectedDays, value } = this.state;
    let selectedDay;
    if (!selectedDays && value) {
      const m = moment(value, format, true);
      if (m.isValid()) {
        selectedDay = m.toDate();
      }
    } else if (selectedDays) {
      selectedDay = selectedDays;
    }

    let onTodayButtonClick;
    if (dayPickerProps.todayButton) {
      // Set the current day when clicking the today button
      onTodayButtonClick = () =>
        this.updateState(new Date(), moment().format(this.props.format));
    }

    return (

          <DayPicker
            ref={el => (this.daypicker = el)}
            localeUtils={MomentLocaleUtils}
            fixedWeeks
            onTodayButtonClick={onTodayButtonClick}
            {...dayPickerProps}
            month={this.state.month}
            selectedDays={selectedDay}
            onDayClick={this.handleDayClick}
          />

    );
  }

  render() {
    const inputProps = { ...this.props };
    delete inputProps.component;
    delete inputProps.dayPickerProps;
    delete inputProps.format;
    delete inputProps.clickUnselectsDay;
    delete inputProps.hideOnDayClick;
    delete inputProps.onDayChange;
    delete inputProps.classNames;
    return (

        {React.createElement(this.props.component, {
          ref: el => (this.input = el),
          ...inputProps,
          value: this.state.value,
          onChange: this.handleInputChange,
          onFocus: this.handleInputFocus,
          onBlur: this.handleInputBlur,
          onKeyUp: this.handleInputOnKeyUp,
          onClick: this.handleInputClick,
        })}
        {this.state.showOverlay && this.renderOverlay()}

    );
  }
}
<commit_msg>Update value when changed from props<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment'; // eslint-disable-line import/no-extraneous-dependencies

import DayPicker from './DayPicker';
import { getModifiersForDay } from './ModifiersUtils';
import MomentLocaleUtils from './addons/MomentLocaleUtils';
import { ESC } from './keys';

// When clicking on a day cell, overlay will be hidden after this timeout
export const HIDE_TIMEOUT = 100;

export default class DayPickerInput extends React.Component {
  static propTypes = {
    value: PropTypes.string,

    format: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.string),
      PropTypes.string,
    ]),

    dayPickerProps: PropTypes.object,
    hideOnDayClick: PropTypes.bool,
    clickUnselectsDay: PropTypes.bool,
    component: PropTypes.any,

    classNames: PropTypes.shape({
      container: PropTypes.string,
      overlayWrapper: PropTypes.string,
      overlay: PropTypes.string.isRequired,
    }),

    onDayChange: PropTypes.func,
    onChange: PropTypes.func,
    onClick: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    onKeyUp: PropTypes.func,
  };

  static defaultProps = {
    dayPickerProps: {},
    value: '',
    format: 'L',
    hideOnDayClick: true,
    clickUnselectsDay: false,
    component: 'input',
    classNames: {
      container: 'DayPickerInput',
      overlayWrapper: 'DayPickerInput-OverlayWrapper',
      overlay: 'DayPickerInput-Overlay',
    },
  };

  constructor(props) {
    super(props);
    this.state = this.getStateFromProps(props);
    this.state.showOverlay = false;
    this.hideAfterDayClick = this.hideAfterDayClick.bind(this);
    this.handleContainerMouseDown = this.handleContainerMouseDown.bind(this);
    this.handleInputClick = this.handleInputClick.bind(this);
    this.handleInputFocus = this.handleInputFocus.bind(this);
    this.handleInputBlur = this.handleInputBlur.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInputOnKeyUp = this.handleInputOnKeyUp.bind(this);
    this.handleDayClick = this.handleDayClick.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    const monthFromProps = this.props.dayPickerProps.month;
    const nextMonthFromProps = nextProps.dayPickerProps.month;
    const nextValue = nextProps.value;
    const currentValue = this.props.value;

    const monthChanged =
      (nextMonthFromProps && !monthFromProps) ||
      (nextMonthFromProps &&
        (nextMonthFromProps.getFullYear() !== monthFromProps.getFullYear() ||
          nextMonthFromProps.getMonth() !== monthFromProps.getMonth()));

    if (nextValue !== currentValue) {
      this.setState({ value: nextValue });
    }
    if (monthChanged) {
      this.setState({ month: nextMonthFromProps });
    }
  }

  componentWillUnmount() {
    clearTimeout(this.clickTimeout);
    clearTimeout(this.hideTimeout);
    clearTimeout(this.blurTimeout);
  }

  getStateFromProps(props) {
    const { dayPickerProps, format, value } = props;
    let month;
    if (value) {
      // Display the month specified in the value prop
      const m = moment(value, format, true);
      if (m.isValid()) {
        month = m.toDate();
      }
    } else {
      // Otherwise display the month coming from `dayPickerProps` or the current month
      month = dayPickerProps.initialMonth || dayPickerProps.month || new Date();
    }
    return {
      value,
      month,
      selectedDays: dayPickerProps.selectedDays,
    };
  }

  input = null;
  daypicker = null;
  clickedInside = false;
  clickTimeout = null;
  hideTimeout = null;

  /**
   * Update the component's state and fire the `onDayChange` event
   * passing the day's modifiers to it
   * @param {Date} day - Will be used for changing the month
   * @param {String} value - Input field value
   * @private
   */
  updateState(day, value) {
    const { dayPickerProps, onDayChange } = this.props;
    this.setState({ month: day, value }, () => {
      if (!onDayChange) {
        return;
      }
      const modifiersObj = {
        disabled: dayPickerProps.disabledDays,
        selected: dayPickerProps.selectedDays,
        ...dayPickerProps.modifiers,
      };
      const modifiers = getModifiersForDay(
        day,
        modifiersObj
      ).reduce((obj, modifier) => {
        const newObj = { ...obj };
        newObj[modifier] = true;
        return newObj;
      }, {});
      onDayChange(moment(day), modifiers);
    });
  }

  /**
   * Show the Day Picker overlay.
   *
   * @memberof DayPickerInput
   */
  showDayPicker() {
    this.setState({
      showOverlay: true,
    });
  }

  /**
   * Hide the Day Picker overlay
   *
   * @memberof DayPickerInput
   */
  hideDayPicker() {
    this.setState({
      showOverlay: false,
    });
  }

  hideAfterDayClick() {
    if (!this.props.hideOnDayClick) {
      return;
    }
    this.hideTimeout = setTimeout(() => this.hideDayPicker(), HIDE_TIMEOUT);
  }

  handleContainerMouseDown() {
    this.clickedInside = true;
    // The input's onBlur method is called from a queue right after the onMouseDown event.
    // setTimeout adds another callback in the queue, which is called after the onBlur event.
    this.clickTimeout = setTimeout(() => {
      this.clickedInside = false;
    }, 0);
  }

  handleInputClick(e) {
    this.showDayPicker();
    if (this.props.onClick) {
      e.persist();
      this.props.onClick(e);
    }
  }

  handleInputFocus(e) {
    this.showDayPicker();
    if (this.props.onFocus) {
      e.persist();
      this.props.onFocus(e);
    }
  }

  handleInputBlur(e) {
    this.setState({
      showOverlay: this.clickedInside,
    });
    // Force input's focus if blur event was caused by clicking inside the overlay
    if (this.clickedInside) {
      this.blurTimeout = setTimeout(() => this.input.focus(), 0);
    }
    if (this.props.onBlur) {
      e.persist();
      this.props.onBlur(e);
    }
  }

  handleInputChange(e) {
    const { onChange, onDayChange, format } = this.props;
    if (onChange) {
      e.persist();
      onChange(e);
    }
    const { value } = e.target;
    const m = moment(value, format, true);
    if (value.trim() === '') {
      this.setState({ value });
      if (onDayChange) {
        onDayChange(undefined, {});
      }
      return;
    }
    if (!m.isValid()) {
      this.setState({ value });
      return;
    }
    const day = m.toDate();
    this.updateState(day, value);
  }

  handleInputOnKeyUp(e) {
    // Hide the overlay if the ESC key is pressed
    this.setState({ showOverlay: e.keyCode !== ESC });
    if (this.props.onKeyUp) {
      e.persist();
      this.props.onKeyUp(e);
    }
  }

  handleDayClick(day, modifiers, e) {
    const {
      clickUnselectsDay,
      dayPickerProps,
      onDayChange,
      format,
    } = this.props;
    if (dayPickerProps.onDayClick) {
      dayPickerProps.onDayClick(day, modifiers, e);
    }

    // Do nothing if the day is disabled
    if (modifiers.disabled) {
      return;
    }

    // If the clicked day is already selected, remove the clicked day
    // from the selected days and empty the field value
    if (modifiers.selected && clickUnselectsDay) {
      let { selectedDays } = this.state;
      if (Array.isArray(selectedDays)) {
        selectedDays = selectedDays.slice(0);
        const selectedDayIdx = selectedDays.indexOf(day);
        selectedDays.splice(selectedDayIdx, 1);
      } else if (moment(selectedDays).isValid()) {
        selectedDays = null;
      }
      this.setState({ value: '', selectedDays }, this.hideAfterDayClick);
      if (onDayChange) {
        onDayChange(undefined, modifiers);
      }
      return;
    }

    const m = moment(day);
    const value = m.format(typeof format === 'string' ? format : format[0]);
    this.setState({ value, month: day }, () => {
      if (onDayChange) {
        onDayChange(m, modifiers);
      }
      this.hideAfterDayClick();
    });
  }

  renderOverlay() {
    const { format, classNames, dayPickerProps } = this.props;
    const { selectedDays, value } = this.state;
    let selectedDay;
    if (!selectedDays && value) {
      const m = moment(value, format, true);
      if (m.isValid()) {
        selectedDay = m.toDate();
      }
    } else if (selectedDays) {
      selectedDay = selectedDays;
    }

    let onTodayButtonClick;
    if (dayPickerProps.todayButton) {
      // Set the current day when clicking the today button
      onTodayButtonClick = () =>
        this.updateState(new Date(), moment().format(this.props.format));
    }

    return (

          <DayPicker
            ref={el => (this.daypicker = el)}
            localeUtils={MomentLocaleUtils}
            fixedWeeks
            onTodayButtonClick={onTodayButtonClick}
            {...dayPickerProps}
            month={this.state.month}
            selectedDays={selectedDay}
            onDayClick={this.handleDayClick}
          />

    );
  }

  render() {
    const inputProps = { ...this.props };
    delete inputProps.component;
    delete inputProps.dayPickerProps;
    delete inputProps.format;
    delete inputProps.clickUnselectsDay;
    delete inputProps.hideOnDayClick;
    delete inputProps.onDayChange;
    delete inputProps.classNames;
    return (

        {React.createElement(this.props.component, {
          ref: el => (this.input = el),
          ...inputProps,
          value: this.state.value,
          onChange: this.handleInputChange,
          onFocus: this.handleInputFocus,
          onBlur: this.handleInputBlur,
          onKeyUp: this.handleInputOnKeyUp,
          onClick: this.handleInputClick,
        })}
        {this.state.showOverlay && this.renderOverlay()}

    );
  }
}
<|endoftext|>


<commit_before>import DataSource, {NetworkSource, NetworkTileSource} from './data_source';
import {decodeMultiPolygon} from './mvt';
import Geo from '../geo';

// For tiling GeoJSON client-side
import geojsonvt from 'geojson-vt';

/**
 GeoJSON standalone (non-tiled) source
 Uses geojson-vt split into tiles client-side
*/

export class GeoJSONSource extends NetworkSource {

    constructor(source) {
        super(source);
        this.tiled = true;
        this.load_data = null;
        this.tile_indexes = {}; // geojson-vt tile indices, by layer name
        this.max_zoom = Math.max(this.max_zoom || 0, 15); // TODO: max zoom < 15 causes artifacts/no-draw at 20, investigate
        this.pad_scale = 0; // we don't want padding on auto-tiled sources
    }

    _load(dest) {
        if (!this.load_data) {
            this.load_data = super._load({ source_data: { layers: {} } }).then(data => {
                let layers = data.source_data.layers;
                for (let layer_name in layers) {
                    this.tile_indexes[layer_name] = geojsonvt(layers[layer_name], {
                        maxZoom: this.max_zoom,  // max zoom to preserve detail on
                        tolerance: 3, // simplification tolerance (higher means simpler)
                        extent: Geo.tile_scale, // tile extent (both width and height)
                        buffer: 0     // tile buffer on each side
                    });
                }

                this.loaded = true;
                return data;
            });
        }

        return this.load_data.then(() => {
            for (let layer_name in this.tile_indexes) {
                dest.source_data.layers[layer_name] = this.getTileFeatures(dest, layer_name);
            }
            return dest;
        });
    }

    getTileFeatures(tile, layer_name) {
        let coords = Geo.wrapTile(tile.coords, { x: true });

        // request a particular tile
        let t = this.tile_indexes[layer_name].getTile(coords.z, coords.x, coords.y);

        // Convert from MVT-style JSON struct to GeoJSON
        let collection;
        if (t && t.features) {
            collection = {
                type: 'FeatureCollection',
                features: []
            };

            for (let feature of t.features) {
                // GeoJSON feature
                let f = {
                    type: 'Feature',
                    geometry: {},
                    properties: feature.tags
                };

                if (feature.type === 1) {
                    f.geometry.coordinates = feature.geometry.map(coord => [coord[0], coord[1]]);
                    f.geometry.type = 'MultiPoint';
                }
                else if (feature.type === 2 || feature.type === 3) {
                    f.geometry.coordinates = feature.geometry.map(ring =>
                        ring.map(coord => [coord[0], coord[1]])
                    );

                    if (feature.type === 2) {
                        f.geometry.type = 'MultiLineString';
                    }
                    else  {
                        f.geometry = decodeMultiPolygon(f.geometry); // un-flatten rings
                    }
                }
                else {
                    continue;
                }

                collection.features.push(f);
            }
        }

        return collection;
    }

    formatUrl (dest) {
        return this.url;
    }

    parseSourceData (tile, source, response) {
        let parsed_response = JSON.parse(response);
        let layers = this.getLayers(parsed_response);
        this.preprocessLayers(layers);
        source.layers = layers;
    }

    preprocessLayers (layers){
        for (let key in layers) {
            let layer = layers[key];
            this.preprocessFeatures(layer.features);
        }
    }

    // Preprocess features. Currently used to add a new "centroid" feature for polygon labeling
    preprocessFeatures (features) {
        // Define centroids for polygons for centroid label placement
        // Avoids redundant label placement for each generated tile at higher zoom levels
        if (this.config.generate_label_centroids){
            let features_centroid = [];
            let centroid_properties = {"label_placement" : "yes"};

            features.forEach(feature => {
                let coordinates, centroid_feature;
                switch (feature.geometry.type) {
                    case 'Polygon':
                        coordinates = feature.geometry.coordinates;
                        centroid_feature = getCentroidFeatureForPolygon(coordinates, feature.properties, centroid_properties);
                        features_centroid.push(centroid_feature);
                        break;
                    case 'MultiPolygon':
                        // Add centroid feature for largest polygon
                        coordinates = feature.geometry.coordinates;
                        let max_area = -Infinity;
                        let max_area_index = 0;
                        for (let index = 0; index < coordinates.length; index++) {
                            let area = Geo.polygonArea(coordinates[index]);
                            if (area > max_area) {
                                max_area = area;
                                max_area_index = index;
                            }
                        }
                        centroid_feature = getCentroidFeatureForPolygon(coordinates[max_area_index], feature.properties, centroid_properties);
                        features_centroid.push(centroid_feature);
                        break;
                }
            });

            // append centroid features to features array
            Array.prototype.push.apply(features, features_centroid);
        }

        return features;
    }

    // Detect single or multiple layers in returned data
    getLayers (data) {
        if (data.type === 'Feature' || data.type === 'FeatureCollection') {
            return { _default: data };
        }
        else {
            return data;
        }
    }

}

/**
 Mapzen/OSM.US-style GeoJSON vector tiles
 @class GeoJSONTileSource
*/
export class GeoJSONTileSource extends NetworkTileSource {

    constructor(source) {
        super(source);

        // Check for URL tile pattern, if not found, treat as standalone GeoJSON/TopoJSON object
        if (!this.urlHasTilePattern(this.url)) {
            // Check instance type from parent class
            if (this instanceof GeoJSONTileSource) {
                // Replace instance type
                return new GeoJSONSource(source);
            }
            else {
                // Pass back to parent class to instantiate
                return null;
            }
        }
        return this;
    }

    parseSourceData (tile, source, response) {
        let data = JSON.parse(response);
        this.prepareGeoJSON(data, tile, source);
    }

    prepareGeoJSON (data, tile, source) {
        // Apply optional data transform
        if (typeof this.transform === 'function') {
            data = this.transform(data, this.extra_data);
        }

        source.layers = GeoJSONSource.prototype.getLayers(data);

        // A "synthetic" tile that adjusts the tile min anchor to account for tile longitude wrapping
        let anchor = {
            coords: tile.coords,
            min: Geo.metersForTile(Geo.wrapTile(tile.coords, { x: true }))
        };

        DataSource.projectData(source); // mercator projection
        DataSource.scaleData(source, anchor); // re-scale from meters to local tile coords
    }

}

DataSource.register(GeoJSONTileSource, 'GeoJSON');      // prefered shorter name
DataSource.register(GeoJSONTileSource, 'GeoJSONTiles'); // for backwards-compatibility

// Helper function to create centroid point feature from polygon coordinates and provided feature meta-data
function getCentroidFeatureForPolygon (coordinates, properties, newProperties) {
    let centroid = Geo.centroid(coordinates);

    // clone properties and mixix newProperties
    let centroid_properties = {};
    Object.assign(centroid_properties, properties, newProperties);

    return {
        type: "Feature",
        properties: centroid_properties,
        geometry: {
            type: "Point",
            coordinates: centroid
        }
    };
}
<commit_msg>add small buffer on geoson-vt fixes edge case with very small geom values near zero<commit_after>import DataSource, {NetworkSource, NetworkTileSource} from './data_source';
import {decodeMultiPolygon} from './mvt';
import Geo from '../geo';

// For tiling GeoJSON client-side
import geojsonvt from 'geojson-vt';

/**
 GeoJSON standalone (non-tiled) source
 Uses geojson-vt split into tiles client-side
*/

export class GeoJSONSource extends NetworkSource {

    constructor(source) {
        super(source);
        this.tiled = true;
        this.load_data = null;
        this.tile_indexes = {}; // geojson-vt tile indices, by layer name
        this.max_zoom = Math.max(this.max_zoom || 0, 15); // TODO: max zoom < 15 causes artifacts/no-draw at 20, investigate
        this.pad_scale = 0; // we don't want padding on auto-tiled sources
    }

    _load(dest) {
        if (!this.load_data) {
            this.load_data = super._load({ source_data: { layers: {} } }).then(data => {
                let layers = data.source_data.layers;
                for (let layer_name in layers) {
                    this.tile_indexes[layer_name] = geojsonvt(layers[layer_name], {
                        maxZoom: this.max_zoom,  // max zoom to preserve detail on
                        tolerance: 3, // simplification tolerance (higher means simpler)
                        extent: Geo.tile_scale, // tile extent (both width and height)
                        buffer: 0.0001     // tile buffer on each side
                    });
                }

                this.loaded = true;
                return data;
            });
        }

        return this.load_data.then(() => {
            for (let layer_name in this.tile_indexes) {
                dest.source_data.layers[layer_name] = this.getTileFeatures(dest, layer_name);
            }
            return dest;
        });
    }

    getTileFeatures(tile, layer_name) {
        let coords = Geo.wrapTile(tile.coords, { x: true });

        // request a particular tile
        let t = this.tile_indexes[layer_name].getTile(coords.z, coords.x, coords.y);

        // Convert from MVT-style JSON struct to GeoJSON
        let collection;
        if (t && t.features) {
            collection = {
                type: 'FeatureCollection',
                features: []
            };

            for (let feature of t.features) {
                // GeoJSON feature
                let f = {
                    type: 'Feature',
                    geometry: {},
                    properties: feature.tags
                };

                if (feature.type === 1) {
                    f.geometry.coordinates = feature.geometry.map(coord => [coord[0], coord[1]]);
                    f.geometry.type = 'MultiPoint';
                }
                else if (feature.type === 2 || feature.type === 3) {
                    f.geometry.coordinates = feature.geometry.map(ring =>
                        ring.map(coord => [coord[0], coord[1]])
                    );

                    if (feature.type === 2) {
                        f.geometry.type = 'MultiLineString';
                    }
                    else  {
                        f.geometry = decodeMultiPolygon(f.geometry); // un-flatten rings
                    }
                }
                else {
                    continue;
                }

                collection.features.push(f);
            }
        }

        return collection;
    }

    formatUrl (dest) {
        return this.url;
    }

    parseSourceData (tile, source, response) {
        let parsed_response = JSON.parse(response);
        let layers = this.getLayers(parsed_response);
        this.preprocessLayers(layers);
        source.layers = layers;
    }

    preprocessLayers (layers){
        for (let key in layers) {
            let layer = layers[key];
            this.preprocessFeatures(layer.features);
        }
    }

    // Preprocess features. Currently used to add a new "centroid" feature for polygon labeling
    preprocessFeatures (features) {
        // Define centroids for polygons for centroid label placement
        // Avoids redundant label placement for each generated tile at higher zoom levels
        if (this.config.generate_label_centroids){
            let features_centroid = [];
            let centroid_properties = {"label_placement" : "yes"};

            features.forEach(feature => {
                let coordinates, centroid_feature;
                switch (feature.geometry.type) {
                    case 'Polygon':
                        coordinates = feature.geometry.coordinates;
                        centroid_feature = getCentroidFeatureForPolygon(coordinates, feature.properties, centroid_properties);
                        features_centroid.push(centroid_feature);
                        break;
                    case 'MultiPolygon':
                        // Add centroid feature for largest polygon
                        coordinates = feature.geometry.coordinates;
                        let max_area = -Infinity;
                        let max_area_index = 0;
                        for (let index = 0; index < coordinates.length; index++) {
                            let area = Geo.polygonArea(coordinates[index]);
                            if (area > max_area) {
                                max_area = area;
                                max_area_index = index;
                            }
                        }
                        centroid_feature = getCentroidFeatureForPolygon(coordinates[max_area_index], feature.properties, centroid_properties);
                        features_centroid.push(centroid_feature);
                        break;
                }
            });

            // append centroid features to features array
            Array.prototype.push.apply(features, features_centroid);
        }

        return features;
    }

    // Detect single or multiple layers in returned data
    getLayers (data) {
        if (data.type === 'Feature' || data.type === 'FeatureCollection') {
            return { _default: data };
        }
        else {
            return data;
        }
    }

}

/**
 Mapzen/OSM.US-style GeoJSON vector tiles
 @class GeoJSONTileSource
*/
export class GeoJSONTileSource extends NetworkTileSource {

    constructor(source) {
        super(source);

        // Check for URL tile pattern, if not found, treat as standalone GeoJSON/TopoJSON object
        if (!this.urlHasTilePattern(this.url)) {
            // Check instance type from parent class
            if (this instanceof GeoJSONTileSource) {
                // Replace instance type
                return new GeoJSONSource(source);
            }
            else {
                // Pass back to parent class to instantiate
                return null;
            }
        }
        return this;
    }

    parseSourceData (tile, source, response) {
        let data = JSON.parse(response);
        this.prepareGeoJSON(data, tile, source);
    }

    prepareGeoJSON (data, tile, source) {
        // Apply optional data transform
        if (typeof this.transform === 'function') {
            data = this.transform(data, this.extra_data);
        }

        source.layers = GeoJSONSource.prototype.getLayers(data);

        // A "synthetic" tile that adjusts the tile min anchor to account for tile longitude wrapping
        let anchor = {
            coords: tile.coords,
            min: Geo.metersForTile(Geo.wrapTile(tile.coords, { x: true }))
        };

        DataSource.projectData(source); // mercator projection
        DataSource.scaleData(source, anchor); // re-scale from meters to local tile coords
    }

}

DataSource.register(GeoJSONTileSource, 'GeoJSON');      // prefered shorter name
DataSource.register(GeoJSONTileSource, 'GeoJSONTiles'); // for backwards-compatibility

// Helper function to create centroid point feature from polygon coordinates and provided feature meta-data
function getCentroidFeatureForPolygon (coordinates, properties, newProperties) {
    let centroid = Geo.centroid(coordinates);

    // clone properties and mixix newProperties
    let centroid_properties = {};
    Object.assign(centroid_properties, properties, newProperties);

    return {
        type: "Feature",
        properties: centroid_properties,
        geometry: {
            type: "Point",
            coordinates: centroid
        }
    };
}
<|endoftext|>


<commit_before>/**
 This Source Code is licensed under the MIT license. If a copy of the
 MIT-license was not distributed with this file, You can obtain one at:
 http://opensource.org/licenses/mit-license.html.

 @author: Hans van den Akker (mysim1)
 @license MIT
 @copyright Bizboard, 2015

 */
// hello world

import {Injector, annotate, Provide}            from 'di.js';
import {ArvaRouter}                             from './routers/ArvaRouter';
import Engine                                   from 'famous/core/Engine';
import {Context as ArvaContext}                 from 'arva-context/Context';
import Context                                  from 'famous/core/Context';
import AnimationController                      from 'famous-flex/src/AnimationController';

var famouscontext;

function famousContext() {
    if (famouscontext) {
        return famouscontext;
    }
    famouscontext = Engine.createContext();
    return famouscontext;
}
annotate(famousContext, new Provide(Context));

function newAnimationController() {
    famouscontext = famousContext();
    var controller = new AnimationController();

    famouscontext.add(controller);
    return controller;
}
annotate(newAnimationController, new Provide(AnimationController));

export function GetDefaultContext() {
    return ArvaContext.getContext('Default');
}

export function reCreateDefaultContext(dataSource = null) {
    if (dataSource) {
        ArvaContext.setContext('Default', new Injector([ArvaRouter, famousContext, newAnimationController, dataSource]));
    } else {
        ArvaContext.setContext('Default', new Injector([ArvaRouter, famousContext, newAnimationController]));
    }

    return ArvaContext.getContext('Default');
}
<commit_msg>it's now possible to provide a list of injectors within your app instead of only supporting a datasource.<commit_after>/**
 This Source Code is licensed under the MIT license. If a copy of the
 MIT-license was not distributed with this file, You can obtain one at:
 http://opensource.org/licenses/mit-license.html.

 @author: Hans van den Akker (mysim1)
 @license MIT
 @copyright Bizboard, 2015

 */
// hello world

import {Injector, annotate, Provide}            from 'di.js';
import {ArvaRouter}                             from './routers/ArvaRouter';
import Engine                                   from 'famous/core/Engine';
import {Context as ArvaContext}                 from 'arva-context/Context';
import Context                                  from 'famous/core/Context';
import AnimationController                      from 'famous-flex/src/AnimationController';

var famouscontext;

function famousContext() {
    if (famouscontext) {
        return famouscontext;
    }
    famouscontext = Engine.createContext();
    return famouscontext;
}
annotate(famousContext, new Provide(Context));

function newAnimationController() {
    famouscontext = famousContext();
    var controller = new AnimationController();

    famouscontext.add(controller);
    return controller;
}
annotate(newAnimationController, new Provide(AnimationController));

export function GetDefaultContext() {
    return ArvaContext.getContext('Default');
}

export function reCreateDefaultContext() {
    // combine all injectors from context creation and the default injectors.
    let arrayOfInjectors = [ArvaContext, famousContext, newAnimationController].concat(arguments);
    ArvaContext.setContext('Default', new Injector(arrayOfInjectors));
    return ArvaContext.getContext('Default');
}
<|endoftext|>


<commit_before>
var SpeechSynthesis = function(props){
  this.utterance = new window.SpeechSynthesisUtterance();
  this.selected = SpeechSynthesis.getVoice(props.voice);
  this.utterance.voice = this.selected[0] || 'Google UK Female';
  this.utterance.voiceURI = 'Google UK Female';
  this.utterance.text = props.text.replace(/\n/g, '');
  this.utterance.lang = props.lang || 'en-GB';
  this.utterance.pitch = parseFloat(props.pitch, 10) || 1;
  this.utterance.rate = parseFloat(props.rate, 10) || 0.8;
  this.utterance.volume = parseFloat(props.volume, 10) || 1;
};

SpeechSynthesis.supported = function(selected) {
  return window.speechSynthesis;
};

SpeechSynthesis.getVoice = function(selected) {
  return window.speechSynthesis.getVoices().filter(function(voice) {
    return voice.name === selected;
  });
};

SpeechSynthesis.prototype.onend = function(func) {
  this.utterance.onend = func;
};

SpeechSynthesis.prototype.onerror = function(func) {
  this.utterance.onerror = func;
};

SpeechSynthesis.prototype.speak = function() {
  window.speechSynthesis.cancel();
  window.speechSynthesis.speak(this.utterance);
};

SpeechSynthesis.prototype.pause = function() {
  window.speechSynthesis.pause();
};

SpeechSynthesis.prototype.cancel = function() {
  window.speechSynthesis.cancel();
};

SpeechSynthesis.prototype.resume = function() {
  window.speechSynthesis.resume();
};

module.exports = SpeechSynthesis;
<commit_msg>reset voice back to daniel<commit_after>
var SpeechSynthesis = function(props){
  this.utterance = new window.SpeechSynthesisUtterance();
  this.selected = SpeechSynthesis.getVoice(props.voice);
  this.utterance.voice = this.selected[0] || 'Daniel';
  this.utterance.voiceURI = 'Daniel';
  this.utterance.text = props.text.replace(/\n/g, '');
  this.utterance.lang = props.lang || 'en-GB';
  this.utterance.pitch = parseFloat(props.pitch, 10) || 1;
  this.utterance.rate = parseFloat(props.rate, 10) || 0.8;
  this.utterance.volume = parseFloat(props.volume, 10) || 1;
};

SpeechSynthesis.supported = function(selected) {
  return window.speechSynthesis;
};

SpeechSynthesis.getVoice = function(selected) {
  return window.speechSynthesis.getVoices().filter(function(voice) {
    return voice.name === selected;
  });
};

SpeechSynthesis.prototype.onend = function(func) {
  this.utterance.onend = func;
};

SpeechSynthesis.prototype.onerror = function(func) {
  this.utterance.onerror = func;
};

SpeechSynthesis.prototype.speak = function() {
  window.speechSynthesis.cancel();
  window.speechSynthesis.speak(this.utterance);
};

SpeechSynthesis.prototype.pause = function() {
  window.speechSynthesis.pause();
};

SpeechSynthesis.prototype.cancel = function() {
  window.speechSynthesis.cancel();
};

SpeechSynthesis.prototype.resume = function() {
  window.speechSynthesis.resume();
};

module.exports = SpeechSynthesis;
<|endoftext|>


<commit_before>import React from 'react';
import classNames from 'classnames';
import Button from './Button';
import SafeAnchor from './SafeAnchor';

import { prefix } from './utils/bootstrapUtils';

const CARET =  ;

export default class DropdownToggle extends React.Component {
  render() {
    const caret = this.props.noCaret ? null : CARET;

    const classes = {
      [prefix(this.props, 'toggle')]: true
    };

    const Component = this.props.useAnchor ? SafeAnchor : Button;

    return (
      <Component
        {...this.props}
        className={classNames(classes, this.props.className)}
        role="button"
        aria-haspopup
        aria-expanded={this.props.open}>
        {this.props.children || this.props.title}{caret}
      </Component>
    );
  }
}

DropdownToggle.defaultProps = {
  open: false,
  useAnchor: false,
  bsRole: 'toggle'
};

DropdownToggle.propTypes = {
  bsRole: React.PropTypes.string,
  noCaret: React.PropTypes.bool,
  open: React.PropTypes.bool,
  title: React.PropTypes.string,
  useAnchor: React.PropTypes.bool
};

DropdownToggle.isToggle = true;
DropdownToggle.titleProp = 'title';
DropdownToggle.onClickProp = 'onClick';
<commit_msg>Adding defaultProps and extracting props properly<commit_after>import React from 'react';
import classNames from 'classnames';
import Button from './Button';
import SafeAnchor from './SafeAnchor';

import { prefix } from './utils/bootstrapUtils';

const CARET =  ;

export default class DropdownToggle extends React.Component {
  render() {

    const {
      noCaret,
      useAnchor,
      bsClass,
      ...props
    } = this.props;

    const caret = noCaret ? null : CARET;

    const classes = {
      [prefix(this.props, 'toggle')]: true
    };

    const Component = useAnchor ? SafeAnchor : Button;

    return (
      <Component
        {...props}
        className={classNames(classes, this.props.className)}
        role="button"
        aria-haspopup
        aria-expanded={this.props.open}>
        {this.props.children || this.props.title}{caret}
      </Component>
    );
  }
}

DropdownToggle.defaultProps = {
  open: false,
  useAnchor: false,
  bsRole: 'toggle',
  bsClass: 'dropdown'
};

DropdownToggle.propTypes = {
  bsRole: React.PropTypes.string,
  bsClass: React.PropTypes.string,
  noCaret: React.PropTypes.bool,
  open: React.PropTypes.bool,
  title: React.PropTypes.string,
  useAnchor: React.PropTypes.bool
};

DropdownToggle.isToggle = true;
DropdownToggle.titleProp = 'title';
DropdownToggle.onClickProp = 'onClick';
<|endoftext|>