ColorPropTypes support for isRequired and more precise description

Summary:
The previous implementation of ColorPropType was very hacky as it used `ReactPropTypes.oneOfType([colorValidator, ReactPropTypes.number])`. It turns out that oneOfType also accepts arbitrary functions instead of a type, but doesn't display any of the error message.

In this diff I properly implement isRequired (sadly we don't export `createChainableTypeChecker` in ReactPropTypes) and provide a lot more context that we have. I copy and pasted the way we displayed this context from the existing checkers.

**Test Plan**

When doing .isRequired and do not provide the value:

![simulator screen shot feb 1 2016 9 56 00 am](https://cloud.githubusercontent.com/assets/197597/12726239/61243f88-c8cb-11e5-889b-6594ffd85973.png)

When providing a bad value:

![simulator screen shot feb 1 2016 10 01 25 am](https://cloud.githubusercontent.com/assets/197597/12726244/6e80aa36-c8cb-11e5-9bd3-a8637de75496.png)
Closes https://github.com/facebook/react-native/pull/5671

Reviewed By: svcscm

Differential Revision: D2886760

Pulled By: vjeux

fb-gh-sync-id: d6be42b5768fca5463fe80fe4b144506d21b0832
This commit is contained in:
Christopher Chedeau 2016-02-01 12:46:50 -08:00 committed by facebook-github-bot-4
parent 36efbc341d
commit 1491668b35
1 changed files with 18 additions and 3 deletions

View File

@ -11,12 +11,20 @@
'use strict';
var ReactPropTypes = require('ReactPropTypes');
var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
var normalizeColor = require('normalizeColor');
var ColorPropType = function(props, propName) {
var colorPropType = function(isRequired, props, propName, componentName, location, propFullName) {
var color = props[propName];
if (color === undefined || color === null) {
if (isRequired) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
'Required ' + locationName + ' `' + (propFullName || propName) +
'` was not specified in `' + componentName + '`.'
);
}
return;
}
@ -28,8 +36,11 @@ var ColorPropType = function(props, propName) {
}
if (normalizeColor(color) === null) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
`Invalid color supplied to ${propName}: ${color}. Valid color formats are
'Invalid ' + locationName + ' `' + (propFullName || propName) +
'` supplied to `' + componentName + '`: ' + color + '\n' +
`Valid color formats are
- #f0f (#rgb)
- #f0fc (#rgba)
- #ff00ff (#rrggbb)
@ -39,8 +50,12 @@ var ColorPropType = function(props, propName) {
- hsl(360, 100%, 100%)
- hsla(360, 100%, 100%, 1.0)
- transparent
- red`);
- red
`);
}
};
var ColorPropType = colorPropType.bind(null, false /* isRequired */);
ColorPropType.isRequired = colorPropType.bind(null, true /* isRequired */);
module.exports = ColorPropType;