react-native/Libraries/StyleSheet/flattenStyle.js

52 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-01-30 01:10:49 +00:00
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
2015-01-30 01:10:49 +00:00
*
* @providesModule flattenStyle
2015-03-25 02:34:12 +00:00
* @flow
2015-01-30 01:10:49 +00:00
*/
'use strict';
var StyleSheetRegistry = require('StyleSheetRegistry');
2015-03-25 02:34:12 +00:00
var invariant = require('invariant');
2015-01-30 01:10:49 +00:00
var mergeIntoFast = require('mergeIntoFast');
2015-03-25 02:34:12 +00:00
type Atom = number | bool | Object | Array<?Atom>
type StyleObj = Atom | Array<?StyleObj>
2015-01-30 01:10:49 +00:00
function getStyle(style) {
if (typeof style === 'number') {
return StyleSheetRegistry.getStyleByID(style);
}
return style;
}
2015-03-25 02:34:12 +00:00
// TODO: Flow 0.7.0 doesn't refine bools properly so we have to use `any` to
// tell it that this can't be a bool anymore. Should be fixed in 0.8.0,
// after which this can take a ?StyleObj.
function flattenStyle(style: any): ?Object {
2015-01-30 01:10:49 +00:00
if (!style) {
return undefined;
}
2015-03-25 02:34:12 +00:00
invariant(style !== true, 'style may be false but not true');
2015-01-30 01:10:49 +00:00
if (!Array.isArray(style)) {
return getStyle(style);
}
var result = {};
for (var i = 0; i < style.length; ++i) {
var computedStyle = flattenStyle(style[i]);
if (computedStyle) {
mergeIntoFast(result, computedStyle);
}
}
return result;
}
module.exports = flattenStyle;