<commit_before>'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _ComponentMenu = require('./ComponentMenu');

var _ComponentMenu2 = _interopRequireDefault(_ComponentMenu);

var _Header = require('./Header');

var _Header2 = _interopRequireDefault(_Header);

var _PreviewBox = require('./PreviewBox');

var _PreviewBox2 = _interopRequireDefault(_PreviewBox);

var _VariablesEditor = require('./VariablesEditor');

var _VariablesEditor2 = _interopRequireDefault(_VariablesEditor);

var _componentScraper = require('../../../../lib/component-scraper');

var _componentScraper2 = _interopRequireDefault(_componentScraper);

var _sass = require('../../../../lib/sass');

var _sass2 = _interopRequireDefault(_sass);

var _theme = require('../../../../lib/theme');

var _theme2 = _interopRequireDefault(_theme);

var _user_config = require('../../../../lib/user_config');

var _user_config2 = _interopRequireDefault(_user_config);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var LexiconCustomizer = function (_Component) {
	_inherits(LexiconCustomizer, _Component);

	function LexiconCustomizer(props) {
		_classCallCheck(this, LexiconCustomizer);

		return _possibleConstructorReturn(this, Object.getPrototypeOf(LexiconCustomizer).call(this, props));
	}

	_createClass(LexiconCustomizer, [{
		key: 'render',
		value: function render() {
			return _react2.default.createElement(
				'div',
				{ className: 'lexicon-customizer' },
				_react2.default.createElement(_Header2.default, null),
				_react2.default.createElement('div', { className: 'lexicon-customizer-content' })
			);
		}
	}]);

	return LexiconCustomizer;
}(_react.Component);

var LexiconCustomizer_OLD = function (_Component2) {
	_inherits(LexiconCustomizer_OLD, _Component2);

	function LexiconCustomizer_OLD(props) {
		_classCallCheck(this, LexiconCustomizer_OLD);

		var _this2 = _possibleConstructorReturn(this, Object.getPrototypeOf(LexiconCustomizer_OLD).call(this, props));

		var customVariables = _componentScraper2.default.getVariablesFromFile(_path2.default.join(process.cwd(), 'lexicon/_custom_variables.scss'));

		var variables = Object.assign({}, props.baseVariables, customVariables);

		var config = userConfig.getConfig();

		_this2.state = {
			baseLexiconTheme: config.baseLexiconTheme || 'lexiconBase',
			componentFile: '_cards.scss',
			componentName: 'cards',
			components: {},
			folderHovering: false,
			styleHREF: _path2.default.join(process.cwd(), 'lexicon/build/lexicon-base.css'),
			theme: config.theme || ''
		};
		return _this2;
	}

	_createClass(LexiconCustomizer_OLD, [{
		key: 'componentDidMount',
		value: function componentDidMount() {
			var componentData = _componentScraper2.default.getLexiconBaseComponents();

			this.setState({
				components: componentData
			});

			this.attachDocumentEventListeners();
		}
	}, {
		key: 'attachDocumentEventListeners',
		value: function attachDocumentEventListeners() {
			var instance = this;

			document.addEventListener('dragleave', function (event) {
				if (event.target.className.indexOf('folder-hovering-mask') != -1) {
					instance.setState({
						folderHovering: false
					});
				}
			}, false);

			document.addEventListener('dragenter', function (event) {
				event.preventDefault();

				instance.setState({
					folderHovering: true
				});

				return false;
			}, false);

			document.addEventListener('drop', function (event) {
				event.preventDefault();

				if (event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files.length) {
					instance.handleFileDrop(event);
				}

				return false;
			}, false);
		}
	}, {
		key: 'render',
		value: function render() {
			var folderHoveringMask = this.state.folderHovering ? _react2.default.createElement(
				'div',
				{ className: 'folder-hovering-mask' },
				_react2.default.createElement(
					'span',
					null,
					'Drop theme to sync'
				)
			) : '';

			return _react2.default.createElement(
				'div',
				{ className: 'lexicon-customizer' },
				_react2.default.createElement(_Header2.default, {
					baseLexiconTheme: this.state.baseLexiconTheme,
					onReset: this.handleReset.bind(this),
					onBaseLexiconThemeChange: this.handleBaseLexiconThemeChange.bind(this),
					onClearTheme: this.handleClearTheme.bind(this),
					theme: this.state.theme
				}),
				_react2.default.createElement(
					'div',
					{ className: 'lexicon-customizer-content' },
					_react2.default.createElement(_ComponentMenu2.default, {
						components: this.state.components,
						onUserClick: this.handleComponentItemClick.bind(this),
						selectedComponent: this.state.componentName
					}),
					_react2.default.createElement(_PreviewBox2.default, {
						baseLexiconTheme: this.state.baseLexiconTheme,
						componentFile: this.state.componentFile,
						componentName: this.state.componentName
					}),
					_react2.default.createElement(_VariablesEditor2.default, {
						componentFile: this.state.componentFile,
						componentName: this.state.componentName,
						theme: this.state.theme,
						variables: this.props.variables
					})
				),
				folderHoveringMask
			);
		}
	}, {
		key: 'handleBaseLexiconThemeChange',
		value: function handleBaseLexiconThemeChange(value) {
			var state = {
				baseLexiconTheme: value
			};

			this.setState(state);

			this._buildLexiconBase();

			userConfig.setConfig(state);
		}
	}, {
		key: 'handleClearTheme',
		value: function handleClearTheme(event) {
			this.setState({
				theme: null
			});
		}
	}, {
		key: 'handleComponentItemClick',
		value: function handleComponentItemClick(event) {
			var currentTarget = event.currentTarget;

			this.setState({
				componentFile: currentTarget.getAttribute('data-file'),
				componentName: currentTarget.getAttribute('data-name')
			});
		}
	}, {
		key: 'handleFileDrop',
		value: function handleFileDrop(event) {
			var file = event.dataTransfer.files[0];

			var state = {
				folderHovering: false
			};

			if (_theme2.default.isTheme(file.path)) {
				userConfig.setConfig('theme', file.path);

				state.theme = file.path;
			}

			this.setState(state);
		}
	}, {
		key: 'handleReset',
		value: function handleReset(event) {
			store.dispatch({
				type: 'RESET_VARIABLES',
				variables: this.props.baseVariables
			});

			this._buildCustomVariablesFile({});
			this._buildLexiconBase();
		}

		// handleUserInput(variableMap, test) {
		// 	var instance = this;

		// 	var mergedVariables = _.assign({}, this.state.variables, variableMap);

		// 	this.setState({
		// 		variables: mergedVariables
		// 	});

		// 	var baseVariables = this.props.baseVariables;

		// 	variableMap = _.reduce(mergedVariables, function(result, item, index) {
		// 		if (item != baseVariables[index]) {
		// 			result[index] = item;
		// 		}

		// 		return result;
		// 	}, {});

		// 	this._buildCustomVariablesFile(variableMap);
		// 	this._buildLexiconBase(variableMap);
		// }

	}, {
		key: '_buildCustomVariablesFile',
		value: function _buildCustomVariablesFile(variableMap) {
			_sass2.default.writeCustomVariablesFile(variableMap, this.state.theme);
		}
	}, {
		key: '_buildLexiconBase',
		value: function _buildLexiconBase() {
			var instance = this;

			var baseLexiconTheme = _lodash2.default.kebabCase(this.state.baseLexiconTheme);

			_sass2.default.renderLexiconBase({
				baseLexiconTheme: baseLexiconTheme
			}, function (err, result) {
				instance.setState({
					styleHREF: _path2.default.join(process.cwd(), 'lexicon/build', baseLexiconTheme + '.css') + '?t=' + Date.now()
				});
			});
		}
	}]);

	return LexiconCustomizer_OLD;
}(_react.Component);

;

exports.default = LexiconCustomizer;<commit_msg>Rebuild<commit_after>'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _ComponentMenu = require('./ComponentMenu');

var _ComponentMenu2 = _interopRequireDefault(_ComponentMenu);

var _Header = require('./Header');

var _Header2 = _interopRequireDefault(_Header);

var _PreviewBox = require('./PreviewBox');

var _PreviewBox2 = _interopRequireDefault(_PreviewBox);

var _VariablesEditor = require('./VariablesEditor');

var _VariablesEditor2 = _interopRequireDefault(_VariablesEditor);

var _componentScraper = require('../../../../lib/component-scraper');

var _componentScraper2 = _interopRequireDefault(_componentScraper);

var _sass = require('../../../../lib/sass');

var _sass2 = _interopRequireDefault(_sass);

var _theme = require('../../../../lib/theme');

var _theme2 = _interopRequireDefault(_theme);

var _user_config = require('../../../../lib/user_config');

var _user_config2 = _interopRequireDefault(_user_config);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var LexiconCustomizer = function (_Component) {
	_inherits(LexiconCustomizer, _Component);

	function LexiconCustomizer() {
		_classCallCheck(this, LexiconCustomizer);

		return _possibleConstructorReturn(this, Object.getPrototypeOf(LexiconCustomizer).apply(this, arguments));
	}

	_createClass(LexiconCustomizer, [{
		key: 'render',
		value: function render() {
			return _react2.default.createElement(
				'div',
				{ className: 'lexicon-customizer' },
				_react2.default.createElement(_Header2.default, null),
				_react2.default.createElement('div', { className: 'lexicon-customizer-content' })
			);
		}
	}]);

	return LexiconCustomizer;
}(_react.Component);

var LexiconCustomizer_OLD = function (_Component2) {
	_inherits(LexiconCustomizer_OLD, _Component2);

	function LexiconCustomizer_OLD(props) {
		_classCallCheck(this, LexiconCustomizer_OLD);

		var _this2 = _possibleConstructorReturn(this, Object.getPrototypeOf(LexiconCustomizer_OLD).call(this, props));

		var customVariables = _componentScraper2.default.getVariablesFromFile(_path2.default.join(process.cwd(), 'lexicon/_custom_variables.scss'));

		var variables = Object.assign({}, props.baseVariables, customVariables);

		var config = userConfig.getConfig();

		_this2.state = {
			baseLexiconTheme: config.baseLexiconTheme || 'lexiconBase',
			componentFile: '_cards.scss',
			componentName: 'cards',
			components: {},
			folderHovering: false,
			styleHREF: _path2.default.join(process.cwd(), 'lexicon/build/lexicon-base.css'),
			theme: config.theme || ''
		};
		return _this2;
	}

	_createClass(LexiconCustomizer_OLD, [{
		key: 'componentDidMount',
		value: function componentDidMount() {
			var componentData = _componentScraper2.default.getLexiconBaseComponents();

			this.setState({
				components: componentData
			});

			this.attachDocumentEventListeners();
		}
	}, {
		key: 'attachDocumentEventListeners',
		value: function attachDocumentEventListeners() {
			var instance = this;

			document.addEventListener('dragleave', function (event) {
				if (event.target.className.indexOf('folder-hovering-mask') != -1) {
					instance.setState({
						folderHovering: false
					});
				}
			}, false);

			document.addEventListener('dragenter', function (event) {
				event.preventDefault();

				instance.setState({
					folderHovering: true
				});

				return false;
			}, false);

			document.addEventListener('drop', function (event) {
				event.preventDefault();

				if (event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files.length) {
					instance.handleFileDrop(event);
				}

				return false;
			}, false);
		}
	}, {
		key: 'render',
		value: function render() {
			var folderHoveringMask = this.state.folderHovering ? _react2.default.createElement(
				'div',
				{ className: 'folder-hovering-mask' },
				_react2.default.createElement(
					'span',
					null,
					'Drop theme to sync'
				)
			) : '';

			return _react2.default.createElement(
				'div',
				{ className: 'lexicon-customizer' },
				_react2.default.createElement(_Header2.default, {
					baseLexiconTheme: this.state.baseLexiconTheme,
					onReset: this.handleReset.bind(this),
					onBaseLexiconThemeChange: this.handleBaseLexiconThemeChange.bind(this),
					onClearTheme: this.handleClearTheme.bind(this),
					theme: this.state.theme
				}),
				_react2.default.createElement(
					'div',
					{ className: 'lexicon-customizer-content' },
					_react2.default.createElement(_ComponentMenu2.default, {
						components: this.state.components,
						onUserClick: this.handleComponentItemClick.bind(this),
						selectedComponent: this.state.componentName
					}),
					_react2.default.createElement(_PreviewBox2.default, {
						baseLexiconTheme: this.state.baseLexiconTheme,
						componentFile: this.state.componentFile,
						componentName: this.state.componentName
					}),
					_react2.default.createElement(_VariablesEditor2.default, {
						componentFile: this.state.componentFile,
						componentName: this.state.componentName,
						theme: this.state.theme,
						variables: this.props.variables
					})
				),
				folderHoveringMask
			);
		}
	}, {
		key: 'handleBaseLexiconThemeChange',
		value: function handleBaseLexiconThemeChange(value) {
			var state = {
				baseLexiconTheme: value
			};

			this.setState(state);

			this._buildLexiconBase();

			userConfig.setConfig(state);
		}
	}, {
		key: 'handleClearTheme',
		value: function handleClearTheme(event) {
			this.setState({
				theme: null
			});
		}
	}, {
		key: 'handleComponentItemClick',
		value: function handleComponentItemClick(event) {
			var currentTarget = event.currentTarget;

			this.setState({
				componentFile: currentTarget.getAttribute('data-file'),
				componentName: currentTarget.getAttribute('data-name')
			});
		}
	}, {
		key: 'handleFileDrop',
		value: function handleFileDrop(event) {
			var file = event.dataTransfer.files[0];

			var state = {
				folderHovering: false
			};

			if (_theme2.default.isTheme(file.path)) {
				userConfig.setConfig('theme', file.path);

				state.theme = file.path;
			}

			this.setState(state);
		}
	}, {
		key: 'handleReset',
		value: function handleReset(event) {
			store.dispatch({
				type: 'RESET_VARIABLES',
				variables: this.props.baseVariables
			});

			this._buildCustomVariablesFile({});
			this._buildLexiconBase();
		}

		// handleUserInput(variableMap, test) {
		// 	var instance = this;

		// 	var mergedVariables = _.assign({}, this.state.variables, variableMap);

		// 	this.setState({
		// 		variables: mergedVariables
		// 	});

		// 	var baseVariables = this.props.baseVariables;

		// 	variableMap = _.reduce(mergedVariables, function(result, item, index) {
		// 		if (item != baseVariables[index]) {
		// 			result[index] = item;
		// 		}

		// 		return result;
		// 	}, {});

		// 	this._buildCustomVariablesFile(variableMap);
		// 	this._buildLexiconBase(variableMap);
		// }

	}, {
		key: '_buildCustomVariablesFile',
		value: function _buildCustomVariablesFile(variableMap) {
			_sass2.default.writeCustomVariablesFile(variableMap, this.state.theme);
		}
	}, {
		key: '_buildLexiconBase',
		value: function _buildLexiconBase() {
			var instance = this;

			var baseLexiconTheme = _lodash2.default.kebabCase(this.state.baseLexiconTheme);

			_sass2.default.renderLexiconBase({
				baseLexiconTheme: baseLexiconTheme
			}, function (err, result) {
				instance.setState({
					styleHREF: _path2.default.join(process.cwd(), 'lexicon/build', baseLexiconTheme + '.css') + '?t=' + Date.now()
				});
			});
		}
	}]);

	return LexiconCustomizer_OLD;
}(_react.Component);

;

exports.default = LexiconCustomizer;<|endoftext|>


<commit_before>
var express = require('../')
  , request = require('./support/http')
  , assert = require('assert')
  , methods = require('methods');

describe('app.router', function(){
  describe('methods supported', function(){
    methods.forEach(function(method){
      it('should include ' + method.toUpperCase(), function(done){
        if (method == 'delete') method = 'del';
        var app = express();
        var calls = [];

        app[method]('/foo', function(req, res){
          if ('head' == method) {
            res.end();
          } else {
            res.end(method);
          }
        });

        request(app)
        [method]('/foo')
        .expect('head' == method ? '' : method, done);
      })
    });
  })

  describe('decode querystring', function(){
    it('should decode correct params', function(done){
      var app = express();

      app.get('/:name', function(req, res, next){
        res.send(req.params.name);
      });

      request(app)
      .get('/foo%2Fbar')
      .expect('foo/bar', done);
    })

    it('should not accept params in malformed paths', function(done) {
      var app = express();

      app.get('/:name', function(req, res, next){
        res.send(req.params.name);
      });

      request(app)
      .get('/%foobar')
      .expect(400, done);
    })

    it('should not decode spaces', function(done) {
      var app = express();

      app.get('/:name', function(req, res, next){
        res.send(req.params.name);
      });

      request(app)
      .get('/foo+bar')
      .expect('foo+bar', done);
    })

    it('should work with unicode', function(done) {
      var app = express();

      app.get('/:name', function(req, res, next){
        res.send(req.params.name);
      });

      request(app)
      .get('/%ce%b1')
      .expect('\u03b1', done);
    })
  })

  it('should be .use()able', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.use(app.router);

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  it('should be auto .use()d on the first app.VERB() call', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  describe('when given a regexp', function(){
    it('should match the pathname only', function(done){
      var app = express();

      app.get(/^\/user\/[0-9]+$/, function(req, res){
        res.end('user');
      });

      request(app)
      .get('/user/12?foo=bar')
      .expect('user', done);
    })

    it('should populate req.params with the captures', function(done){
      var app = express();

      app.get(/^\/user\/([0-9]+)\/(view|edit)?$/, function(req, res){
        var id = req.params.shift()
          , op = req.params.shift();
        res.end(op + 'ing user ' + id);
      });

      request(app)
      .get('/user/10/edit')
      .expect('editing user 10', done);
    })
  })

  describe('case sensitivity', function(){
    it('should be disabled by default', function(done){
      var app = express();

      app.get('/user', function(req, res){
        res.end('tj');
      });

      request(app)
      .get('/USER')
      .expect('tj', done);
    })

    describe('when "case sensitive routing" is enabled', function(){
      it('should match identical casing', function(done){
        var app = express();

        app.enable('case sensitive routing');

        app.get('/uSer', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/uSer')
        .expect('tj', done);
      })

      it('should not match otherwise', function(done){
        var app = express();

        app.enable('case sensitive routing');

        app.get('/uSer', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect(404, done);
      })
    })
  })

  describe('trailing slashes', function(){
    it('should be optional by default', function(done){
      var app = express();

      app.get('/user', function(req, res){
        res.end('tj');
      });

      request(app)
      .get('/user/')
      .expect('tj', done);
    })

    describe('when "strict routing" is enabled', function(){
      it('should match trailing slashes', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user/', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user/')
        .expect('tj', done);
      })

      it('should match no slashes', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect('tj', done);
      })

      it('should fail when omitting the trailing slash', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user/', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect(404, done);
      })

      it('should fail when adding the trailing slash', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user/')
        .expect(404, done);
      })
    })
  })

  it('should allow escaped regexp', function(done){
    var app = express();

    app.get('/user/\\d+', function(req, res){
      res.end('woot');
    });

    request(app)
    .get('/user/10')
    .end(function(err, res){
      res.statusCode.should.equal(200);
      request(app)
      .get('/user/tj')
      .expect(404, done);
    });
  })

  it('should allow literal "."', function(done){
    var app = express();

    app.get('/api/users/:from..:to', function(req, res){
      var from = req.params.from
        , to = req.params.to;

      res.end('users from ' + from + ' to ' + to);
    });

    request(app)
    .get('/api/users/1..50')
    .expect('users from 1 to 50', done);
  })

  describe('*', function(){
    it('should denote a greedy capture group', function(done){
      var app = express();

      app.get('/user/*.json', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/user/tj.json')
      .expect('tj', done);
    })

    it('should work with several', function(done){
      var app = express();

      app.get('/api/*.*', function(req, res){
        var resource = req.params.shift()
          , format = req.params.shift();
        res.end(resource + ' as ' + format);
      });

      request(app)
      .get('/api/users/foo.bar.json')
      .expect('users/foo.bar as json', done);
    })

    it('should work cross-segment', function(done){
      var app = express();

      app.get('/api*', function(req, res){
        res.send(req.params[0]);
      });

      request(app)
      .get('/api')
      .expect('', function(){
        request(app)
        .get('/api/hey')
        .expect('/hey', done);
      });
    })

    it('should allow naming', function(done){
      var app = express();

      app.get('/api/:resource(*)', function(req, res){
        var resource = req.params.resource;
        res.end(resource);
      });

      request(app)
      .get('/api/users/0.json')
      .expect('users/0.json', done);
    })

    it('should not be greedy immediately after param', function(done){
      var app = express();

      app.get('/user/:user*', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/122')
      .expect('122', done);
    })

    it('should eat everything after /', function(done){
      var app = express();

      app.get('/user/:user*', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/122/aaa')
      .expect('122', done);
    })

    it('should span multiple segments', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file/javascripts/jquery.js')
      .expect('javascripts/jquery.js', done);
    })

    it('should be optional', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file/')
      .expect('', done);
    })

    it('should require a preceeding /', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file')
      .expect(404, done);
    })
  })

  describe(':name', function(){
    it('should denote a capture group', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('tj', done);
    })

    it('should match a single segment only', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect(404, done);
    })

    it('should allow several capture groups', function(done){
      var app = express();

      app.get('/user/:user/:op', function(req, res){
        res.end(req.params.op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe(':name?', function(){
    it('should denote an optional capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('viewing tj', done);
    })

    it('should populate the capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe('.:name', function(){
    it('should denote a format', function(done){
      var app = express();

      app.get('/:name.:format', function(req, res){
        res.end(req.params.name + ' as ' + req.params.format);
      });

      request(app)
      .get('/foo.json')
      .expect('foo as json', function(){
        request(app)
        .get('/foo')
        .expect(404, done);
      });
    })
  })

  describe('.:name?', function(){
    it('should denote an optional format', function(done){
      var app = express();

      app.get('/:name.:format?', function(req, res){
        res.end(req.params.name + ' as ' + (req.params.format || 'html'));
      });

      request(app)
      .get('/foo')
      .expect('foo as html', function(){
        request(app)
        .get('/foo.json')
        .expect('foo as json', done);
      });
    })
  })

  describe('when next() is called', function(){
    it('should continue lookup', function(done){
      var app = express()
        , calls = [];

      app.get('/foo/:bar?', function(req, res, next){
        calls.push('/foo/:bar?');
        next();
      });

      app.get('/bar', function(req, res){
        assert(0);
      });

      app.get('/foo', function(req, res, next){
        calls.push('/foo');
        next();
      });

      app.get('/foo', function(req, res, next){
        calls.push('/foo 2');
        res.end('done');
      });

      request(app)
      .get('/foo')
      .expect('done', function(){
        calls.should.eql(['/foo/:bar?', '/foo', '/foo 2']);
        done();
      })
    })
  })

  describe('when next(err) is called', function(){
    it('should break out of app.router', function(done){
      var app = express()
        , calls = [];

      app.get('/foo/:bar?', function(req, res, next){
        calls.push('/foo/:bar?');
        next();
      });

      app.get('/bar', function(req, res){
        assert(0);
      });

      app.get('/foo', function(req, res, next){
        calls.push('/foo');
        next(new Error('fail'));
      });

      app.get('/foo', function(req, res, next){
        assert(0);
      });

      app.use(function(err, req, res, next){
        res.end(err.message);
      })

      request(app)
      .get('/foo')
      .expect('fail', function(){
        calls.should.eql(['/foo/:bar?', '/foo']);
        done();
      })
    })
  })

  it('should allow rewriting of the url', function(done){
    var app = express();

    app.get('/account/edit', function(req, res, next){
      req.user = { id: 12 }; // faux authenticated user
      req.url = '/user/' + req.user.id + '/edit';
      next();
    });

    app.get('/user/:id/edit', function(req, res){
      res.send('editing user ' + req.params.id);
    });

    request(app)
    .get('/account/edit')
    .expect('editing user 12', done);
  })

  it('should be chainable', function(){
    var app = express();
    app.get('/', function(){}).should.equal(app);
  })
})
<commit_msg>tests: add test for app.delete<commit_after>
var express = require('../')
  , request = require('supertest')
  , assert = require('assert')
  , methods = require('methods');

describe('app.router', function(){
  describe('methods supported', function(){
    methods.concat('del').forEach(function(method){
      if (method === 'connect') return;

      it('should include ' + method.toUpperCase(), function(done){
        var app = express();
        var calls = [];

        app[method]('/foo', function(req, res){
          if ('head' == method) {
            res.end();
          } else {
            res.end(method);
          }
        });

        request(app)
        [method]('/foo')
        .expect('head' == method ? '' : method, done);
      })
    });
  })

  describe('decode querystring', function(){
    it('should decode correct params', function(done){
      var app = express();

      app.get('/:name', function(req, res, next){
        res.send(req.params.name);
      });

      request(app)
      .get('/foo%2Fbar')
      .expect('foo/bar', done);
    })

    it('should not accept params in malformed paths', function(done) {
      var app = express();

      app.get('/:name', function(req, res, next){
        res.send(req.params.name);
      });

      request(app)
      .get('/%foobar')
      .expect(400, done);
    })

    it('should not decode spaces', function(done) {
      var app = express();

      app.get('/:name', function(req, res, next){
        res.send(req.params.name);
      });

      request(app)
      .get('/foo+bar')
      .expect('foo+bar', done);
    })

    it('should work with unicode', function(done) {
      var app = express();

      app.get('/:name', function(req, res, next){
        res.send(req.params.name);
      });

      request(app)
      .get('/%ce%b1')
      .expect('\u03b1', done);
    })
  })

  it('should be .use()able', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.use(app.router);

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  it('should be auto .use()d on the first app.VERB() call', function(done){
    var app = express();

    var calls = [];

    app.use(function(req, res, next){
      calls.push('before');
      next();
    });

    app.get('/', function(req, res, next){
      calls.push('GET /')
      next();
    });

    app.use(function(req, res, next){
      calls.push('after');
      res.end();
    });

    request(app)
    .get('/')
    .end(function(res){
      calls.should.eql(['before', 'GET /', 'after'])
      done();
    })
  })

  describe('when given a regexp', function(){
    it('should match the pathname only', function(done){
      var app = express();

      app.get(/^\/user\/[0-9]+$/, function(req, res){
        res.end('user');
      });

      request(app)
      .get('/user/12?foo=bar')
      .expect('user', done);
    })

    it('should populate req.params with the captures', function(done){
      var app = express();

      app.get(/^\/user\/([0-9]+)\/(view|edit)?$/, function(req, res){
        var id = req.params[0]
          , op = req.params[1];
        res.end(op + 'ing user ' + id);
      });

      request(app)
      .get('/user/10/edit')
      .expect('editing user 10', done);
    })
  })

  describe('case sensitivity', function(){
    it('should be disabled by default', function(done){
      var app = express();

      app.get('/user', function(req, res){
        res.end('tj');
      });

      request(app)
      .get('/USER')
      .expect('tj', done);
    })

    describe('when "case sensitive routing" is enabled', function(){
      it('should match identical casing', function(done){
        var app = express();

        app.enable('case sensitive routing');

        app.get('/uSer', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/uSer')
        .expect('tj', done);
      })

      it('should not match otherwise', function(done){
        var app = express();

        app.enable('case sensitive routing');

        app.get('/uSer', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect(404, done);
      })
    })
  })

  describe('trailing slashes', function(){
    it('should be optional by default', function(done){
      var app = express();

      app.get('/user', function(req, res){
        res.end('tj');
      });

      request(app)
      .get('/user/')
      .expect('tj', done);
    })

    describe('when "strict routing" is enabled', function(){
      it('should match trailing slashes', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user/', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user/')
        .expect('tj', done);
      })

      it('should match no slashes', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect('tj', done);
      })

      it('should fail when omitting the trailing slash', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user/', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user')
        .expect(404, done);
      })

      it('should fail when adding the trailing slash', function(done){
        var app = express();

        app.enable('strict routing');

        app.get('/user', function(req, res){
          res.end('tj');
        });

        request(app)
        .get('/user/')
        .expect(404, done);
      })
    })
  })

  it('should allow escaped regexp', function(done){
    var app = express();

    app.get('/user/\\d+', function(req, res){
      res.end('woot');
    });

    request(app)
    .get('/user/10')
    .end(function(err, res){
      res.statusCode.should.equal(200);
      request(app)
      .get('/user/tj')
      .expect(404, done);
    });
  })

  it('should allow literal "."', function(done){
    var app = express();

    app.get('/api/users/:from..:to', function(req, res){
      var from = req.params.from
        , to = req.params.to;

      res.end('users from ' + from + ' to ' + to);
    });

    request(app)
    .get('/api/users/1..50')
    .expect('users from 1 to 50', done);
  })

  describe('*', function(){
    it('should denote a greedy capture group', function(done){
      var app = express();

      app.get('/user/*.json', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/user/tj.json')
      .expect('tj', done);
    })

    it('should work with several', function(done){
      var app = express();

      app.get('/api/*.*', function(req, res){
        var resource = req.params[0]
          , format = req.params[1];
        res.end(resource + ' as ' + format);
      });

      request(app)
      .get('/api/users/foo.bar.json')
      .expect('users/foo.bar as json', done);
    })

    it('should work cross-segment', function(done){
      var app = express();

      app.get('/api*', function(req, res){
        res.send(req.params[0]);
      });

      request(app)
      .get('/api')
      .expect('', function(){
        request(app)
        .get('/api/hey')
        .expect('/hey', done);
      });
    })

    it('should allow naming', function(done){
      var app = express();

      app.get('/api/:resource(*)', function(req, res){
        var resource = req.params.resource;
        res.end(resource);
      });

      request(app)
      .get('/api/users/0.json')
      .expect('users/0.json', done);
    })

    it('should not be greedy immediately after param', function(done){
      var app = express();

      app.get('/user/:user*', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/122')
      .expect('122', done);
    })

    it('should eat everything after /', function(done){
      var app = express();

      app.get('/user/:user*', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/122/aaa')
      .expect('122', done);
    })

    it('should span multiple segments', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file/javascripts/jquery.js')
      .expect('javascripts/jquery.js', done);
    })

    it('should be optional', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file/')
      .expect('', done);
    })

    it('should require a preceeding /', function(done){
      var app = express();

      app.get('/file/*', function(req, res){
        res.end(req.params[0]);
      });

      request(app)
      .get('/file')
      .expect(404, done);
    })
  })

  describe(':name', function(){
    it('should denote a capture group', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('tj', done);
    })

    it('should match a single segment only', function(done){
      var app = express();

      app.get('/user/:user', function(req, res){
        res.end(req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect(404, done);
    })

    it('should allow several capture groups', function(done){
      var app = express();

      app.get('/user/:user/:op', function(req, res){
        res.end(req.params.op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe(':name?', function(){
    it('should denote an optional capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj')
      .expect('viewing tj', done);
    })

    it('should populate the capture group', function(done){
      var app = express();

      app.get('/user/:user/:op?', function(req, res){
        var op = req.params.op || 'view';
        res.end(op + 'ing ' + req.params.user);
      });

      request(app)
      .get('/user/tj/edit')
      .expect('editing tj', done);
    })
  })

  describe('.:name', function(){
    it('should denote a format', function(done){
      var app = express();

      app.get('/:name.:format', function(req, res){
        res.end(req.params.name + ' as ' + req.params.format);
      });

      request(app)
      .get('/foo.json')
      .expect('foo as json', function(){
        request(app)
        .get('/foo')
        .expect(404, done);
      });
    })
  })

  describe('.:name?', function(){
    it('should denote an optional format', function(done){
      var app = express();

      app.get('/:name.:format?', function(req, res){
        res.end(req.params.name + ' as ' + (req.params.format || 'html'));
      });

      request(app)
      .get('/foo')
      .expect('foo as html', function(){
        request(app)
        .get('/foo.json')
        .expect('foo as json', done);
      });
    })
  })

  describe('when next() is called', function(){
    it('should continue lookup', function(done){
      var app = express()
        , calls = [];

      app.get('/foo/:bar?', function(req, res, next){
        calls.push('/foo/:bar?');
        next();
      });

      app.get('/bar', function(req, res){
        assert(0);
      });

      app.get('/foo', function(req, res, next){
        calls.push('/foo');
        next();
      });

      app.get('/foo', function(req, res, next){
        calls.push('/foo 2');
        res.end('done');
      });

      request(app)
      .get('/foo')
      .expect('done', function(){
        calls.should.eql(['/foo/:bar?', '/foo', '/foo 2']);
        done();
      })
    })
  })

  describe('when next(err) is called', function(){
    it('should break out of app.router', function(done){
      var app = express()
        , calls = [];

      app.get('/foo/:bar?', function(req, res, next){
        calls.push('/foo/:bar?');
        next();
      });

      app.get('/bar', function(req, res){
        assert(0);
      });

      app.get('/foo', function(req, res, next){
        calls.push('/foo');
        next(new Error('fail'));
      });

      app.get('/foo', function(req, res, next){
        assert(0);
      });

      app.use(function(err, req, res, next){
        res.end(err.message);
      })

      request(app)
      .get('/foo')
      .expect('fail', function(){
        calls.should.eql(['/foo/:bar?', '/foo']);
        done();
      })
    })
  })

  it('should allow rewriting of the url', function(done){
    var app = express();

    app.get('/account/edit', function(req, res, next){
      req.user = { id: 12 }; // faux authenticated user
      req.url = '/user/' + req.user.id + '/edit';
      next();
    });

    app.get('/user/:id/edit', function(req, res){
      res.send('editing user ' + req.params.id);
    });

    request(app)
    .get('/account/edit')
    .expect('editing user 12', done);
  })

  it('should be chainable', function(){
    var app = express();
    app.get('/', function(){}).should.equal(app);
  })
})
<|endoftext|>


<commit_before>QUnit.test( 'background', function( assert ) {
  'use strict';

  var done = assert.async( 9 );

  var imgLoad0 = imagesLoaded( '#background .tulip', { background: true }, function() {
    assert.ok( true, 'callback triggered on .orange-tree');
    assert.equal( imgLoad0.images.length, 1, '1 image on .images' );
    done();
  });

  var imgLoad1 = imagesLoaded( '#background .thunder-cloud', { background: true }, function() {
    assert.ok( true, 'callback triggered on .thunder-cloud');
    assert.equal( imgLoad1.images.length, 1, '1 image on .images' );
    done();
  });

  // multiple backgrounds
  var imgLoad2 = imagesLoaded( '#background .multi', { background: true }, function() {
    assert.ok( true, 'callback triggered on .multi');
    assert.equal( imgLoad2.images.length, 3, '3 images on .images' );
    done();
  });

  // multiple elements
  var imgLoad3 = imagesLoaded( '#background .bg-box', { background: true }, function() {
    assert.ok( true, 'callback triggered on .bg-box');
    assert.equal( imgLoad3.images.length, 5, '5 images on .bg-box' );
    done();
  });

  imgLoad3.on('progress', function( instance, image, element ) {
    assert.ok( true, 'progress on .bg-box; ' + image.img.src );
    assert.equal( image.isLoaded, true, 'image.isLoaded == true' );
    done();
  });

});<commit_msg>check for multiple BG support for IE8<commit_after>QUnit.test( 'background', function( assert ) {
  'use strict';

  // from Modernizr
  var supportsMultiBGs = ( function() {
    var style = document.createElement('a').style;
    style.cssText = 'background:url(https://),url(https://),red url(https://)';
    return (/(url\s*\(.*?){3}/).test(style.background);
  })();

  var multiBGCount = supportsMultiBGs ? 3 : 0;
  var done = assert.async( 6 + multiBGCount );

  var imgLoad0 = imagesLoaded( '#background .tulip', { background: true }, function() {
    assert.ok( true, 'callback triggered on .orange-tree');
    assert.equal( imgLoad0.images.length, 1, '1 image on .images' );
    done();
  });

  var imgLoad1 = imagesLoaded( '#background .thunder-cloud', { background: true }, function() {
    assert.ok( true, 'callback triggered on .thunder-cloud');
    assert.equal( imgLoad1.images.length, 1, '1 image on .images' );
    done();
  });

  // multiple backgrounds
  var imgLoad2 = imagesLoaded( '#background .multi', { background: true }, function() {
    assert.ok( true, 'callback triggered on .multi');
    assert.equal( imgLoad2.images.length, multiBGCount, 'correct multiple BG count on .images' );
    done();
  });

  // multiple elements
  var imgLoad3 = imagesLoaded( '#background .bg-box', { background: true }, function() {
    assert.ok( true, 'callback triggered on .bg-box');
    var count = 2 + multiBGCount;
    assert.equal( imgLoad3.images.length, count, count + ' images on .bg-box' );
    done();
  });

  imgLoad3.on('progress', function( instance, image, element ) {
    assert.ok( true, 'progress on .bg-box; ' + image.img.src );
    assert.equal( image.isLoaded, true, 'image.isLoaded == true' );
    assert.equal( element.nodeName, 'DIV', 'element is DIV, not IMG' );
    done();
  });

});
<|endoftext|>


<commit_before>angular.module('n3-charts.linechart', [])

.factory('n3utils', function() {
  return {
    getDefaultMargins: function() {
      return {top: 20, right: 50, bottom: 30, left: 50};
    },

    clean: function(element) {
      d3.select(element).select('svg').remove();
    },

    bootstrap: function(element, dimensions) {
      d3.select(element).classed('chart', true);

      var width = dimensions.width;
      var height = dimensions.height;

      var svg = d3.select(element).append('svg')
        .attr('width', width)
        .attr('height', height)
        .append('g')
          .attr('transform', 'translate(' + dimensions.left +
            ',' + dimensions.top + ')'
          );

      return svg;
    },

    getTooltipTextWidth: function(text) {
      return Math.max(25, text.length*6.7);
    },

    getWidestOrdinate: function(data, series) {
      var widest = '';

      data.forEach(function(row) {
        series.forEach(function(series) {
          if (('' + row[series.y]).length > ('' + widest).length) {
            widest = row[series.y];
          }
        })
      })

      return widest;
    },

    createAxes: function(svg, dimensions, drawY2Axis) {
      var width = dimensions.width;
      var height = dimensions.height;

      width = width - dimensions.left - dimensions.right;
      height = height - dimensions.top - dimensions.bottom;

      var x = d3.scale.linear().rangeRound([0, width]);
      var y = d3.scale.linear().rangeRound([height, 0]);
      var y2 = d3.scale.linear().rangeRound([height, 0]);

      var xAxis = d3.svg.axis().scale(x).orient('bottom');
      var yAxis = d3.svg.axis().scale(y).orient('left');
      var y2Axis = d3.svg.axis().scale(y2).orient('right');

      var that = this;

      return {
        xScale: x,
        yScale: y,
        y2Scale: y2,
        xAxis: xAxis,
        yAxis: yAxis,
        y2Axis: y2Axis,

        andAddThemIf: function(expression) {
          if (!!expression) {
            svg.append('g')
              .attr('class', 'x axis')
              .attr('transform', 'translate(0,' + height + ')')
              .call(xAxis);

            svg.append('g')
              .attr('class', 'y axis')
              .call(yAxis);

            if (drawY2Axis) {
              svg.append('g')
                .attr('class', 'y2 axis')
                .attr('transform', 'translate(' + width + ', 0)')
                .call(y2Axis);
            }

            that.addTooltips(svg, width, height, drawY2Axis);
          }

          return {
            xScale: x, yScale: y, y2Scale: y2,
            xAxis: xAxis, yAxis: yAxis, y2Axis: y2Axis
          }
        }
      }
    },

    addTooltips: function (svg, width, height, drawY2Axis) {
      var w = 24;
      var h = 18;
      var p = 5;

      var xTooltip = svg.append('g')
        .attr({
          'id': 'xTooltip',
          'opacity': 0
        });

      xTooltip.append('path')
        .attr({
          'transform': 'translate(0,' + (height + 1) + ')'
        });

      xTooltip.append('text')
        .style({
          'text-anchor': 'middle'
        })
        .attr({
          'width': w,
          'height': h,
          'font-family': 'monospace',
          'font-size': 10,
          'transform': 'translate(0,' + (height + 19) + ')',
          'fill': 'white',
          'text-rendering': 'geometric-precision'
        });

      var yTooltip = svg.append('g')
        .attr({
          'id': 'yTooltip',
          'opacity': 0
        });

      yTooltip.append('path');
      yTooltip.append('text')
        .attr({
          'width': h,
          'height': w,
          'font-family': 'monospace',
          'font-size': 10,
          'fill': 'white',
          'text-rendering': 'geometric-precision'
        });

      if (drawY2Axis) {
        var y2Tooltip = svg.append('g')
          .attr({
            'id': 'y2Tooltip',
            'opacity': 0,
            'transform': 'translate(' + width + ',0)'
          });

        y2Tooltip.append('path');

        y2Tooltip.append('text')
          .attr({
            'width': h,
            'height': w,
            'font-family': 'monospace',
            'font-size': 10,
            'fill': 'white',
            'text-rendering': 'geometric-precision'
          })
      }
    },

    createContent: function(svg) {
      svg.append('g')
        .attr('class', 'content');
    },

    drawLines: function(svg, scales, data, interpolateMode) {
      var drawers = {
        y: this.createLeftLineDrawer(scales, interpolateMode),
        y2: this.createRightLineDrawer(scales, interpolateMode)
      };

      svg.select('.content').selectAll('.lineGroup')
        .data(data.filter(function(s) {return s.type === 'line'  || s.type === 'area'}))
        .enter().append('g')
          .style('stroke', function(serie) {return serie.color;})
          .attr('class', 'lineGroup')
          .append('path')
            .attr('class', 'line')
            .attr('d', function(d) {return drawers[d.axis](d.values);})
            .style({
              'fill': 'none',
              'stroke-width': '1px'
            });

      return this;
    },

    createLeftLineDrawer: function(scales, interpolateMode) {
      return d3.svg.line()
        .x(function(d) {return scales.xScale(d.x);})
        .y(function(d) {return scales.yScale(d.value);})
        .interpolate(interpolateMode);
    },

    createRightLineDrawer: function(scales, interpolateMode) {
      return d3.svg.line()
        .x(function(d) {return scales.xScale(d.x);})
        .y(function(d) {return scales.y2Scale(d.value);})
        .interpolate(interpolateMode);
    },

    drawArea: function(svg, scales, data, interpolateMode){
      var drawers = {
        y: this.createLeftAreaDrawer(scales, interpolateMode),
        y2: this.createRightAreaDrawer(scales, interpolateMode)
      };

      svg.select('.content').selectAll('.areaGroup')
        .data(data.filter(function(series) {return series.type === 'area'}))
        .enter().append('g')
          .style('fill', function(serie) {return serie.color;})
          .attr('class','areaGroup')
          .append('path')
            .style('opacity', '0.3')
            .attr('class', 'area')
            .attr('d',  function(d) {return drawers[d.axis](d.values);});

      return this;
    },

    createLeftAreaDrawer: function(scales, interpolateMode) {
      return d3.svg.area()
        .x(function(d) {return scales.xScale(d.x);})
        .y0(function(d) {return scales.yScale(0);})
        .y1(function(d) {return scales.yScale(d.value);})
        .interpolate(interpolateMode);
    },

    createRightAreaDrawer: function(scales, interpolateMode) {
      return d3.svg.area()
        .x(function(d) {return scales.xScale(d.x);})
        .y0(function(d) {return scales.y2Scale(0);})
        .y1(function(d) {return scales.y2Scale(d.value);})
        .interpolate(interpolateMode);
    },

    getBestColumnWidth: function(dimensions, data) {
      if (!data || data.length === 0) {
        return 10;
      }

      var n = data[0].values.length + 2; // +2 because abscissas will be extended
                                         // to one more row at each end
      var s = data.length;
      var oP = 3; // space between two rows
      var avWidth = dimensions.width - dimensions.left - dimensions.right;

      return (avWidth - (n - 1)*oP) / (n*s);
    },

    drawColumns: function(svg, axes, data, columnWidth) {
      data = data.filter(function(s) {return s.type === 'column';});

      var x1 = d3.scale.ordinal()
        .domain(data.map(function(s) {return s.name;}))
        .rangeRoundBands([0, data.length * columnWidth], 0.05);

      var that = this;

      var colGroup = svg.select('.content').selectAll('.columnGroup')
        .data(data)
        .enter().append("g")
          .attr("class", "columnGroup")
          .style("fill", function(s) {return s.color;})
          .style("fill-opacity", .8)
          .attr("transform", function(series) {
            return "translate(" + (
              x1(series.name) - data.length*columnWidth/2
            ) + ",0)";
          })
          .on('mouseover', function(series) {
            var target = d3.select(d3.event.target);

            that.onMouseOver(svg, {
              series: series,
              x: target.attr('x'),
              y: axes[series.axis + 'Scale'](target.datum().value),
              datum: target.datum()
            });
          })
          .on('mouseout', function(d) {
            d3.select(d3.event.target).attr('r', 2);
            that.onMouseOut(svg);
          });

      colGroup.selectAll("rect")
        .data(function(d) {return d.values;})
        .enter().append("rect")
          .attr("width", columnWidth)
          .attr("x", function(d) {return axes.xScale(d.x);})

          .attr("y", function(d) {
            return axes[d.axis + 'Scale'](Math.max(0, d.value));
          })

          .attr("height", function(d) {
            return Math.abs(axes[d.axis + 'Scale'](d.value) -
              axes[d.axis + 'Scale'](0));
          });

      return this;
    },

    drawDots: function(svg, axes, data) {
      var that = this;

      svg.select('.content').selectAll('.dotGroup')
        .data(data.filter(function(s) {return s.type === 'line' || s.type === 'area'}))
        .enter().append('g')
          .attr('class', 'dotGroup')
          .attr('fill', function(s) {return s.color;})
          .on('mouseover', function(series) {
            var target = d3.select(d3.event.target);
            target.attr('r', 4);

            that.onMouseOver(svg, {
              series: series,
              x: target.attr('cx'),
              y: target.attr('cy'),
              datum: target.datum()
            });
          })
          .on('mouseout', function(d) {
            d3.select(d3.event.target).attr('r', 2);
            that.onMouseOut(svg);
          })
          .selectAll('.dot').data(function(d) {return d.values;})
            .enter().append('circle')
            .attr({
              'class': 'dot',
              'r': 2,
              'cx': function(d) {return axes.xScale(d.x)},
              'cy': function(d) {return axes[d.axis + 'Scale'](d.value)}
            })
            .style({
              'stroke': 'white',
              'stroke-width': '2px'
            });

      return this;
    },

    onMouseOver: function(svg, target) {
      this.updateXTooltip(svg, target);

      if (target.series.axis === 'y2') {
        this.updateY2Tooltip(svg, target);
      } else {
        this.updateYTooltip(svg, target);
      }
    },

    onMouseOut: function(svg) {
      this.hideTooltips(svg);
    },

    updateXTooltip: function(svg, target) {
      var xTooltip = svg.select("#xTooltip")
        .transition()
        .attr({
          'opacity': 1.0,
          'transform': 'translate(' + target.x + ',0)'
        })

      var textX = '' + target.datum.x;
      xTooltip.select('text').text(textX)
      xTooltip.select('path')
        .attr('fill', target.series.color)
        .attr('d', this.getXTooltipPath(textX));
    },

    getXTooltipPath: function(text) {
      var w = this.getTooltipTextWidth(text);
      var h = 18;
      var p = 5; // Size of the 'arrow' that points towards the axis

      return 'm-' + w/2 + ' ' + p + ' ' +
        'l0 ' + h + ' ' +
        'l' + w + ' 0 ' +
        'l0 ' + '-' + h +
        'l-' + (w/2 - p) + ' 0 ' +
        'l-' + p + ' -' + h/4 + ' ' +
        'l-' + p + ' ' + h/4 + ' ' +
        'l-' + (w/2 - p) + ' 0z';
    },

    updateYTooltip: function(svg, target) {
      var yTooltip = svg.select("#yTooltip")
        .transition()
        .attr({
          'opacity': 1.0,
          'transform': 'translate(0, ' + target.y + ')'
        })

      var textY = '' + target.datum.value;
      var yTooltipText = yTooltip.select('text').text(textY);
      yTooltipText.attr(
        'transform',
        'translate(-' + (this.getTooltipTextWidth(textY) + 3) + ',3)'
      );
      yTooltip.select('path')
        .attr('fill', target.series.color)
        .attr('d', this.getYTooltipPath(textY));
    },

    getYTooltipPath: function(text) {
      var w = this.getTooltipTextWidth(text);
      var h = 18;
      var p = 5; // Size of the 'arrow' that points towards the axis

      return 'm0 0' +
        'l-' + p + ' -' + p + ' ' +
        'l0 -' + (h/2 - p) + ' ' +
        'l-' + w + ' 0 ' +
        'l0 ' + h + ' ' +
        'l' + w + ' 0 ' +
        'l0 -' + (h/2 - p) +
        'l-' + p + ' ' + p + 'z';
    },

    updateY2Tooltip: function(svg, target) {
      var y2Tooltip = svg.select("#y2Tooltip")
        .transition()
        .attr({
          'opacity': 1.0
        })

      var textY = '' + target.datum.value;
      var y2TooltipText = y2Tooltip.select('text').text(textY);
      y2TooltipText.attr(
        'transform',
        'translate(5, ' + (parseFloat(target.y) + 3) + ')'
      );
      y2Tooltip.select('path')
        .attr({
          'fill': target.series.color,
          'd': this.getY2TooltipPath(textY),
          'transform': 'translate(0, ' + target.y + ')'
        })
    },

    getY2TooltipPath: function(text) {
      var w = this.getTooltipTextWidth(text);
      var h = 18;
      var p = 5; // Size of the 'arrow' that points towards the axis

      return 'm0 0' +
        'l' + p + ' ' + p + ' ' +
        'l0 ' + (h/2 - p) + ' ' +
        'l' + w + ' 0 ' +
        'l0 -' + h + ' ' +
        'l-' + w + ' 0 ' +
        'l0 ' + (h/2 - p) + ' ' +
        'l-' + p + ' ' + p + 'z'
    },

    hideTooltips: function(svg) {
      svg.select("#xTooltip")
        .transition()
        .attr({
          'opacity': .0
        })

      svg.select("#yTooltip")
        .transition()
        .attr({
          'opacity': .0
        })

      svg.select("#y2Tooltip")
        .transition()
        .attr({
          'opacity': .0
        })
    },

    getDataPerSeries: function(data, options) {
      var series = options ? options.series : null;

      if (!series || !series.length || !data || !data.length) {
        return [];
      }

      var lineData = [];

      series.forEach(function(s) {
        var seriesData = {
          name: s.y,
          values: [],
          color: s.color,
          axis: s.axis || 'y',
          type: s.type || 'line'
        };

        data.forEach(function(row) {
          seriesData.values.push({
            x: row.x,
            value: row[s.y],
            axis: s.axis || 'y'
          })
        });

        lineData.push(seriesData);
      });

      return lineData;
    },

    setScalesDomain: function(scales, data, series, svg) {
      this.setXScale(scales.xScale, data, series);

      var ySeries = series.filter(function(s) {return s.axis !== 'y2'});
      var y2Series = series.filter(function(s) {return s.axis === 'y2'});

      scales.yScale.domain(this.yExtent(ySeries, data)).nice();
      scales.y2Scale.domain(this.yExtent(y2Series, data)).nice();

      svg.selectAll('.x.axis').call(scales.xAxis)
      svg.selectAll('.y.axis').call(scales.yAxis)
      svg.selectAll('.y2.axis').call(scales.y2Axis)
    },

    yExtent: function(series, data) {
      var minY = Number.POSITIVE_INFINITY;
      var maxY = Number.NEGATIVE_INFINITY;

      series.forEach(function(s) {
        minY = Math.min(minY, d3.min(data, function(d) {return d[s.y]}));
        maxY = Math.max(maxY, d3.max(data, function(d) {return d[s.y]}));
      });

      return [minY, maxY];
    },

    setXScale: function(xScale, data, series) {
      xScale.domain(d3.extent(data, function(d) {return d.x;}));

      if (series.filter(function(s) {return s.type === 'column'}).length) {
        this.adjustXScaleForColumns(xScale, data);
      }
    },

    adjustXScaleForColumns: function(xScale, data) {
      var step = this.getAverageStep(data, 'x');
      var d = xScale.domain();

      xScale.domain([d[0] - step, d[1] + step]);
    },

    getAverageStep: function(data, field) {
      var sum = 0;
      var n = data.length - 1;

      for (var i = 0; i<n; i++) {
        sum += data[i + 1][field] - data[i][field];
      }

      return sum/n;
    },

    haveSecondYAxis: function(series) {
      var doesHave = false;

      angular.forEach(series, function(s) {
        doesHave = doesHave || s.axis === 'y2';
      });

      return doesHave;
    },

    resetMargins: function(dimensions) {
      var defaults = this.getDefaultMargins();

      dimensions.left = defaults.left;
      dimensions.right = defaults.right;
      dimensions.top = defaults.top;
      dimensions.bottom = defaults.bottom;
    },

    adjustMargins: function(dimensions, options, data) {
      this.resetMargins(dimensions);

      if (!data || data.length === 0) {
        return;
      }

      var series = (options && options.series) ? options.series : [];

      var leftSeries = series.filter(function(s) {return s.axis !== 'y2'});
      var leftWidest = this.getWidestOrdinate(data, leftSeries);
      dimensions.left = this.getTooltipTextWidth('' + leftWidest) + 20;

      var rightSeries = series.filter(function(s) {return s.axis === 'y2'});
      if (rightSeries.length === 0) {
        return;
      }
      var rightWidest = this.getWidestOrdinate(data, rightSeries);
      dimensions.right = this.getTooltipTextWidth('' + rightWidest) + 20;
    },

    adjustMarginsForThumbnail: function(dimensions, options, data) {
      dimensions.left = 0;
      dimensions.right = 0;
      dimensions.top = 0;
      dimensions.bottom = 0;
    }
  }
})

.directive('linechart', function(n3utils, $window) {
  var link  = function(scope, element, attrs, ctrl) {
    var dim = n3utils.getDefaultMargins();

    scope.updateDimensions = function(dimensions) {
      dimensions.width = element[0].parentElement.offsetWidth || 900;
      dimensions.height = element[0].parentElement.offsetHeight || 500;
    }

    scope.update = function() {
      scope.updateDimensions(dim);
      scope.redraw(dim);
    };

    scope.redraw = function(dimensions) {
      var data = scope.data;
      var options = scope.options;
      var series = options && options.series ? options.series : [];

      var dataPerSeries = n3utils.getDataPerSeries(data, options);

      if (attrs.mode === 'thumbnail') {
        n3utils.adjustMarginsForThumbnail(dimensions, options, data);
      } else {
        n3utils.adjustMargins(dimensions, options, data);
      }

      n3utils.clean(element[0]);

      var haveSecondYAxis = n3utils.haveSecondYAxis(series);

      var svg = n3utils.bootstrap(element[0], dimensions);
      var axes = n3utils
        .createAxes(svg, dimensions, haveSecondYAxis)
        .andAddThemIf(attrs.mode !== 'thumbnail');

      n3utils.createContent(svg);

      var lineMode = options ? options.lineMode : 'linear';

      if (dataPerSeries.length > 0) {
        n3utils.setScalesDomain(axes, data, options.series, svg);

        var columnWidth = n3utils.getBestColumnWidth(dimensions, dataPerSeries);

        n3utils
          .drawArea(svg, axes, dataPerSeries, lineMode)
          .drawColumns(svg, axes, dataPerSeries, columnWidth)
          .drawLines(svg, axes, dataPerSeries, lineMode)
          .drawDots(svg, axes, dataPerSeries)
        ;
      }
    }

    $window.onresize = function() {
      scope.update();
    }

    scope.$watch('data', scope.update);
    scope.$watch('options', scope.update, true);
  };

  return {
    replace: true,
    restrict: 'E',
    scope: {data: '=', options: '='},
    template: '<div></div>',
    link: link
  };
});<commit_msg>Remove wrong file<commit_after><|endoftext|>


<commit_before>!function(a){"use strict";var b=function(c){this.conf=a.extend({name:"database",indexedKeys:[],uniqueKey:"id",driver:new b.drivers.StorageDriver({name:c.name,storage:a.localStorage})},c||{}),this.initialize()};b.prototype.initialize=function(){this.data=this.load()||[],this.id=0,this.data.length>0&&(this.data=this.data.map(function(a){return parseInt(a,10)}),this.id=Math.max.apply(Math,this.data))},b.prototype.find=function(a){if("undefined"==typeof a)return this.findAll();var b,d=this.getKeys(a),e=[];for(var f in d[0])e.push(this.conf.driver.getItem(f+":"+d[0][f])||!1);return b=0===e.length?this.data:1===e.length?e[0]:c.apply(this,e),this.filter(this.select(b),d[1])},b.prototype.findAll=function(){return this.select(this.data)},b.prototype.getKeys=function(a){var b,c=[];c[0]={},c[1]={};for(var d in a)b=-1!==this.conf.indexedKeys.indexOf(d)?0:1,c[b][d]=a[d];return c},b.prototype.select=function(a){var b=[];a=1===a.length?[a]:a;for(var c=0,d=a.length;d>c;c++)b.push(this.conf.driver.getItem(a[c]));return b},b.prototype.filter=function(a,b){for(var c,d,e=[],f=0,g=a.length;g>f;f++){d=a[f],c=!0;for(var h in b)if(d[h]!==b[h]){c=!1;break}c&&e.push(d)}return e},b.prototype.insert=function(a){if("[object Object]"!==Object.prototype.toString.call(a))throw"Can't insert "+a+". Please insert object.";return this.id++,-1===this.data.indexOf(this.id)?(a[this.conf.uniqueKey]=this.id,this.data.push(this.id),this.conf.driver.setItem(this.id,a),this.conf.driver.setItem("__data",this.data.join(",")),this.buildIndex(a),this.id):void 0},b.prototype.update=function(a,b){return-1!==this.data.indexOf(a)?(this.destroyIndex(a),b[this.conf.uniqueKey]=a,this.conf.driver.setItem(a,b),this.buildIndex(b),b):void 0},b.prototype.delete=function(a){if("[object Object]"===Object.prototype.toString.call(a))this.findAndDelete(a);else if(-1!==this.data.indexOf(a))return this.data.splice(this.data.indexOf(a),1),this.destroyIndex(a),this.conf.driver.removeItem(a),this.conf.driver.setItem("__data",this.data.join(",")),-1===this.data.indexOf(a)},b.prototype.findAndDelete=function(a){for(var b,c=this.find(a),d=this.data.length,e=0;e<c.length;e++)b=c[e][this.conf.uniqueKey],-1!==this.data.indexOf(b)&&(this.data.splice(this.data.indexOf(b),1),this.destroyIndex(b),this.conf.driver.removeItem(b),this.conf.driver.setItem("__data",this.data.join(",")));return this.data.length<d},b.prototype.count=function(){return this.data.length},b.prototype.drop=function(){for(var a=0,b=this.data.length;b>a;a++)this.delete(this.data[a]);return this.conf.driver.removeItem("__data"),this.data.length=0,0===this.data.length},b.prototype.load=function(){return this.conf.driver.getItem("__data")?this.conf.driver.getItem("__data").split(","):null},b.prototype.buildIndex=function(a){var b,c,d;for(var e in a)-1!==this.conf.indexedKeys.indexOf(e)&&(d=[a[this.conf.uniqueKey]],b=e+":"+a[e],c=this.conf.driver.getItem(b),null!==c&&(c.push(a[this.conf.uniqueKey]),d=c),this.conf.driver.setItem(b,d))},b.prototype.destroyIndex=function(a){var b,c,d=this.conf.driver.getItem(a);if(null!==d)for(var e in d)-1!==this.conf.indexedKeys.indexOf(e)&&(b=e+":"+d[e],c=this.conf.driver.getItem(b),null!==c&&(c.splice(c.indexOf(a),1),0===c.length?this.conf.driver.removeItem(b):this.conf.driver.setItem(b,c)))};var c=function(){var a,b,c,d,e,f,g=[],h={};for(f=arguments.length-1,c=arguments[0].length,b=0,a=0;f>=a;a++)d=arguments[a].length,c>d&&(b=a,c=d);for(a=0;f>=a;a++){d=a===b?0:a||b,e=arguments[d].length;for(var i=0;e>i;i++){var j=arguments[d][i];h[j]===a-1?a===f?(g.push(j),h[j]=0):h[j]=a:0===a&&(h[j]=0)}}return g};a.Database=b,a.Database.drivers={}}(window),function(a){"use strict";var b=function(b){if(this.conf=a.extend({name:"",storage:a.localStorage},b||{}),"function"!=typeof b.storage.getItem||"function"!=typeof b.storage.removeItem||"function"!=typeof b.storage.setItem)throw"Given Storage doesn't have methods `getItem`, `setItem` and `removeItem`."};b.prototype.setItem=function(a,b){return this.conf.storage.setItem(this.conf.name+":"+a,JSON.stringify(b))},b.prototype.getItem=function(a){return JSON.parse(this.conf.storage.getItem(this.conf.name+":"+a))},b.prototype.removeItem=function(a){return this.conf.storage.removeItem(this.conf.name+":"+a)},a.Database&&(a.Database.drivers.StorageDriver=b)}(window),function(a){"use strict";a.extend=function(a,b){if(a=a||{},arguments.length>2)for(var c=1;c<arguments.length;c++)window.extend(a,arguments[c]);else for(var d in b)a[d]=b[d];return a}}(window);<commit_msg>Removed old file<commit_after><|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var {
  StyleSheet,
  View,
  Text,
  ScrollView,
} = React;

var Carousel = React.createClass({

  getDefaultProps() {
    return {
      hideIndicators: true,
      indicatorColor: '#000000',
      inactiveIndicatorColor: '#999999',
      indicatorAtBottom: true,
      width: 375
    };
  },

  getInitialState() {
    return {
      activePage: 0
    };
  },

  render() {

    return (
      <View style={{ flex: 1 }}>
        <ScrollView ref="scrollview"
          contentContainerStyle={styles.container}
          automaticallyAdjustContentInsets={false}
          horizontal={true}
          pagingEnabled={true}
          showsHorizontalScrollIndicator={false}
          bounces={false}
          onMomentumScrollEnd={this.onAnimationEnd}
        >
          {this.props.children}
        </ScrollView>
        {this.renderPageIndicator()}
      </View>
    );
  },
  indicatorPressed(ind){
    this.setState({
      activePage:ind
    });

    this.refs.scrollview.scrollTo(0,ind*this.props.width);
  },

  renderPageIndicator() {
    if (this.props.hideIndicators === true) {
      return null;
    }

    var indicators = [],
        indicatorStyle = this.props.indicatorAtBottom ? styles.pageIndicatorBottom : styles.pageIndicatorTop,
        style, position;

    position = {
      width: this.props.children.length * 15,
    };
    position.left = (this.props.width - position.width) / 2;

    for (var i=0; i< this.props.children.length; i++) {
      style = i === this.state.activePage ? { color: this.props.indicatorColor } : { color: this.props.inactiveIndicatorColor };
      indicators.push(<Text style={style} key={i} onPress={this.indicatorPressed.bind(this,i)}>•</Text>);
    }

    return (
      <View style={[styles.pageIndicator, position, indicatorStyle]}>
        {indicators}
      </View>
    );
  },

  onAnimationEnd(e) {
    var activePage = e.nativeEvent.contentOffset.x / this.props.width;
    this.setState({
      activePage: activePage
    });
    if (this.props.onPageChange) {
      this.props.onPageChange(activePage);
    }
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  page: {
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
  },
  pageIndicator: {
    position: 'absolute',
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor:'transparent'
  },
  pageIndicatorTop: {
    top: 20
  },
  pageIndicatorBottom: {
    bottom:20
  }
});

module.exports = Carousel;
<commit_msg>Set default to false<commit_after>'use strict';

var React = require('react-native');
var {
  StyleSheet,
  View,
  Text,
  ScrollView,
} = React;

var Carousel = React.createClass({

  getDefaultProps() {
    return {
      hideIndicators: false,
      indicatorColor: '#000000',
      inactiveIndicatorColor: '#999999',
      indicatorAtBottom: true,
      width: 375
    };
  },

  getInitialState() {
    return {
      activePage: 0
    };
  },

  render() {

    return (
      <View style={{ flex: 1 }}>
        <ScrollView ref="scrollview"
          contentContainerStyle={styles.container}
          automaticallyAdjustContentInsets={false}
          horizontal={true}
          pagingEnabled={true}
          showsHorizontalScrollIndicator={false}
          bounces={false}
          onMomentumScrollEnd={this.onAnimationEnd}
        >
          {this.props.children}
        </ScrollView>
        {this.renderPageIndicator()}
      </View>
    );
  },
  indicatorPressed(ind){
    this.setState({
      activePage:ind
    });

    this.refs.scrollview.scrollTo(0,ind*this.props.width);
  },

  renderPageIndicator() {
    if (this.props.hideIndicators === true) {
      return null;
    }

    var indicators = [],
        indicatorStyle = this.props.indicatorAtBottom ? styles.pageIndicatorBottom : styles.pageIndicatorTop,
        style, position;

    position = {
      width: this.props.children.length * 15,
    };
    position.left = (this.props.width - position.width) / 2;

    for (var i=0; i< this.props.children.length; i++) {
      style = i === this.state.activePage ? { color: this.props.indicatorColor } : { color: this.props.inactiveIndicatorColor };
      indicators.push(<Text style={style} key={i} onPress={this.indicatorPressed.bind(this,i)}>•</Text>);
    }

    return (
      <View style={[styles.pageIndicator, position, indicatorStyle]}>
        {indicators}
      </View>
    );
  },

  onAnimationEnd(e) {
    var activePage = e.nativeEvent.contentOffset.x / this.props.width;
    this.setState({
      activePage: activePage
    });
    if (this.props.onPageChange) {
      this.props.onPageChange(activePage);
    }
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  page: {
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
  },
  pageIndicator: {
    position: 'absolute',
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor:'transparent'
  },
  pageIndicatorTop: {
    top: 20
  },
  pageIndicatorBottom: {
    bottom:20
  }
});

module.exports = Carousel;
<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var {
  StyleSheet,
  View,
  Text,
  ScrollView,
} = React;

var Carousel = React.createClass({

  getDefaultProps() {
    return {
      hideIndicators: false,
      indicatorColor: '#000000',
      indicatorSize: 20,
      inactiveIndicatorColor: '#999999',
      indicatorAtBottom: true,
      width: 375,
      initialPage: 0,
      indicatorSpace: 15
    };
  },

  getInitialState() {
    return {
      activePage: 0
    };
  },

  componentDidMount() {
    if (this.props.initialPage > 0) {
      var width = this.props.initialPage * this.props.width;
      this.setState({
        activePage: this.props.initialPage
      });
      this.refs.scrollview.scrollWithoutAnimationTo(0, this.props.initialPage * width);
    }
  },

  render() {

    return (
      <View style={{ flex: 1 }}>
        <ScrollView ref="scrollview"
          contentContainerStyle={styles.container}
          automaticallyAdjustContentInsets={false}
          horizontal={true}
          pagingEnabled={true}
          showsHorizontalScrollIndicator={false}
          bounces={false}
          onMomentumScrollEnd={this.onAnimationEnd}
        >
          {this.props.children}
        </ScrollView>
        {this.renderPageIndicator()}
      </View>
    );
  },

  indicatorPressed(ind){
    this.setState({
      activePage:ind
    });

    this.refs.scrollview.scrollTo(0,ind*this.props.width);
  },

  renderPageIndicator() {
    if (this.props.hideIndicators === true) {
      return null;
    }

    var indicators = [],
        indicatorStyle = this.props.indicatorAtBottom ? styles.pageIndicatorBottom : styles.pageIndicatorTop,
        style, position;

    position = {
      width: this.props.children.length * this.props.indicatorSpace,
    };
    position.left = (this.props.width - position.width) / 2;

    for (var i=0; i< this.props.children.length; i++) {
      style = i === this.state.activePage ? { color: this.props.indicatorColor } : { color: this.props.inactiveIndicatorColor };
      indicators.push(<Text style={[style, { fontSize: this.props.indicatorSize }]} key={i} onPress={this.indicatorPressed.bind(this,i)}>•</Text>);
    }

    return (
      <View style={[styles.pageIndicator, position, indicatorStyle]}>
        {indicators}
      </View>
    );
  },

  onAnimationEnd(e) {
    var activePage = e.nativeEvent.contentOffset.x / this.props.width;
    this.setState({
      activePage: activePage
    });
    if (this.props.onPageChange) {
      this.props.onPageChange(activePage);
    }
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  page: {
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
  },
  pageIndicator: {
    position: 'absolute',
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor:'transparent'
  },
  pageIndicatorTop: {
    top: 20
  },
  pageIndicatorBottom: {
    bottom:20
  }
});

module.exports = Carousel;
<commit_msg>Add custom prop for indicator bullets style<commit_after>'use strict';

var React = require('react-native');
var {
  StyleSheet,
  View,
  Text,
  ScrollView,
} = React;

var Carousel = React.createClass({

  getDefaultProps() {
    return {
      hideIndicators: false,
      indicatorColor: '#000000',
      indicatorSize: 20,
      inactiveIndicatorColor: '#999999',
      indicatorAtBottom: true,
      width: 375,
      initialPage: 0,
      indicatorSpace: 15
    };
  },

  getInitialState() {
    return {
      activePage: 0
    };
  },

  componentDidMount() {
    if (this.props.initialPage > 0) {
      var width = this.props.initialPage * this.props.width;
      this.setState({
        activePage: this.props.initialPage
      });
      this.refs.scrollview.scrollWithoutAnimationTo(0, this.props.initialPage * width);
    }
  },

  render() {

    return (
      <View style={{ flex: 1 }}>
        <ScrollView ref="scrollview"
          contentContainerStyle={styles.container}
          automaticallyAdjustContentInsets={false}
          horizontal={true}
          pagingEnabled={true}
          showsHorizontalScrollIndicator={false}
          bounces={false}
          onMomentumScrollEnd={this.onAnimationEnd}
        >
          {this.props.children}
        </ScrollView>
        {this.renderPageIndicator()}
      </View>
    );
  },

  indicatorPressed(ind){
    this.setState({
      activePage:ind
    });

    this.refs.scrollview.scrollTo(0,ind*this.props.width);
  },

  renderPageIndicator() {
    if (this.props.hideIndicators === true) {
      return null;
    }

    var indicators = [],
        indicatorStyle = this.props.indicatorAtBottom ? styles.pageIndicatorBottom : styles.pageIndicatorTop,
        style, position;

    position = {
      width: this.props.children.length * this.props.indicatorSpace,
    };
    position.left = (this.props.width - position.width) / 2;

    for (var i=0; i< this.props.children.length; i++) {
      style = i === this.state.activePage ? { color: this.props.indicatorColor } : { color: this.props.inactiveIndicatorColor };
      indicators.push(<Text style={[style, { fontSize: this.props.indicatorSize }]} key={i} onPress={this.indicatorPressed.bind(this,i)}>•</Text>);
    }

    return (
      <View style={[styles.pageIndicator, position, indicatorStyle, this.props.indicatorStyle]}>
        {indicators}
      </View>
    );
  },

  onAnimationEnd(e) {
    var activePage = e.nativeEvent.contentOffset.x / this.props.width;
    this.setState({
      activePage: activePage
    });
    if (this.props.onPageChange) {
      this.props.onPageChange(activePage);
    }
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  page: {
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
  },
  pageIndicator: {
    position: 'absolute',
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor:'transparent'
  },
  pageIndicatorTop: {
    top: 20
  },
  pageIndicatorBottom: {
    bottom:20
  }
});

module.exports = Carousel;
<|endoftext|>