Created
March 26, 2014 17:55
-
-
Save parshap/9789332 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
// A function that wraps a given `React.DOM.input`-like component to | |
// apply formatting to the value for display purposes. | |
// | |
// Example: | |
// | |
// var RoundedInput = createFormattedInput(React.DOM.input, { | |
// set: Math.round, | |
// }); | |
var React = require("react"); | |
var isFunction = require("core-util-is").isFunction; | |
var defaults = require("underscore").defaults; | |
var filter = require("object-filter"); | |
var getOnChange = require("react/lib/LinkedValueUtils").getOnChange; | |
function getValue(props) { | |
return props.valueLink ? props.valueLink.value : props.value; | |
} | |
function filterKeys(obj, keys) { | |
return filter(obj, function(val, key) { | |
return keys.indexOf(key) === -1; | |
}); | |
} | |
module.exports = function(Component, options) { | |
return React.createClass({ | |
getState: function(props) { | |
var value = String(getValue(props)); | |
return { | |
value: format.call(this, value), | |
}; | |
}, | |
getInitialState: function() { | |
return this.getState(this.props); | |
}, | |
componentWillReceiveProps: function(props) { | |
this.setState(this.getState(props)); | |
}, | |
handleChange: function(e) { | |
this.setState({ value: e.target.value }); | |
}, | |
handleFormat: function() { | |
var value = unformat.call(this, this.state.value); | |
var e = { target: { value: value } }; | |
getOnChange(this).call(this, e); | |
}, | |
render: function() { | |
var props = filterKeys(this.props, ["valueLink"]); | |
return Component(defaults({ | |
value: this.state.value, | |
onChange: this.handleChange, | |
onBlur: this.handleFormat, | |
}, props)); | |
}, | |
}); | |
function format(value) { | |
if (options.format) { | |
return options.format.call(this, value); | |
} | |
return value; | |
} | |
function unformat(value) { | |
if (options.unformat) { | |
return options.unformat.call(this, value); | |
} | |
return value; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment