Skip to content

Commit

Permalink
Implement CSS z-index for iOS
Browse files Browse the repository at this point in the history
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 d64368b
Show file tree
Hide file tree
Showing 11 changed files with 173 additions and 10 deletions.
67 changes: 66 additions & 1 deletion Examples/UIExplorer/ViewExample.js
Original file line number Diff line number Diff line change
@@ -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.
*
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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.';
Expand Down Expand Up @@ -188,5 +248,10 @@ exports.examples = [
</View>
);
},
}, {
title: 'ZIndex',
render: function() {
return <ZIndexExample />;
},
},
];
3 changes: 3 additions & 0 deletions Libraries/StyleSheet/LayoutPropTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
4 changes: 0 additions & 4 deletions React/Modules/RCTUIManager.m
Original file line number Diff line number Diff line change
Expand Up @@ -893,8 +893,6 @@ static void RCTSetChildren(NSNumber *containerTag,
[container insertReactSubview:view atIndex:index++];
}
}

[container didUpdateReactSubviews];
}

RCT_EXPORT_METHOD(manageChildren:(nonnull NSNumber *)containerTag
Expand Down Expand Up @@ -965,8 +963,6 @@ - (void)_manageChildren:(NSNumber *)containerTag
[container insertReactSubview:destinationsToChildrenToAdd[reactIndex]
atIndex:reactIndex.integerValue];
}

[container didUpdateReactSubviews];
}

RCT_EXPORT_METHOD(createView:(nonnull NSNumber *)reactTag
Expand Down
5 changes: 5 additions & 0 deletions React/Views/RCTShadowView.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 24 additions & 0 deletions React/Views/RCTShadowView.m
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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];
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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];
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions React/Views/RCTView.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions React/Views/RCTView.m
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ @implementation RCTView
UIColor *_backgroundColor;
}

@synthesize reactZIndex = _reactZIndex;

- (instancetype)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame])) {
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions React/Views/RCTViewManager.m
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -290,4 +292,6 @@ - (RCTViewManagerUIBlock)uiBlockToAmendWithShadowViewRegistry:(__unused NSDictio

RCT_EXPORT_SHADOW_PROPERTY(onLayout, RCTDirectEventBlock)

RCT_EXPORT_SHADOW_PROPERTY(zIndex, double)

@end
6 changes: 5 additions & 1 deletion React/Views/UIView+Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
13 changes: 12 additions & 1 deletion React/Views/UIView+React.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
44 changes: 43 additions & 1 deletion React/Views/UIView+React.m
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}
}
Expand Down

3 comments on commit d64368b

@skv-headless
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

@senthilsivanath
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any plans for android ?

@rclai
Copy link
Contributor

@rclai rclai commented on d64368b Jul 12, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.