Updates from Wed July 15th

This commit is contained in:
Spencer Ahrens committed 2015-07-15 19:05:08 +02:00
commit 902ffbbfb8
54 files changed
+632 -573

No files matched your search

+1 -1
View File
@@ -87,7 +87,7 @@ RCT_ENUM_CONVERTER(CTTextAlignment, (@{
}
NSDictionary *fontDict = dict[@"font"];
CTFontRef font = (__bridge CTFontRef)[self UIFont:nil withFamily:fontDict[@"fontFamily"] size:fontDict[@"fontSize"] weight:fontDict[@"fontWeight"] style:fontDict[@"fontStyle"] scaleMultiplier:1.0];
CTFontRef font = (__bridge CTFontRef)[self UIFont:nil withFamily:fontDict[@"fontFamily"] size:fontDict[@"fontSize"] weight:fontDict[@"fontWeight"] style:fontDict[@"fontStyle"]];
if (!font) {
return frame;
}
+1 -1
View File
@@ -411,7 +411,7 @@ var TextInput = React.createClass({
_renderIOS: function() {
var textContainer;
var props = this.props;
var props = Object.assign({},this.props);
props.style = [styles.input, this.props.style];
if (!props.multiline) {
@@ -21,6 +21,7 @@ var TransformPropTypes = require('TransformPropTypes');
var ViewStylePropTypes = {
...LayoutPropTypes,
...TransformPropTypes,
backfaceVisibility: ReactPropTypes.oneOf(['visible', 'hidden']),
backgroundColor: ReactPropTypes.string,
borderColor: ReactPropTypes.string,
borderTopColor: ReactPropTypes.string,
@@ -220,11 +220,6 @@ var Navigator = React.createClass({
*/
onDidFocus: PropTypes.func,
/**
* Will be called with (ref, indexInStack, route) when the scene ref changes
*/
onItemRef: PropTypes.func,
/**
* Optionally provide a navigation bar that persists across scene
* transitions
@@ -318,7 +313,6 @@ var Navigator = React.createClass({
onPanResponderMove: this._handlePanResponderMove,
onPanResponderTerminate: this._handlePanResponderTerminate,
});
this._itemRefs = {};
this._interactionHandle = null;
this._emitWillFocus(this.state.routeStack[this.state.presentedIndex]);
},
@@ -1006,22 +1000,10 @@ var Navigator = React.createClass({
return this.state.routeStack.slice();
},
_handleItemRef: function(itemId, route, ref) {
this._itemRefs[itemId] = ref;
var itemIndex = this.state.idStack.indexOf(itemId);
if (itemIndex === -1) {
return;
}
this.props.onItemRef && this.props.onItemRef(ref, itemIndex, route);
},
_cleanScenesPastIndex: function(index) {
var newStackLength = index + 1;
// Remove any unneeded rendered routes.
if (newStackLength < this.state.routeStack.length) {
this.state.idStack.slice(newStackLength).map((removingId) => {
this._itemRefs[removingId] = null;
});
this.setState({
sceneConfigStack: this.state.sceneConfigStack.slice(0, newStackLength),
idStack: this.state.idStack.slice(0, newStackLength),
@@ -1031,38 +1013,22 @@ var Navigator = React.createClass({
},
_renderScene: function(route, i) {
var child = this.props.renderScene(
route,
this
);
var disabledSceneStyle = null;
if (i !== this.state.presentedIndex) {
disabledSceneStyle = styles.disabledScene;
}
var originalRef = child.ref;
if (originalRef != null && typeof originalRef !== 'function') {
console.warn(
'String refs are not supported for navigator scenes. Use a callback ' +
'ref instead. Ignoring ref: ' + originalRef
);
originalRef = null;
}
return (
<View
key={this.state.idStack[i]}
key={'scene_' + i}
ref={'scene_' + i}
onStartShouldSetResponderCapture={() => {
return (this.state.transitionFromIndex != null) || (this.state.transitionFromIndex != null);
}}
style={[styles.baseScene, this.props.sceneStyle, disabledSceneStyle]}>
{React.cloneElement(child, {
ref: component => {
this._handleItemRef(this.state.idStack[i], route, component);
if (originalRef) {
originalRef(component);
}
}
})}
{this.props.renderScene(
route,
this
)}
</View>
);
},
-1
View File
@@ -66,7 +66,6 @@ static void *const RCTDownloadTaskWrapperProgressBlockKey = (void *)&RCTDownload
task.rct_completionBlock = completionBlock;
task.rct_progressBlock = progressBlock;
[task resume];
return task;
}
+20 -7
View File
@@ -14,7 +14,8 @@
#import "RCTLog.h"
#import "RCTUtils.h"
typedef void (^RCTCachedDataDownloadBlock)(BOOL cached, NSData *data, NSError *error);
typedef void (^RCTCachedDataDownloadBlock)(BOOL cached, NSURLResponse *response,
NSData *data, NSError *error);
CGSize RCTTargetSizeForClipRect(CGRect);
CGRect RCTClipRect(CGSize, CGFloat, CGSize, CGFloat, UIViewContentMode);
@@ -80,24 +81,36 @@ CGRect RCTClipRect(CGSize, CGFloat, CGSize, CGFloat, UIViewContentMode);
_pendingBlocks[cacheKey] = [NSMutableArray arrayWithObject:block];
__weak RCTImageDownloader *weakSelf = self;
RCTCachedDataDownloadBlock runBlocks = ^(BOOL cached, NSData *data, NSError *error) {
RCTCachedDataDownloadBlock runBlocks = ^(BOOL cached, NSURLResponse *response, NSData *data, NSError *error) {
if (!error && [response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode != 200) {
data = nil;
error = [[NSError alloc] initWithDomain:NSURLErrorDomain
code:httpResponse.statusCode
userInfo:nil];
}
}
dispatch_async(_processingQueue, ^{
RCTImageDownloader *strongSelf = weakSelf;
NSArray *blocks = strongSelf->_pendingBlocks[cacheKey];
[strongSelf->_pendingBlocks removeObjectForKey:cacheKey];
for (RCTCachedDataDownloadBlock downloadBlock in blocks) {
downloadBlock(cached, data, error);
downloadBlock(cached, response, data, error);
}
});
};
NSURLRequest *request = [NSURLRequest requestWithURL:url];
task = [_downloadTaskWrapper downloadData:url progressBlock:progressBlock completionBlock:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!cancelled) {
runBlocks(NO, data, error);
runBlocks(NO, response, data, error);
}
if (response) {
if (response && !error) {
RCTImageDownloader *strongSelf = weakSelf;
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:data userInfo:nil storagePolicy:NSURLCacheStorageAllowed];
[strongSelf->_cache storeCachedResponse:cachedResponse forRequest:request];
@@ -111,7 +124,7 @@ CGRect RCTClipRect(CGSize, CGFloat, CGSize, CGFloat, UIViewContentMode);
}
if (cachedResponse) {
runBlocks(YES, cachedResponse.data, nil);
runBlocks(YES, cachedResponse.response, cachedResponse.data, nil);
} else {
[task resume];
}
@@ -123,7 +136,7 @@ CGRect RCTClipRect(CGSize, CGFloat, CGSize, CGFloat, UIViewContentMode);
- (RCTImageDownloadCancellationBlock)downloadDataForURL:(NSURL *)url progressBlock:(RCTDataProgressBlock)progressBlock block:(RCTDataDownloadBlock)block
{
return [self _downloadDataForURL:url progressBlock:progressBlock block:^(BOOL cached, NSData *data, NSError *error) {
return [self _downloadDataForURL:url progressBlock:progressBlock block:^(BOOL cached, NSURLResponse *response, NSData *data, NSError *error) {
block(data, error);
}];
}
+4 -2
View File
@@ -86,6 +86,8 @@ RCT_NOT_IMPLEMENTED(-initWithCoder:(NSCoder *)aDecoder)
{
if (![_imageURL isEqual:imageURL] && _downloadToken) {
[_imageDownloader cancelDownload:_downloadToken];
NSDictionary *event = @{ @"target": self.reactTag };
[_eventDispatcher sendInputEventWithName:@"loadAbort" body:event];
_downloadToken = nil;
}
@@ -146,7 +148,7 @@ RCT_NOT_IMPLEMENTED(-initWithCoder:(NSCoder *)aDecoder)
loadEndHandler();
});
} else if (error) {
errorHandler([error description]);
errorHandler([error localizedDescription]);
}
}];
} else {
@@ -170,7 +172,7 @@ RCT_NOT_IMPLEMENTED(-initWithCoder:(NSCoder *)aDecoder)
loadEndHandler();
});
} else if (error) {
errorHandler([error description]);
errorHandler([error localizedDescription]);
}
}];
}
+1 -1
View File
@@ -47,7 +47,7 @@ RCT_CUSTOM_VIEW_PROPERTY(tintColor, UIColor, RCTNetworkImageView)
return @{
@"loadStart": @{ @"registrationName": @"onLoadStart" },
@"loadProgress": @{ @"registrationName": @"onLoadProgress" },
@"loaded": @{ @"registrationName": @"onLoaded" },
@"loaded": @{ @"registrationName": @"onLoadEnd" },
@"loadError": @{ @"registrationName": @"onLoadError" },
@"loadAbort": @{ @"registrationName": @"onLoadAbort" },
};
+72
View File
@@ -20,10 +20,21 @@ var StyleSheet = require('StyleSheet');
var UIManager = require('NativeModules').UIManager;
var View = require('View');
var REACT_DEVTOOLS_HOOK: ?Object = typeof window !== 'undefined' ? window.__REACT_DEVTOOLS_BACKEND__ : null;
if (REACT_DEVTOOLS_HOOK) {
// required for devtools to be able to edit react native styles
REACT_DEVTOOLS_HOOK.resolveRNStyle = require('flattenStyle');
}
class Inspector extends React.Component {
_subs: ?Array<() => void>;
constructor(props: Object) {
super(props);
this.state = {
devtoolsBackend: null,
panelPos: 'bottom',
inspecting: true,
perfing: false,
@@ -31,6 +42,63 @@ class Inspector extends React.Component {
};
}
componentDidMount() {
if (REACT_DEVTOOLS_HOOK) {
this.attachToDevtools = this.attachToDevtools.bind(this);
REACT_DEVTOOLS_HOOK.addStartupListener(this.attachToDevtools);
// if devtools is already started
// TODO(jared): should addStartupListener just go ahead and call the
// listener if the devtools is already started? might be unexpected...
// is there some name other than `addStartupListener` that would be
// better?
if (REACT_DEVTOOLS_HOOK.backend) {
this.attachToDevtools(REACT_DEVTOOLS_HOOK.backend);
}
}
}
componentWillUnmount() {
if (this._subs) {
this._subs.map(fn => fn());
}
if (REACT_DEVTOOLS_HOOK) {
REACT_DEVTOOLS_HOOK.removeStartupListener(this.attachToDevtools);
}
}
attachToDevtools(backend: Object) {
var _hideWait = null;
var hlSub = backend.sub('highlight', ({node, name, props}) => {
clearTimeout(_hideWait);
UIManager.measure(node, (x, y, width, height, left, top) => {
this.setState({
hierarchy: [],
inspected: {
frame: {left, top, width, height},
style: props ? props.style : {},
},
});
});
});
var hideSub = backend.sub('hideHighlight', () => {
// we wait to actually hide in order to avoid flicker
_hideWait = setTimeout(() => {
this.setState({
inspected: null,
});
}, 100);
});
this._subs = [hlSub, hideSub];
backend.on('shutdown', () => {
this.setState({devtoolsBackend: null});
this._subs = null;
});
this.setState({
devtoolsBackend: backend,
});
}
setSelection(i: number) {
var instance = this.state.hierarchy[i];
var publicInstance = instance.getPublicInstance();
@@ -46,6 +114,9 @@ class Inspector extends React.Component {
}
onTouchInstance(instance: Object, frame: Object, pointerY: number) {
if (this.state.devtoolsBackend) {
this.state.devtoolsBackend.selectFromReactInstance(instance, true);
}
var hierarchy = InspectorUtils.getOwnerHierarchy(instance);
var publicInstance = instance.getPublicInstance();
var props = publicInstance.props || {};
@@ -88,6 +159,7 @@ class Inspector extends React.Component {
/>}
<View style={[styles.panelContainer, panelContainerStyle]}>
<InspectorPanel
devtoolsIsOpen={!!this.state.devtoolsBackend}
inspecting={this.state.inspecting}
perfing={this.state.perfing}
setPerfing={this.setPerfing.bind(this)}
+5 -1
View File
@@ -27,7 +27,11 @@ type EventLike = {
var InspectorOverlay = React.createClass({
propTypes: {
inspectedViewTag: PropTypes.object,
inspected: PropTypes.shape({
frame: PropTypes.object,
style: PropTypes.any,
}),
inspectedViewTag: PropTypes.number,
onTouchInstance: PropTypes.func.isRequired,
},
+2 -1
View File
@@ -58,7 +58,7 @@ class InspectorPanel extends React.Component {
}
return (
<View style={styles.container}>
{contents}
{!this.props.devtoolsIsOpen && contents}
<View style={styles.buttonRow}>
<Button
title={'Inspect'}
@@ -76,6 +76,7 @@ class InspectorPanel extends React.Component {
}
InspectorPanel.propTypes = {
devtoolsIsOpen: PropTypes.bool,
inspecting: PropTypes.bool,
setInspecting: PropTypes.func,
inspected: PropTypes.object,
@@ -25,13 +25,16 @@ type Exception = {
message: string;
}
var exceptionID = 0;
function reportException(e: Exception, isFatal: bool, stack?: any) {
var currentExceptionID = ++exceptionID;
if (RCTExceptionsManager) {
if (!stack) {
stack = parseErrorStack(e);
}
if (isFatal) {
RCTExceptionsManager.reportFatalException(e.message, stack);
RCTExceptionsManager.reportFatalException(e.message, stack, currentExceptionID);
} else {
RCTExceptionsManager.reportSoftException(e.message, stack);
}
@@ -39,7 +42,7 @@ function reportException(e: Exception, isFatal: bool, stack?: any) {
(sourceMapPromise = sourceMapPromise || loadSourceMap())
.then(map => {
var prettyStack = parseErrorStack(e, map);
RCTExceptionsManager.updateExceptionMessage(e.message, prettyStack);
RCTExceptionsManager.updateExceptionMessage(e.message, prettyStack, currentExceptionID);
})
.catch(error => {
// This can happen in a variety of normal situations, such as
@@ -0,0 +1,150 @@
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
'use strict';
jest.dontMock('diffRawProperties');
jest.dontMock('deepDiffer');
var diffRawProperties = require('diffRawProperties');
describe('diffRawProperties', function() {
it('should work with simple example', () => {
expect(diffRawProperties(
null,
{a: 1, c: 3},
{b: 2, c: 3},
{a: true, b: true}
)).toEqual({a: null, b: 2});
});
it('should skip fields that are equal', () => {
expect(diffRawProperties(
null,
{a: 1, b: 'two', c: true, d: false, e: undefined, f: 0},
{a: 1, b: 'two', c: true, d: false, e: undefined, f: 0},
{a: true, b: true, c: true, d: true, e: true, f: true}
)).toEqual(null);
});
it('should remove fields', () => {
expect(diffRawProperties(
null,
{a: 1},
{},
{a: true}
)).toEqual({a: null});
});
it('should ignore invalid fields', () => {
expect(diffRawProperties(
null,
{a: 1},
{b: 2},
{}
)).toEqual(null);
});
it('should override the updatePayload argument', () => {
var updatePayload = {a: 1};
var result = diffRawProperties(
updatePayload,
{},
{b: 2},
{b: true}
);
expect(result).toBe(updatePayload);
expect(result).toEqual({a: 1, b: 2});
});
it('should use the diff attribute', () => {
var diffA = jest.genMockFunction().mockImpl((a, b) => true);
var diffB = jest.genMockFunction().mockImpl((a, b) => false);
expect(diffRawProperties(
null,
{a: [1], b: [3]},
{a: [2], b: [4]},
{a: {diff: diffA}, b: {diff: diffB}}
)).toEqual({a: [2]});
expect(diffA).toBeCalledWith([1], [2]);
expect(diffB).toBeCalledWith([3], [4]);
});
it('should not use the diff attribute on addition/removal', () => {
var diffA = jest.genMockFunction();
var diffB = jest.genMockFunction();
expect(diffRawProperties(
null,
{a: [1]},
{b: [2]},
{a: {diff: diffA}, b: {diff: diffB}}
)).toEqual({a: null, b: [2]});
expect(diffA).not.toBeCalled();
expect(diffB).not.toBeCalled();
});
it('should do deep diffs of Objects by default', () => {
expect(diffRawProperties(
null,
{a: [1], b: {k: [3,4]}, c: {k: [4,4]} },
{a: [2], b: {k: [3,4]}, c: {k: [4,5]} },
{a: true, b: true, c: true}
)).toEqual({a: [2], c: {k: [4,5]}});
});
it('should work with undefined styles', () => {
expect(diffRawProperties(
null,
{a: 1, c: 3},
undefined,
{a: true, b: true}
)).toEqual({a: null});
expect(diffRawProperties(
null,
undefined,
{a: 1, c: 3},
{a: true, b: true}
)).toEqual({a: 1});
expect(diffRawProperties(
null,
undefined,
undefined,
{a: true, b: true}
)).toEqual(null);
});
it('should work with empty styles', () => {
expect(diffRawProperties(
null,
{a: 1, c: 3},
{},
{a: true, b: true}
)).toEqual({a: null});
expect(diffRawProperties(
null,
{},
{a: 1, c: 3},
{a: true, b: true}
)).toEqual({a: 1});
expect(diffRawProperties(
null,
{},
{},
{a: true, b: true}
)).toEqual(null);
});
// Function properties are just markers to native that events should be sent.
it('should convert functions to booleans', () => {
// Note that if the property changes from one function to another, we don't
// need to send an update.
expect(diffRawProperties(
null,
{a: function() { return 1; }, b: function() { return 2; }, c: 3},
{b: function() { return 9; }, c: function() { return 3; }, },
{a: true, b: true, c: true}
)).toEqual({a: null, c: true});
});
});
+14 -16
View File
@@ -11,6 +11,8 @@
*/
'use strict';
var deepDiffer = require('deepDiffer');
/**
* diffRawProperties takes two sets of props and a set of valid attributes
* and write to updatePayload the values that changed or were deleted
@@ -33,6 +35,7 @@ function diffRawProperties(
var prevProp;
var isScalar;
var shouldUpdate;
var differ;
if (nextProps) {
for (var propKey in nextProps) {
@@ -53,16 +56,11 @@ function diffRawProperties(
}
if (prevProp !== nextProp) {
// If you want a property's diff to be detected, you must configure it
// to be so - *or* it must be a scalar property. For now, we'll allow
// creation with any attribute that is not scalar, but we should
// eventually even reject those unless they are properly configured.
// Scalars and new props are always updated. Objects use deepDiffer by
// default, but can be optimized with custom differs.
differ = validAttributeConfig.diff || deepDiffer;
isScalar = typeof nextProp !== 'object' || nextProp === null;
shouldUpdate = isScalar ||
!prevProp ||
validAttributeConfig.diff &&
validAttributeConfig.diff(prevProp, nextProp);
shouldUpdate = isScalar || !prevProp || differ(prevProp, nextProp);
if (shouldUpdate) {
updatePayload = updatePayload || {};
updatePayload[propKey] = nextProp;
@@ -99,14 +97,14 @@ function diffRawProperties(
if (nextProp === undefined) {
nextProp = null; // null is a sentinel we explicitly send to native
}
// If you want a property's diff to be detected, you must configure it
// to be so - *or* it must be a scalar property. For now, we'll allow
// creation with any attribute that is not scalar, but we should
// eventually even reject those unless they are properly configured.
// Scalars and new props are always updated. Objects use deepDiffer by
// default, but can be optimized with custom differs.
differ = validAttributeConfig.diff || deepDiffer;
isScalar = typeof nextProp !== 'object' || nextProp === null;
shouldUpdate = isScalar && prevProp !== nextProp ||
validAttributeConfig.diff &&
validAttributeConfig.diff(prevProp, nextProp);
shouldUpdate =
isScalar &&
prevProp !== nextProp ||
differ(prevProp, nextProp);
if (shouldUpdate) {
updatePayload = updatePayload || {};
updatePayload[propKey] = nextProp;
+2 -4
View File
@@ -15,7 +15,6 @@ var RCTUIManager = require('NativeModules').UIManager;
var UnimplementedView = require('UnimplementedView');
var createReactNativeComponentClass = require('createReactNativeComponentClass');
var deepDiffer = require('deepDiffer');
var insetsDiffer = require('insetsDiffer');
var pointsDiffer = require('pointsDiffer');
var matricesDiffer = require('matricesDiffer');
@@ -54,9 +53,8 @@ function requireNativeComponent(
viewConfig.uiViewClassName = viewName;
viewConfig.validAttributes = {};
for (var key in nativeProps) {
// TODO: deep diff by default in diffRawProperties instead of setting it here
var differ = TypeToDifferMap[nativeProps[key]] || deepDiffer;
viewConfig.validAttributes[key] = {diff: differ};
var differ = TypeToDifferMap[nativeProps[key]];
viewConfig.validAttributes[key] = differ ? {diff: differ} : true;
}
if (__DEV__) {
wrapperComponent && verifyPropTypes(wrapperComponent, viewConfig);
@@ -79,6 +79,12 @@ var ReactNativeMount = {
_instancesByContainerID: {},
// these two functions are needed by React Devtools
findNodeHandle: require('findNodeHandle'),
nativeTagToRootNodeID: function (nativeTag: number): string {
return ReactNativeTagHandles.tagToRootNodeID[nativeTag];
},
/**
* @param {ReactComponent} instance Instance to render.
* @param {containerTag} containerView Handle to native view tag
@@ -16,7 +16,12 @@ var ReactPropTypes = require('ReactPropTypes');
var TransformPropTypes = {
transform: ReactPropTypes.arrayOf(
ReactPropTypes.oneOfType([
ReactPropTypes.shape({perspective: ReactPropTypes.number}),
ReactPropTypes.shape({rotate: ReactPropTypes.string}),
ReactPropTypes.shape({rotateX: ReactPropTypes.string}),
ReactPropTypes.shape({rotateY: ReactPropTypes.string}),
ReactPropTypes.shape({rotateZ: ReactPropTypes.string}),
ReactPropTypes.shape({scale: ReactPropTypes.number}),
ReactPropTypes.shape({scaleX: ReactPropTypes.number}),
ReactPropTypes.shape({scaleY: ReactPropTypes.number}),
ReactPropTypes.shape({translateX: ReactPropTypes.number}),
+13
View File
@@ -58,7 +58,17 @@ function _precomputeTransforms(style: Object): Object {
case 'matrix':
MatrixMath.multiplyInto(result, result, value);
break;
case 'perspective':
_multiplyTransform(result, MatrixMath.reusePerspectiveCommand, [value]);
break;
case 'rotateX':
_multiplyTransform(result, MatrixMath.reuseRotateXCommand, [_convertToRadians(value)]);
break;
case 'rotateY':
_multiplyTransform(result, MatrixMath.reuseRotateYCommand, [_convertToRadians(value)]);
break;
case 'rotate':
case 'rotateZ':
_multiplyTransform(result, MatrixMath.reuseRotateZCommand, [_convertToRadians(value)]);
break;
case 'scale':
@@ -156,6 +166,9 @@ function _validateTransform(key, value, transformation) {
break;
case 'translate':
break;
case 'rotateX':
case 'rotateY':
case 'rotateZ':
case 'rotate':
invariant(
typeof value === 'string',
-24
View File
@@ -9,32 +9,8 @@
#import "RCTShadowRawText.h"
#import "RCTUIManager.h"
@implementation RCTShadowRawText
- (instancetype)init
{
if ((self = [super init])) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(contentSizeMultiplierDidChange:)
name:RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification
object:nil];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)contentSizeMultiplierDidChange:(NSNotification *)note
{
[self dirtyLayout];
[self dirtyText];
}
- (void)setText:(NSString *)text
{
if (_text != text) {
-2
View File
@@ -30,8 +30,6 @@ extern NSString *const RCTReactTagAttributeName;
@property (nonatomic, strong) UIColor *textDecorationColor;
@property (nonatomic, assign) NSUnderlineStyle textDecorationStyle;
@property (nonatomic, assign) RCTTextDecorationLineType textDecorationLine;
@property (nonatomic, assign) CGFloat fontSizeMultiplier;
@property (nonatomic, assign) BOOL allowFontScaling;
- (void)recomputeText;
+3 -46
View File
@@ -9,9 +9,6 @@
#import "RCTShadowText.h"
#import "RCTAccessibilityManager.h"
#import "RCTUIManager.h"
#import "RCTBridge.h"
#import "RCTConvert.h"
#import "RCTLog.h"
#import "RCTShadowRawText.h"
@@ -54,31 +51,16 @@ static css_dim_t RCTMeasure(void *context, float width)
_letterSpacing = NAN;
_isHighlighted = NO;
_textDecorationStyle = NSUnderlineStyleSingle;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(contentSizeMultiplierDidChange:)
name:RCTUIManagerWillUpdateViewsDueToContentSizeMultiplierChangeNotification
object:nil];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (NSString *)description
{
NSString *superDescription = super.description;
return [[superDescription substringToIndex:superDescription.length - 1] stringByAppendingFormat:@"; text: %@>", [self attributedString].string];
}
- (void)contentSizeMultiplierDidChange:(NSNotification *)note
{
[self dirtyLayout];
[self dirtyText];
}
- (NSDictionary *)processUpdatedProperties:(NSMutableSet *)applierBlocks
parentProperties:(NSDictionary *)parentProperties
{
@@ -208,9 +190,7 @@ static css_dim_t RCTMeasure(void *context, float width)
[self _addAttribute:NSBackgroundColorAttributeName withValue:self.backgroundColor toAttributedString:attributedString];
}
UIFont *font = [RCTConvert UIFont:nil withFamily:fontFamily
size:fontSize weight:fontWeight style:fontStyle
scaleMultiplier:(_allowFontScaling && _fontSizeMultiplier > 0.0 ? _fontSizeMultiplier : 1.0)];
UIFont *font = [RCTConvert UIFont:nil withFamily:fontFamily size:fontSize weight:fontWeight style:fontStyle];
[self _addAttribute:NSFontAttributeName withValue:font toAttributedString:attributedString];
[self _addAttribute:NSKernAttributeName withValue:letterSpacing toAttributedString:attributedString];
[self _addAttribute:RCTReactTagAttributeName withValue:self.reactTag toAttributedString:attributedString];
@@ -267,9 +247,8 @@ static css_dim_t RCTMeasure(void *context, float width)
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = _textAlign;
paragraphStyle.baseWritingDirection = _writingDirection;
CGFloat lineHeight = round(_lineHeight * self.fontSizeMultiplier);
paragraphStyle.minimumLineHeight = lineHeight;
paragraphStyle.maximumLineHeight = lineHeight;
paragraphStyle.minimumLineHeight = _lineHeight;
paragraphStyle.maximumLineHeight = _lineHeight;
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:(NSRange){0, attributedString.length}];
@@ -342,26 +321,4 @@ RCT_TEXT_PROPERTY(TextDecorationLine, _textDecorationLine, RCTTextDecorationLine
RCT_TEXT_PROPERTY(TextDecorationStyle, _textDecorationStyle, NSUnderlineStyle);
RCT_TEXT_PROPERTY(WritingDirection, _writingDirection, NSWritingDirection)
- (void)setAllowFontScaling:(BOOL)allowFontScaling
{
_allowFontScaling = allowFontScaling;
for (RCTShadowView *child in [self reactSubviews]) {
if ([child isKindOfClass:[RCTShadowText class]]) {
[(RCTShadowText *)child setAllowFontScaling:allowFontScaling];
}
}
[self dirtyText];
}
- (void)setFontSizeMultiplier:(CGFloat)fontSizeMultiplier
{
_fontSizeMultiplier = fontSizeMultiplier;
for (RCTShadowView *child in [self reactSubviews]) {
if ([child isKindOfClass:[RCTShadowText class]]) {
[(RCTShadowText *)child setFontSizeMultiplier:fontSizeMultiplier];
}
}
[self dirtyText];
}
@end
-3
View File
@@ -9,7 +9,6 @@
#import "RCTTextManager.h"
#import "RCTAccessibilityManager.h"
#import "RCTAssert.h"
#import "RCTConvert.h"
#import "RCTLog.h"
@@ -50,7 +49,6 @@ RCT_EXPORT_SHADOW_PROPERTY(textDecorationStyle, NSUnderlineStyle)
RCT_EXPORT_SHADOW_PROPERTY(textDecorationColor, UIColor)
RCT_EXPORT_SHADOW_PROPERTY(textDecorationLine, RCTTextDecorationLineType)
RCT_EXPORT_SHADOW_PROPERTY(writingDirection, NSWritingDirection)
RCT_EXPORT_SHADOW_PROPERTY(allowFontScaling, BOOL)
- (RCTViewManagerUIBlock)uiBlockToAmendWithShadowViewRegistry:(RCTSparseArray *)shadowViewRegistry
{
@@ -71,7 +69,6 @@ RCT_EXPORT_SHADOW_PROPERTY(allowFontScaling, BOOL)
RCTAssert([shadowView isTextDirty], @"Don't process any nodes that don't have dirty text");
if ([shadowView isKindOfClass:[RCTShadowText class]]) {
[(RCTShadowText *)shadowView setFontSizeMultiplier:self.bridge.accessibilityManager.multiplier];
[(RCTShadowText *)shadowView recomputeText];
} else if ([shadowView isKindOfClass:[RCTShadowRawText class]]) {
RCTLogError(@"Raw text cannot be used outside of a <Text> tag. Not rendering string: '%@'",
+2 -15
View File
@@ -30,7 +30,6 @@ var viewConfig = {
validAttributes: merge(ReactNativeViewAttributes.UIView, {
isHighlighted: true,
numberOfLines: true,
allowFontScaling: true,
}),
uiViewClassName: 'RCTText',
};
@@ -100,27 +99,16 @@ var Text = React.createClass({
*
* {nativeEvent: {layout: {x, y, width, height}}}.
*/
onLayout: React.PropTypes.func,
/**
* Specifies should fonts scale to respect Text Size accessibility setting.
*/
allowFontScaling: React.PropTypes.bool,
onLayout: React.PropTypes.func,
},
viewConfig: viewConfig,
getInitialState: function(): Object {
getInitialState: function() {
return merge(this.touchableGetInitialState(), {
isHighlighted: false,
});
},
getDefaultProps: function(): Object {
return {
numberOfLines: 0,
allowFontScaling: true,
};
},
onStartShouldSetResponder: function(): bool {
var shouldSetFromProps = this.props.onStartShouldSetResponder &&
@@ -243,7 +231,6 @@ if (Platform.OS === 'android') {
RCTVirtualText = createReactNativeComponentClass({
validAttributes: merge(ReactNativeViewAttributes.UIView, {
isHighlighted: true,
allowFontScaling: false,
}),
uiViewClassName: 'RCTVirtualText',
});
+4
View File
@@ -65,6 +65,10 @@ var MatrixMath = {
matrixCommand[10] = z;
},
reusePerspectiveCommand: function(matrixCommand, p) {
matrixCommand[11] = -1 / p;
},
reuseScaleXCommand(matrixCommand, factor) {
matrixCommand[0] = factor;
},
+5 -7
View File
@@ -97,7 +97,7 @@ RCT_EXPORT_MODULE()
{
__block NSError *initError;
dispatch_semaphore_t s = dispatch_semaphore_create(0);
[self sendMessage:@{@"method": @"prepareJSRuntime"} context:nil waitForReply:^(NSError *error, NSDictionary *reply) {
[self sendMessage:@{@"method": @"prepareJSRuntime"} waitForReply:^(NSError *error, NSDictionary *reply) {
initError = error;
dispatch_semaphore_signal(s);
}];
@@ -126,7 +126,7 @@ RCT_EXPORT_MODULE()
RCTLogError(@"WebSocket connection failed with error %@", error);
}
- (void)sendMessage:(NSDictionary *)message context:(NSNumber *)executorID waitForReply:(RCTWSMessageCallback)callback
- (void)sendMessage:(NSDictionary *)message waitForReply:(RCTWSMessageCallback)callback
{
static NSUInteger lastID = 10000;
@@ -137,8 +137,6 @@ RCT_EXPORT_MODULE()
}];
callback(error, nil);
return;
} else if (executorID && ![RCTGetExecutorID(self) isEqualToNumber:executorID]) {
return;
}
NSNumber *expectedID = @(lastID++);
@@ -152,12 +150,12 @@ RCT_EXPORT_MODULE()
- (void)executeApplicationScript:(NSString *)script sourceURL:(NSURL *)URL onComplete:(RCTJavaScriptCompleteBlock)onComplete
{
NSDictionary *message = @{@"method": @"executeApplicationScript", @"url": [URL absoluteString], @"inject": _injectedObjects};
[self sendMessage:message context:nil waitForReply:^(NSError *error, NSDictionary *reply) {
[self sendMessage:message waitForReply:^(NSError *error, NSDictionary *reply) {
onComplete(error);
}];
}
- (void)executeJSCall:(NSString *)name method:(NSString *)method arguments:(NSArray *)arguments context:(NSNumber *)executorID callback:(RCTJavaScriptCallback)onComplete
- (void)executeJSCall:(NSString *)name method:(NSString *)method arguments:(NSArray *)arguments callback:(RCTJavaScriptCallback)onComplete
{
RCTAssert(onComplete != nil, @"callback was missing for exec JS call");
NSDictionary *message = @{
@@ -166,7 +164,7 @@ RCT_EXPORT_MODULE()
@"moduleMethod": method,
@"arguments": arguments
};
[self sendMessage:message context:executorID waitForReply:^(NSError *socketError, NSDictionary *reply) {
[self sendMessage:message waitForReply:^(NSError *socketError, NSDictionary *reply) {
if (socketError) {
onComplete(nil, socketError);
return;