Permalink
Browse files

Implement CSS z-index for iOS

Summary:
This diff implement the CSS z-index for React Native iOS views. We've had numerous pull request for this feature, but they've all attempted to use the `layer.zPosition` property, which is problematic for two reasons:

1. zPosition only affects rendering order, not event processing order. Views with a higher zPosition will appear in front of others in the hierarchy, but won't be the first to receive touch events, and may be blocked by views that are visually behind them.
2. when using a perspective transform matrix, views with a nonzero zPosition will be rendered in a different position due to parallax, which probably isn't desirable.

See #7825 for further discussion of this problem.

So instead of using `layer.zPosition`, I've implemented this by actually adjusting the order of the subviews within their parent based on the zIndex. This can't be done on the JS side because it would affect layout, which is order-dependent, so I'm doing it inside the view itself.

It works as follows:

1. The `reactSubviews` array is set, whose order matches the order of the JS components and shadowView components, as specified by the UIManager.
2. `didUpdateReactSubviews` is called, which in turn calls `sortedSubviews` (which lazily generates a sorted array of  `reactSubviews` by zIndex) and inserts the result into the view.
3.  If a subview is added or removed, or the zIndex of any subview is changed, the previous `sortedSubviews` array is cleared and  `didUpdateReactSubviews` is called again.

To demonstrate it working, I've modified the UIExplorer example from #7825

Reviewed By: javache

Differential Revision: D3365717

fbshipit-source-id: b34aa8bfad577bce023f8af5414f9b974aafd8aa
  • Loading branch information...
nicklockwood authored and Facebook Github Bot 8 committed Jun 7, 2016
1 parent 993a928 commit d64368b9e239b574039f4a6508bf2aeb0806121b
@@ -1,4 +1,11 @@
/**
* Copyright (c) 2013-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.
*
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
@@ -30,7 +37,13 @@ var styles = StyleSheet.create({
backgroundColor: '#527FE4',
borderColor: '#000033',
borderWidth: 1,
}
},
zIndex: {
justifyContent: 'space-around',
width: 100,
height: 50,
marginTop: -10,
},
});
var ViewBorderStyleExample = React.createClass({
@@ -74,6 +87,53 @@ var ViewBorderStyleExample = React.createClass({
}
});
var ZIndexExample = React.createClass({
getInitialState() {
return {
flipped: false
};
},
render() {
const indices = this.state.flipped ? [-1, 0, 1, 2] : [2, 1, 0, -1];
return (
<TouchableWithoutFeedback onPress={this._handlePress}>
<View>
<Text style={{paddingBottom: 10}}>Tap to flip sorting order</Text>
<View style={[
styles.zIndex,
{marginTop: 0, backgroundColor: '#E57373', zIndex: indices[0]}
]}>
<Text>ZIndex {indices[0]}</Text>
</View>
<View style={[
styles.zIndex,
{marginLeft: 50, backgroundColor: '#FFF176', zIndex: indices[1]}
]}>
<Text>ZIndex {indices[1]}</Text>
</View>
<View style={[
styles.zIndex,
{marginLeft: 100, backgroundColor: '#81C784', zIndex: indices[2]}
]}>
<Text>ZIndex {indices[2]}</Text>
</View>
<View style={[
styles.zIndex,
{marginLeft: 150, backgroundColor: '#64B5F6', zIndex: indices[3]}
]}>
<Text>ZIndex {indices[3]}</Text>
</View>
</View>
</TouchableWithoutFeedback>
);
},
_handlePress() {
this.setState({flipped: !this.state.flipped});
}
});
exports.title = '<View>';
exports.description = 'Basic building block of all UI, examples that ' +
'demonstrate some of the many styles available.';
@@ -188,5 +248,10 @@ exports.examples = [
</View>
);
},
}, {
title: 'ZIndex',
render: function() {
return <ZIndexExample />;
},
},
];
@@ -100,6 +100,9 @@ var LayoutPropTypes = {
// https://developer.mozilla.org/en-US/docs/Web/CSS/flex
flex: ReactPropTypes.number,
// https://developer.mozilla.org/en-US/docs/Web/CSS/z-index
zIndex: ReactPropTypes.number,
};
module.exports = LayoutPropTypes;
@@ -893,8 +893,6 @@ static void RCTSetChildren(NSNumber *containerTag,
[container insertReactSubview:view atIndex:index++];
}
}
[container didUpdateReactSubviews];
}
RCT_EXPORT_METHOD(manageChildren:(nonnull NSNumber *)containerTag
@@ -965,8 +963,6 @@ - (void)_manageChildren:(NSNumber *)containerTag
[container insertReactSubview:destinationsToChildrenToAdd[reactIndex]
atIndex:reactIndex.integerValue];
}
[container didUpdateReactSubviews];
}
RCT_EXPORT_METHOD(createView:(nonnull NSNumber *)reactTag
@@ -129,6 +129,11 @@ typedef void (^RCTApplierBlock)(NSDictionary<NSNumber *, UIView *> *viewRegistry
@property (nonatomic, assign) css_wrap_type_t flexWrap;
@property (nonatomic, assign) CGFloat flex;
/**
* z-index, used to override sibling order in the view
*/
@property (nonatomic, assign) double zIndex;
/**
* Calculate property changes that need to be propagated to the view.
* The applierBlocks set contains RCTApplierBlock functions that must be applied
@@ -13,6 +13,7 @@
#import "RCTLog.h"
#import "RCTUtils.h"
#import "UIView+React.h"
#import "UIView+Private.h"
typedef void (^RCTActionBlock)(RCTShadowView *shadowViewSelf, id value);
typedef void (^RCTResetActionBlock)(RCTShadowView *shadowViewSelf);
@@ -39,6 +40,7 @@ @implementation RCTShadowView
BOOL _recomputePadding;
BOOL _recomputeMargin;
BOOL _recomputeBorder;
BOOL _didUpdateSubviews;
float _paddingMetaProps[META_PROP_COUNT];
float _marginMetaProps[META_PROP_COUNT];
float _borderMetaProps[META_PROP_COUNT];
@@ -179,6 +181,16 @@ - (void)applyLayoutToChildren:(css_node_t *)node
// dirtied, but really we should track which properties have changed and
// only update those.
if (_didUpdateSubviews) {
_didUpdateSubviews = NO;
[self didUpdateReactSubviews];
[applierBlocks addObject:^(NSDictionary<NSNumber *, UIView *> *viewRegistry) {
UIView *view = viewRegistry[_reactTag];
[view clearSortedSubviews];
[view didUpdateReactSubviews];
}];
}
if (!_backgroundColor) {
UIColor *parentBackgroundColor = parentProperties[RCTBackgroundColorProp];
if (parentBackgroundColor) {
@@ -351,6 +363,7 @@ - (void)insertReactSubview:(RCTShadowView *)subview atIndex:(NSInteger)atIndex
[_reactSubviews insertObject:subview atIndex:atIndex];
_cssNode->children_count = (int)_reactSubviews.count;
subview->_superview = self;
_didUpdateSubviews = YES;
[self dirtyText];
[self dirtyLayout];
[self dirtyPropagation];
@@ -361,6 +374,7 @@ - (void)removeReactSubview:(RCTShadowView *)subview
[subview dirtyText];
[subview dirtyLayout];
[subview dirtyPropagation];
_didUpdateSubviews = YES;
subview->_superview = nil;
[_reactSubviews removeObject:subview];
_cssNode->children_count = (int)_reactSubviews.count;
@@ -596,6 +610,16 @@ - (void)setBackgroundColor:(UIColor *)color
[self dirtyPropagation];
}
- (void)setZIndex:(double)zIndex
{
_zIndex = zIndex;
if (_superview) {
// Changing zIndex means the subview order of the parent needs updating
_superview->_didUpdateSubviews = YES;
[_superview dirtyPropagation];
}
}
- (void)didUpdateReactSubviews
{
// Does nothing by default
View
@@ -41,6 +41,13 @@
*/
+ (UIEdgeInsets)contentInsetsForView:(UIView *)curView;
/**
* z-index, used to override sibling order in didUpdateReactSubviews. This is
* inherited from UIView+React, but we override it here to reduce the boxing
* and associated object overheads.
*/
@property (nonatomic, assign) double reactZIndex;
/**
* This is an optimization used to improve performance
* for large scrolling views with many subviews, such as a
View
@@ -99,6 +99,8 @@ @implementation RCTView
UIColor *_backgroundColor;
}
@synthesize reactZIndex = _reactZIndex;
- (instancetype)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame])) {
@@ -274,7 +276,7 @@ + (UIEdgeInsets)contentInsetsForView:(UIView *)view
- (void)react_remountAllSubviews
{
if (_removeClippedSubviews) {
for (UIView *view in self.reactSubviews) {
for (UIView *view in self.sortedReactSubviews) {
if (view.superview != self) {
[self addSubview:view];
[view react_remountAllSubviews];
@@ -313,7 +315,7 @@ - (void)react_updateClippedSubviewsWithClipRect:(CGRect)clipRect relativeToView:
clipView = self;
// Mount / unmount views
for (UIView *view in self.reactSubviews) {
for (UIView *view in self.sortedReactSubviews) {
if (!CGRectIsEmpty(CGRectIntersection(clipRect, view.frame))) {
// View is at least partially visible, so remount it if unmounted
@@ -246,6 +246,8 @@ - (RCTViewManagerUIBlock)uiBlockToAmendWithShadowViewRegistry:(__unused NSDictio
RCT_VIEW_BORDER_RADIUS_PROPERTY(BottomLeft)
RCT_VIEW_BORDER_RADIUS_PROPERTY(BottomRight)
RCT_REMAP_VIEW_PROPERTY(zIndex, reactZIndex, double)
#pragma mark - ShadowView properties
RCT_EXPORT_SHADOW_PROPERTY(backgroundColor, UIColor)
@@ -290,4 +292,6 @@ - (RCTViewManagerUIBlock)uiBlockToAmendWithShadowViewRegistry:(__unused NSDictio
RCT_EXPORT_SHADOW_PROPERTY(onLayout, RCTDirectEventBlock)
RCT_EXPORT_SHADOW_PROPERTY(zIndex, double)
@end
@@ -9,10 +9,14 @@
#import <UIKit/UIKit.h>
@interface UIView (RCTViewUnmounting)
@interface UIView (Private)
// remove clipped subviews implementation
- (void)react_remountAllSubviews;
- (void)react_updateClippedSubviewsWithClipRect:(CGRect)clipRect relativeToView:(UIView *)clipView;
- (UIView *)react_findClipView;
// zIndex sorting
- (void)clearSortedSubviews;
@end
View
@@ -25,9 +25,20 @@
- (void)insertReactSubview:(UIView *)subview atIndex:(NSInteger)atIndex NS_REQUIRES_SUPER;
- (void)removeReactSubview:(UIView *)subview NS_REQUIRES_SUPER;
/**
* z-index, used to override sibling order in didUpdateReactSubviews.
*/
@property (nonatomic, assign) double reactZIndex;
/**
* The reactSubviews array, sorted by zIndex. This value is cached and
* automatically recalculated if views are added or removed.
*/
@property (nonatomic, copy, readonly) NSArray<UIView *> *sortedReactSubviews;
/**
* Updates the subviews array based on the reactSubviews. Default behavior is
* to insert the reactSubviews into the UIView.
* to insert the sortedReactSubviews into the UIView.
*/
- (void)didUpdateReactSubviews;
View
@@ -87,9 +87,51 @@ - (void)removeReactSubview:(UIView *)subview
[subview removeFromSuperview];
}
- (double)reactZIndex
{
return [objc_getAssociatedObject(self, _cmd) doubleValue];
}
- (void)setReactZIndex:(double)reactZIndex
{
objc_setAssociatedObject(self, @selector(reactZIndex), @(reactZIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSArray<UIView *> *)sortedReactSubviews
{
NSArray *subviews = objc_getAssociatedObject(self, _cmd);
if (!subviews) {
// Check if sorting is required - in most cases it won't be
BOOL sortingRequired = NO;
for (UIView *subview in self.reactSubviews) {
if (subview.reactZIndex != 0) {
sortingRequired = YES;
break;
}
}
subviews = sortingRequired ? [self.reactSubviews sortedArrayUsingComparator:^NSComparisonResult(UIView *a, UIView *b) {
if (a.reactZIndex > b.reactZIndex) {
return NSOrderedDescending;
} else {
// ensure sorting is stable by treating equal zIndex as ascending so
// that original order is preserved
return NSOrderedAscending;
}
}] : self.reactSubviews;
objc_setAssociatedObject(self, _cmd, subviews, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return subviews;
}
// private method, used to reset sort
- (void)clearSortedSubviews
{
objc_setAssociatedObject(self, @selector(sortedReactSubviews), nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)didUpdateReactSubviews
{
for (UIView *subview in self.reactSubviews) {
for (UIView *subview in self.sortedReactSubviews) {
[self addSubview:subview];
}
}

3 comments on commit d64368b

@skv-headless

This comment has been minimized.

Show comment
Hide comment
@skv-headless

skv-headless Jun 9, 2016

Contributor

🎉

Contributor

skv-headless replied Jun 9, 2016

🎉

@senthilsivanath

This comment has been minimized.

Show comment
Hide comment
@senthilsivanath

senthilsivanath Jul 12, 2016

Any plans for android ?

senthilsivanath replied Jul 12, 2016

Any plans for android ?

@rclai

This comment has been minimized.

Show comment
Hide comment
@rclai
Contributor

rclai replied Jul 12, 2016

Please sign in to comment.