Convert react-native-github/Libraries to let/const

Reviewed By: sahrens

Differential Revision: D7956042

fbshipit-source-id: 221851aa311f3cdd6326497352b366048db0a1bb
This commit is contained in:
Eli White 2018-05-10 15:44:52 -07:00 коммит произвёл Facebook Github Bot
Родитель 266016c521
Коммит 8f5ebe5952
114 изменённых файлов: 1017 добавлений и 1035 удалений

Просмотреть файл

@ -9,16 +9,16 @@
// TODO: Move this into an ART mode called "serialized" or something // TODO: Move this into an ART mode called "serialized" or something
var Class = require('art/core/class.js'); const Class = require('art/core/class.js');
var Path = require('art/core/path.js'); const Path = require('art/core/path.js');
var MOVE_TO = 0; const MOVE_TO = 0;
var CLOSE = 1; const CLOSE = 1;
var LINE_TO = 2; const LINE_TO = 2;
var CURVE_TO = 3; const CURVE_TO = 3;
var ARC = 4; const ARC = 4;
var SerializablePath = Class(Path, { const SerializablePath = Class(Path, {
initialize: function(path) { initialize: function(path) {
this.reset(); this.reset();

Просмотреть файл

@ -7,17 +7,17 @@
*/ */
'use strict'; 'use strict';
var Color = require('art/core/color'); const Color = require('art/core/color');
var Path = require('ARTSerializablePath'); const Path = require('ARTSerializablePath');
var Transform = require('art/core/transform'); const Transform = require('art/core/transform');
var React = require('React'); const React = require('React');
var PropTypes = require('prop-types'); const PropTypes = require('prop-types');
var ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
var createReactNativeComponentClass = require('createReactNativeComponentClass'); const createReactNativeComponentClass = require('createReactNativeComponentClass');
var merge = require('merge'); const merge = require('merge');
var invariant = require('fbjs/lib/invariant'); const invariant = require('fbjs/lib/invariant');
// Diff Helpers // Diff Helpers
@ -28,7 +28,7 @@ function arrayDiffer(a, b) {
if (a.length !== b.length) { if (a.length !== b.length) {
return true; return true;
} }
for (var i = 0; i < a.length; i++) { for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) { if (a[i] !== b[i]) {
return true; return true;
} }
@ -62,22 +62,22 @@ function fontAndLinesDiffer(a, b) {
// Native Attributes // Native Attributes
var SurfaceViewAttributes = merge(ReactNativeViewAttributes.UIView, { const SurfaceViewAttributes = merge(ReactNativeViewAttributes.UIView, {
// This should contain pixel information such as width, height and // This should contain pixel information such as width, height and
// resolution to know what kind of buffer needs to be allocated. // resolution to know what kind of buffer needs to be allocated.
// Currently we rely on UIViews and style to figure that out. // Currently we rely on UIViews and style to figure that out.
}); });
var NodeAttributes = { const NodeAttributes = {
transform: { diff: arrayDiffer }, transform: { diff: arrayDiffer },
opacity: true, opacity: true,
}; };
var GroupAttributes = merge(NodeAttributes, { const GroupAttributes = merge(NodeAttributes, {
clipping: { diff: arrayDiffer } clipping: { diff: arrayDiffer }
}); });
var RenderableAttributes = merge(NodeAttributes, { const RenderableAttributes = merge(NodeAttributes, {
fill: { diff: arrayDiffer }, fill: { diff: arrayDiffer },
stroke: { diff: arrayDiffer }, stroke: { diff: arrayDiffer },
strokeWidth: true, strokeWidth: true,
@ -86,11 +86,11 @@ var RenderableAttributes = merge(NodeAttributes, {
strokeDash: { diff: arrayDiffer }, strokeDash: { diff: arrayDiffer },
}); });
var ShapeAttributes = merge(RenderableAttributes, { const ShapeAttributes = merge(RenderableAttributes, {
d: { diff: arrayDiffer }, d: { diff: arrayDiffer },
}); });
var TextAttributes = merge(RenderableAttributes, { const TextAttributes = merge(RenderableAttributes, {
alignment: true, alignment: true,
frame: { diff: fontAndLinesDiffer }, frame: { diff: fontAndLinesDiffer },
path: { diff: arrayDiffer } path: { diff: arrayDiffer }
@ -98,25 +98,25 @@ var TextAttributes = merge(RenderableAttributes, {
// Native Components // Native Components
var NativeSurfaceView = createReactNativeComponentClass('ARTSurfaceView', const NativeSurfaceView = createReactNativeComponentClass('ARTSurfaceView',
() => ({ () => ({
validAttributes: SurfaceViewAttributes, validAttributes: SurfaceViewAttributes,
uiViewClassName: 'ARTSurfaceView', uiViewClassName: 'ARTSurfaceView',
})); }));
var NativeGroup = createReactNativeComponentClass('ARTGroup', const NativeGroup = createReactNativeComponentClass('ARTGroup',
() => ({ () => ({
validAttributes: GroupAttributes, validAttributes: GroupAttributes,
uiViewClassName: 'ARTGroup', uiViewClassName: 'ARTGroup',
})); }));
var NativeShape = createReactNativeComponentClass('ARTShape', const NativeShape = createReactNativeComponentClass('ARTShape',
() => ({ () => ({
validAttributes: ShapeAttributes, validAttributes: ShapeAttributes,
uiViewClassName: 'ARTShape', uiViewClassName: 'ARTShape',
})); }));
var NativeText = createReactNativeComponentClass('ARTText', const NativeText = createReactNativeComponentClass('ARTText',
() => ({ () => ({
validAttributes: TextAttributes, validAttributes: TextAttributes,
uiViewClassName: 'ARTText', uiViewClassName: 'ARTText',
@ -149,9 +149,9 @@ class Surface extends React.Component {
} }
render() { render() {
var props = this.props; const props = this.props;
var w = extractNumber(props.width, 0); const w = extractNumber(props.width, 0);
var h = extractNumber(props.height, 0); const h = extractNumber(props.height, 0);
return ( return (
<NativeSurfaceView style={[props.style, { width: w, height: h }]}> <NativeSurfaceView style={[props.style, { width: w, height: h }]}>
{this.props.children} {this.props.children}
@ -172,12 +172,12 @@ function extractNumber(value, defaultValue) {
return +value; return +value;
} }
var pooledTransform = new Transform(); const pooledTransform = new Transform();
function extractTransform(props) { function extractTransform(props) {
var scaleX = props.scaleX != null ? props.scaleX : const scaleX = props.scaleX != null ? props.scaleX :
props.scale != null ? props.scale : 1; props.scale != null ? props.scale : 1;
var scaleY = props.scaleY != null ? props.scaleY : const scaleY = props.scaleY != null ? props.scaleY :
props.scale != null ? props.scale : 1; props.scale != null ? props.scale : 1;
pooledTransform pooledTransform
@ -219,7 +219,7 @@ class Group extends React.Component {
}; };
render() { render() {
var props = this.props; const props = this.props;
invariant( invariant(
this.context.isInSurface, this.context.isInSurface,
'ART: <Group /> must be a child of a <Surface />' 'ART: <Group /> must be a child of a <Surface />'
@ -236,14 +236,14 @@ class Group extends React.Component {
class ClippingRectangle extends React.Component { class ClippingRectangle extends React.Component {
render() { render() {
var props = this.props; const props = this.props;
var x = extractNumber(props.x, 0); const x = extractNumber(props.x, 0);
var y = extractNumber(props.y, 0); const y = extractNumber(props.y, 0);
var w = extractNumber(props.width, 0); const w = extractNumber(props.width, 0);
var h = extractNumber(props.height, 0); const h = extractNumber(props.height, 0);
var clipping = [x, y, w, h]; const clipping = [x, y, w, h];
// The current clipping API requires x and y to be ignored in the transform // The current clipping API requires x and y to be ignored in the transform
var propsExcludingXAndY = merge(props); const propsExcludingXAndY = merge(props);
delete propsExcludingXAndY.x; delete propsExcludingXAndY.x;
delete propsExcludingXAndY.y; delete propsExcludingXAndY.y;
return ( return (
@ -259,13 +259,13 @@ class ClippingRectangle extends React.Component {
// Renderables // Renderables
var SOLID_COLOR = 0; const SOLID_COLOR = 0;
var LINEAR_GRADIENT = 1; const LINEAR_GRADIENT = 1;
var RADIAL_GRADIENT = 2; const RADIAL_GRADIENT = 2;
var PATTERN = 3; const PATTERN = 3;
function insertColorIntoArray(color, targetArray, atIndex) { function insertColorIntoArray(color, targetArray, atIndex) {
var c = new Color(color); const c = new Color(color);
targetArray[atIndex + 0] = c.red / 255; targetArray[atIndex + 0] = c.red / 255;
targetArray[atIndex + 1] = c.green / 255; targetArray[atIndex + 1] = c.green / 255;
targetArray[atIndex + 2] = c.blue / 255; targetArray[atIndex + 2] = c.blue / 255;
@ -273,14 +273,14 @@ function insertColorIntoArray(color, targetArray, atIndex) {
} }
function insertColorsIntoArray(stops, targetArray, atIndex) { function insertColorsIntoArray(stops, targetArray, atIndex) {
var i = 0; let i = 0;
if ('length' in stops) { if ('length' in stops) {
while (i < stops.length) { while (i < stops.length) {
insertColorIntoArray(stops[i], targetArray, atIndex + i * 4); insertColorIntoArray(stops[i], targetArray, atIndex + i * 4);
i++; i++;
} }
} else { } else {
for (var offset in stops) { for (const offset in stops) {
insertColorIntoArray(stops[offset], targetArray, atIndex + i * 4); insertColorIntoArray(stops[offset], targetArray, atIndex + i * 4);
i++; i++;
} }
@ -289,8 +289,8 @@ function insertColorsIntoArray(stops, targetArray, atIndex) {
} }
function insertOffsetsIntoArray(stops, targetArray, atIndex, multi, reverse) { function insertOffsetsIntoArray(stops, targetArray, atIndex, multi, reverse) {
var offsetNumber; let offsetNumber;
var i = 0; let i = 0;
if ('length' in stops) { if ('length' in stops) {
while (i < stops.length) { while (i < stops.length) {
offsetNumber = i / (stops.length - 1) * multi; offsetNumber = i / (stops.length - 1) * multi;
@ -298,7 +298,7 @@ function insertOffsetsIntoArray(stops, targetArray, atIndex, multi, reverse) {
i++; i++;
} }
} else { } else {
for (var offsetString in stops) { for (const offsetString in stops) {
offsetNumber = (+offsetString) * multi; offsetNumber = (+offsetString) * multi;
targetArray[atIndex + i] = reverse ? 1 - offsetNumber : offsetNumber; targetArray[atIndex + i] = reverse ? 1 - offsetNumber : offsetNumber;
i++; i++;
@ -308,21 +308,21 @@ function insertOffsetsIntoArray(stops, targetArray, atIndex, multi, reverse) {
} }
function insertColorStopsIntoArray(stops, targetArray, atIndex) { function insertColorStopsIntoArray(stops, targetArray, atIndex) {
var lastIndex = insertColorsIntoArray(stops, targetArray, atIndex); const lastIndex = insertColorsIntoArray(stops, targetArray, atIndex);
insertOffsetsIntoArray(stops, targetArray, lastIndex, 1, false); insertOffsetsIntoArray(stops, targetArray, lastIndex, 1, false);
} }
function insertDoubleColorStopsIntoArray(stops, targetArray, atIndex) { function insertDoubleColorStopsIntoArray(stops, targetArray, atIndex) {
var lastIndex = insertColorsIntoArray(stops, targetArray, atIndex); let lastIndex = insertColorsIntoArray(stops, targetArray, atIndex);
lastIndex = insertColorsIntoArray(stops, targetArray, lastIndex); lastIndex = insertColorsIntoArray(stops, targetArray, lastIndex);
lastIndex = insertOffsetsIntoArray(stops, targetArray, lastIndex, 0.5, false); lastIndex = insertOffsetsIntoArray(stops, targetArray, lastIndex, 0.5, false);
insertOffsetsIntoArray(stops, targetArray, lastIndex, 0.5, true); insertOffsetsIntoArray(stops, targetArray, lastIndex, 0.5, true);
} }
function applyBoundingBoxToBrushData(brushData, props) { function applyBoundingBoxToBrushData(brushData, props) {
var type = brushData[0]; const type = brushData[0];
var width = +props.width; const width = +props.width;
var height = +props.height; const height = +props.height;
if (type === LINEAR_GRADIENT) { if (type === LINEAR_GRADIENT) {
brushData[1] *= width; brushData[1] *= width;
brushData[2] *= height; brushData[2] *= height;
@ -356,7 +356,7 @@ function extractBrush(colorOrBrush, props) {
} }
return colorOrBrush._brush; return colorOrBrush._brush;
} }
var c = new Color(colorOrBrush); const c = new Color(colorOrBrush);
return [SOLID_COLOR, c.red / 255, c.green / 255, c.blue / 255, c.alpha]; return [SOLID_COLOR, c.red / 255, c.green / 255, c.blue / 255, c.alpha];
} }
@ -364,7 +364,7 @@ function extractColor(color) {
if (color == null) { if (color == null) {
return null; return null;
} }
var c = new Color(color); const c = new Color(color);
return [c.red / 255, c.green / 255, c.blue / 255, c.alpha]; return [c.red / 255, c.green / 255, c.blue / 255, c.alpha];
} }
@ -391,9 +391,9 @@ function extractStrokeJoin(strokeJoin) {
class Shape extends React.Component { class Shape extends React.Component {
render() { render() {
var props = this.props; const props = this.props;
var path = props.d || childrenAsString(props.children); const path = props.d || childrenAsString(props.children);
var d = (path instanceof Path ? path : new Path(path)).toJSON(); const d = (path instanceof Path ? path : new Path(path)).toJSON();
return ( return (
<NativeShape <NativeShape
fill={extractBrush(props.fill, props)} fill={extractBrush(props.fill, props)}
@ -413,10 +413,10 @@ class Shape extends React.Component {
// Text // Text
var cachedFontObjectsFromString = {}; const cachedFontObjectsFromString = {};
var fontFamilyPrefix = /^[\s"']*/; const fontFamilyPrefix = /^[\s"']*/;
var fontFamilySuffix = /[\s"']*$/; const fontFamilySuffix = /[\s"']*$/;
function extractSingleFontFamily(fontFamilyString) { function extractSingleFontFamily(fontFamilyString) {
// ART on the web allows for multiple font-families to be specified. // ART on the web allows for multiple font-families to be specified.
@ -431,15 +431,15 @@ function parseFontString(font) {
if (cachedFontObjectsFromString.hasOwnProperty(font)) { if (cachedFontObjectsFromString.hasOwnProperty(font)) {
return cachedFontObjectsFromString[font]; return cachedFontObjectsFromString[font];
} }
var regexp = /^\s*((?:(?:normal|bold|italic)\s+)*)(?:(\d+(?:\.\d+)?)[ptexm\%]*(?:\s*\/.*?)?\s+)?\s*\"?([^\"]*)/i; const regexp = /^\s*((?:(?:normal|bold|italic)\s+)*)(?:(\d+(?:\.\d+)?)[ptexm\%]*(?:\s*\/.*?)?\s+)?\s*\"?([^\"]*)/i;
var match = regexp.exec(font); const match = regexp.exec(font);
if (!match) { if (!match) {
return null; return null;
} }
var fontFamily = extractSingleFontFamily(match[3]); const fontFamily = extractSingleFontFamily(match[3]);
var fontSize = +match[2] || 12; const fontSize = +match[2] || 12;
var isBold = /bold/.exec(match[1]); const isBold = /bold/.exec(match[1]);
var isItalic = /italic/.exec(match[1]); const isItalic = /italic/.exec(match[1]);
cachedFontObjectsFromString[font] = { cachedFontObjectsFromString[font] = {
fontFamily: fontFamily, fontFamily: fontFamily,
fontSize: fontSize, fontSize: fontSize,
@ -456,9 +456,9 @@ function extractFont(font) {
if (typeof font === 'string') { if (typeof font === 'string') {
return parseFontString(font); return parseFontString(font);
} }
var fontFamily = extractSingleFontFamily(font.fontFamily); const fontFamily = extractSingleFontFamily(font.fontFamily);
var fontSize = +font.fontSize || 12; const fontSize = +font.fontSize || 12;
var fontWeight = font.fontWeight != null ? font.fontWeight.toString() : '400'; const fontWeight = font.fontWeight != null ? font.fontWeight.toString() : '400';
return { return {
// Normalize // Normalize
fontFamily: fontFamily, fontFamily: fontFamily,
@ -468,7 +468,7 @@ function extractFont(font) {
}; };
} }
var newLine = /\n/g; const newLine = /\n/g;
function extractFontAndLines(font, text) { function extractFontAndLines(font, text) {
return { font: extractFont(font), lines: text.split(newLine) }; return { font: extractFont(font), lines: text.split(newLine) };
} }
@ -486,10 +486,10 @@ function extractAlignment(alignment) {
class Text extends React.Component { class Text extends React.Component {
render() { render() {
var props = this.props; const props = this.props;
var path = props.path; const path = props.path;
var textPath = path ? (path instanceof Path ? path : new Path(path)).toJSON() : null; const textPath = path ? (path instanceof Path ? path : new Path(path)).toJSON() : null;
var textFrame = extractFontAndLines( const textFrame = extractFontAndLines(
props.font, props.font,
childrenAsString(props.children) childrenAsString(props.children)
); );
@ -515,14 +515,14 @@ class Text extends React.Component {
// Declarative fill type objects - API design not finalized // Declarative fill type objects - API design not finalized
function LinearGradient(stops, x1, y1, x2, y2) { function LinearGradient(stops, x1, y1, x2, y2) {
var type = LINEAR_GRADIENT; const type = LINEAR_GRADIENT;
if (arguments.length < 5) { if (arguments.length < 5) {
var angle = ((x1 == null) ? 270 : x1) * Math.PI / 180; const angle = ((x1 == null) ? 270 : x1) * Math.PI / 180;
var x = Math.cos(angle); let x = Math.cos(angle);
var y = -Math.sin(angle); let y = -Math.sin(angle);
var l = (Math.abs(x) + Math.abs(y)) / 2; const l = (Math.abs(x) + Math.abs(y)) / 2;
x *= l; y *= l; x *= l; y *= l;
@ -535,7 +535,7 @@ function LinearGradient(stops, x1, y1, x2, y2) {
this._bb = false; this._bb = false;
} }
var brushData = [type, +x1, +y1, +x2, +y2]; const brushData = [type, +x1, +y1, +x2, +y2];
insertColorStopsIntoArray(stops, brushData, 5); insertColorStopsIntoArray(stops, brushData, 5);
this._brush = brushData; this._brush = brushData;
} }
@ -562,7 +562,7 @@ function RadialGradient(stops, fx, fy, rx, ry, cx, cy) {
// To simulate this we render the gradient twice as large and add double // To simulate this we render the gradient twice as large and add double
// color stops. Ideally this API would become more restrictive so that this // color stops. Ideally this API would become more restrictive so that this
// extra work isn't needed. // extra work isn't needed.
var brushData = [RADIAL_GRADIENT, +fx, +fy, +rx * 2, +ry * 2, +cx, +cy]; const brushData = [RADIAL_GRADIENT, +fx, +fy, +rx * 2, +ry * 2, +cx, +cy];
insertDoubleColorStopsIntoArray(stops, brushData, 7); insertDoubleColorStopsIntoArray(stops, brushData, 7);
this._brush = brushData; this._brush = brushData;
} }
@ -571,7 +571,7 @@ function Pattern(url, width, height, left, top) {
this._brush = [PATTERN, url, +left || 0, +top || 0, +width, +height]; this._brush = [PATTERN, url, +left || 0, +top || 0, +width, +height];
} }
var ReactART = { const ReactART = {
LinearGradient: LinearGradient, LinearGradient: LinearGradient,
RadialGradient: RadialGradient, RadialGradient: RadialGradient,
Pattern: Pattern, Pattern: Pattern,

Просмотреть файл

@ -68,7 +68,7 @@ class AlertAndroid {
buttons?: Buttons, buttons?: Buttons,
options?: Options, options?: Options,
): void { ): void {
var config = { let config = {
title: title || '', title: title || '',
message: message || '', message: message || '',
}; };
@ -78,10 +78,10 @@ class AlertAndroid {
} }
// At most three buttons (neutral, negative, positive). Ignore rest. // At most three buttons (neutral, negative, positive). Ignore rest.
// The text 'OK' should be probably localized. iOS Alert does that in native. // The text 'OK' should be probably localized. iOS Alert does that in native.
var validButtons: Buttons = buttons ? buttons.slice(0, 3) : [{text: 'OK'}]; const validButtons: Buttons = buttons ? buttons.slice(0, 3) : [{text: 'OK'}];
var buttonPositive = validButtons.pop(); const buttonPositive = validButtons.pop();
var buttonNegative = validButtons.pop(); const buttonNegative = validButtons.pop();
var buttonNeutral = validButtons.pop(); const buttonNeutral = validButtons.pop();
if (buttonNeutral) { if (buttonNeutral) {
config = {...config, buttonNeutral: buttonNeutral.text || '' }; config = {...config, buttonNeutral: buttonNeutral.text || '' };
} }

Просмотреть файл

@ -9,7 +9,7 @@
*/ */
'use strict'; 'use strict';
var RCTAlertManager = require('NativeModules').AlertManager; const RCTAlertManager = require('NativeModules').AlertManager;
/** /**
* An Alert button type * An Alert button type
@ -118,7 +118,7 @@ class AlertIOS {
'signature. The current signature is AlertIOS.prompt(title, message, callbackOrButtons, type, defaultValue, ' + 'signature. The current signature is AlertIOS.prompt(title, message, callbackOrButtons, type, defaultValue, ' +
'keyboardType) and the old syntax will be removed in a future version.'); 'keyboardType) and the old syntax will be removed in a future version.');
var callback = type; const callback = type;
RCTAlertManager.alertWithArgs({ RCTAlertManager.alertWithArgs({
title: title || '', title: title || '',
type: 'plain-text', type: 'plain-text',
@ -129,10 +129,10 @@ class AlertIOS {
return; return;
} }
var callbacks = []; let callbacks = [];
var buttons = []; const buttons = [];
var cancelButtonKey; let cancelButtonKey;
var destructiveButtonKey; let destructiveButtonKey;
if (typeof callbackOrButtons === 'function') { if (typeof callbackOrButtons === 'function') {
callbacks = [callbackOrButtons]; callbacks = [callbackOrButtons];
} }
@ -145,7 +145,7 @@ class AlertIOS {
destructiveButtonKey = String(index); destructiveButtonKey = String(index);
} }
if (btn.text || index < (callbackOrButtons || []).length - 1) { if (btn.text || index < (callbackOrButtons || []).length - 1) {
var btnDef = {}; const btnDef = {};
btnDef[index] = btn.text || ''; btnDef[index] = btn.text || '';
buttons.push(btnDef); buttons.push(btnDef);
} }
@ -162,7 +162,7 @@ class AlertIOS {
destructiveButtonKey, destructiveButtonKey,
keyboardType, keyboardType,
}, (id, value) => { }, (id, value) => {
var cb = callbacks[id]; const cb = callbacks[id];
cb && cb(value); cb && cb(value);
}); });
} }

Просмотреть файл

@ -7,7 +7,7 @@
*/ */
'use strict'; 'use strict';
var NativeModules = require('NativeModules'); const NativeModules = require('NativeModules');
function emptyCallback() {} function emptyCallback() {}

Просмотреть файл

@ -8,6 +8,6 @@
*/ */
'use strict'; 'use strict';
var RCTAlertManager = require('NativeModules').AlertManager; const RCTAlertManager = require('NativeModules').AlertManager;
module.exports = RCTAlertManager; module.exports = RCTAlertManager;

Просмотреть файл

@ -8,7 +8,7 @@
*/ */
'use strict'; 'use strict';
var AnimatedImplementation = require('AnimatedImplementation'); const AnimatedImplementation = require('AnimatedImplementation');
module.exports = { module.exports = {
...AnimatedImplementation, ...AnimatedImplementation,

Просмотреть файл

@ -208,7 +208,7 @@ function validateTransform(configs: Array<Object>): void {
} }
function validateStyles(styles: Object): void { function validateStyles(styles: Object): void {
for (var key in styles) { for (const key in styles) {
if (!STYLES_WHITELIST.hasOwnProperty(key)) { if (!STYLES_WHITELIST.hasOwnProperty(key)) {
throw new Error( throw new Error(
`Style property '${key}' is not supported by native animated module`, `Style property '${key}' is not supported by native animated module`,
@ -218,7 +218,7 @@ function validateStyles(styles: Object): void {
} }
function validateInterpolation(config: Object): void { function validateInterpolation(config: Object): void {
for (var key in config) { for (const key in config) {
if (!SUPPORTED_INTERPOLATION_PARAMS.hasOwnProperty(key)) { if (!SUPPORTED_INTERPOLATION_PARAMS.hasOwnProperty(key)) {
throw new Error( throw new Error(
`Interpolation property '${key}' is not supported by native animated module`, `Interpolation property '${key}' is not supported by native animated module`,

Просмотреть файл

@ -77,11 +77,11 @@ function fromBouncinessAndSpeed(
} }
} }
var b = normalize(bounciness / 1.7, 0, 20); let b = normalize(bounciness / 1.7, 0, 20);
b = projectNormal(b, 0, 0.8); b = projectNormal(b, 0, 0.8);
var s = normalize(speed / 1.7, 0, 20); const s = normalize(speed / 1.7, 0, 20);
var bouncyTension = projectNormal(s, 0.5, 200); const bouncyTension = projectNormal(s, 0.5, 200);
var bouncyFriction = quadraticOutInterpolation( const bouncyFriction = quadraticOutInterpolation(
b, b,
b3Nobounce(bouncyTension), b3Nobounce(bouncyTension),
0.01 0.01

Просмотреть файл

@ -8,7 +8,7 @@
*/ */
'use strict'; 'use strict';
var Animated = require('Animated'); let Animated = require('Animated');
describe('Animated tests', () => { describe('Animated tests', () => {
beforeEach(() => { beforeEach(() => {
jest.resetModules(); jest.resetModules();
@ -17,11 +17,11 @@ describe('Animated tests', () => {
describe('Animated', () => { describe('Animated', () => {
it('works end to end', () => { it('works end to end', () => {
var anim = new Animated.Value(0); const anim = new Animated.Value(0);
var callback = jest.fn(); const callback = jest.fn();
var node = new Animated.__PropsOnlyForTests({ const node = new Animated.__PropsOnlyForTests({
style: { style: {
backgroundColor: 'red', backgroundColor: 'red',
opacity: anim, opacity: anim,
@ -83,10 +83,10 @@ describe('Animated tests', () => {
}); });
it('does not detach on updates', () => { it('does not detach on updates', () => {
var anim = new Animated.Value(0); const anim = new Animated.Value(0);
anim.__detach = jest.fn(); anim.__detach = jest.fn();
var c = new Animated.View(); const c = new Animated.View();
c.props = { c.props = {
style: { style: {
opacity: anim, opacity: anim,
@ -109,10 +109,10 @@ describe('Animated tests', () => {
it('stops animation when detached', () => { it('stops animation when detached', () => {
var anim = new Animated.Value(0); const anim = new Animated.Value(0);
var callback = jest.fn(); const callback = jest.fn();
var c = new Animated.View(); const c = new Animated.View();
c.props = { c.props = {
style: { style: {
opacity: anim, opacity: anim,
@ -129,31 +129,31 @@ describe('Animated tests', () => {
}); });
it('triggers callback when spring is at rest', () => { it('triggers callback when spring is at rest', () => {
var anim = new Animated.Value(0); const anim = new Animated.Value(0);
var callback = jest.fn(); const callback = jest.fn();
Animated.spring(anim, {toValue: 0, velocity: 0}).start(callback); Animated.spring(anim, {toValue: 0, velocity: 0}).start(callback);
expect(callback).toBeCalled(); expect(callback).toBeCalled();
}); });
it('send toValue when an underdamped spring stops', () => { it('send toValue when an underdamped spring stops', () => {
var anim = new Animated.Value(0); const anim = new Animated.Value(0);
var listener = jest.fn(); const listener = jest.fn();
anim.addListener(listener); anim.addListener(listener);
Animated.spring(anim, {toValue: 15}).start(); Animated.spring(anim, {toValue: 15}).start();
jest.runAllTimers(); jest.runAllTimers();
var lastValue = listener.mock.calls[listener.mock.calls.length - 2][0].value; const lastValue = listener.mock.calls[listener.mock.calls.length - 2][0].value;
expect(lastValue).not.toBe(15); expect(lastValue).not.toBe(15);
expect(lastValue).toBeCloseTo(15); expect(lastValue).toBeCloseTo(15);
expect(anim.__getValue()).toBe(15); expect(anim.__getValue()).toBe(15);
}); });
it('send toValue when a critically damped spring stops', () => { it('send toValue when a critically damped spring stops', () => {
var anim = new Animated.Value(0); const anim = new Animated.Value(0);
var listener = jest.fn(); const listener = jest.fn();
anim.addListener(listener); anim.addListener(listener);
Animated.spring(anim, {stiffness: 8000, damping: 2000, toValue: 15}).start(); Animated.spring(anim, {stiffness: 8000, damping: 2000, toValue: 15}).start();
jest.runAllTimers(); jest.runAllTimers();
var lastValue = listener.mock.calls[listener.mock.calls.length - 2][0].value; const lastValue = listener.mock.calls[listener.mock.calls.length - 2][0].value;
expect(lastValue).not.toBe(15); expect(lastValue).not.toBe(15);
expect(lastValue).toBeCloseTo(15); expect(lastValue).toBeCloseTo(15);
expect(anim.__getValue()).toBe(15); expect(anim.__getValue()).toBe(15);
@ -168,17 +168,17 @@ describe('Animated tests', () => {
describe('Animated Sequence', () => { describe('Animated Sequence', () => {
it('works with an empty sequence', () => { it('works with an empty sequence', () => {
var cb = jest.fn(); const cb = jest.fn();
Animated.sequence([]).start(cb); Animated.sequence([]).start(cb);
expect(cb).toBeCalledWith({finished: true}); expect(cb).toBeCalledWith({finished: true});
}); });
it('sequences well', () => { it('sequences well', () => {
var anim1 = {start: jest.fn()}; const anim1 = {start: jest.fn()};
var anim2 = {start: jest.fn()}; const anim2 = {start: jest.fn()};
var cb = jest.fn(); const cb = jest.fn();
var seq = Animated.sequence([anim1, anim2]); const seq = Animated.sequence([anim1, anim2]);
expect(anim1.start).not.toBeCalled(); expect(anim1.start).not.toBeCalled();
expect(anim2.start).not.toBeCalled(); expect(anim2.start).not.toBeCalled();
@ -199,9 +199,9 @@ describe('Animated tests', () => {
}); });
it('supports interrupting sequence', () => { it('supports interrupting sequence', () => {
var anim1 = {start: jest.fn()}; const anim1 = {start: jest.fn()};
var anim2 = {start: jest.fn()}; const anim2 = {start: jest.fn()};
var cb = jest.fn(); const cb = jest.fn();
Animated.sequence([anim1, anim2]).start(cb); Animated.sequence([anim1, anim2]).start(cb);
@ -213,11 +213,11 @@ describe('Animated tests', () => {
}); });
it('supports stopping sequence', () => { it('supports stopping sequence', () => {
var anim1 = {start: jest.fn(), stop: jest.fn()}; const anim1 = {start: jest.fn(), stop: jest.fn()};
var anim2 = {start: jest.fn(), stop: jest.fn()}; const anim2 = {start: jest.fn(), stop: jest.fn()};
var cb = jest.fn(); const cb = jest.fn();
var seq = Animated.sequence([anim1, anim2]); const seq = Animated.sequence([anim1, anim2]);
seq.start(cb); seq.start(cb);
seq.stop(); seq.stop();
@ -234,10 +234,10 @@ describe('Animated tests', () => {
describe('Animated Loop', () => { describe('Animated Loop', () => {
it('loops indefinitely if config not specified', () => { it('loops indefinitely if config not specified', () => {
var animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false}; const animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false};
var cb = jest.fn(); const cb = jest.fn();
var loop = Animated.loop(animation); const loop = Animated.loop(animation);
expect(animation.start).not.toBeCalled(); expect(animation.start).not.toBeCalled();
@ -261,10 +261,10 @@ describe('Animated tests', () => {
}); });
it('loops indefinitely if iterations is -1', () => { it('loops indefinitely if iterations is -1', () => {
var animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false}; const animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false};
var cb = jest.fn(); const cb = jest.fn();
var loop = Animated.loop(animation, { iterations: -1 }); const loop = Animated.loop(animation, { iterations: -1 });
expect(animation.start).not.toBeCalled(); expect(animation.start).not.toBeCalled();
@ -288,10 +288,10 @@ describe('Animated tests', () => {
}); });
it('loops indefinitely if iterations not specified', () => { it('loops indefinitely if iterations not specified', () => {
var animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false}; const animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false};
var cb = jest.fn(); const cb = jest.fn();
var loop = Animated.loop(animation, { anotherKey: 'value' }); const loop = Animated.loop(animation, { anotherKey: 'value' });
expect(animation.start).not.toBeCalled(); expect(animation.start).not.toBeCalled();
@ -315,10 +315,10 @@ describe('Animated tests', () => {
}); });
it('loops three times if iterations is 3', () => { it('loops three times if iterations is 3', () => {
var animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false}; const animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false};
var cb = jest.fn(); const cb = jest.fn();
var loop = Animated.loop(animation, { iterations: 3 }); const loop = Animated.loop(animation, { iterations: 3 });
expect(animation.start).not.toBeCalled(); expect(animation.start).not.toBeCalled();
@ -342,10 +342,10 @@ describe('Animated tests', () => {
}); });
it('does not loop if iterations is 1', () => { it('does not loop if iterations is 1', () => {
var animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false}; const animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false};
var cb = jest.fn(); const cb = jest.fn();
var loop = Animated.loop(animation, { iterations: 1 }); const loop = Animated.loop(animation, { iterations: 1 });
expect(animation.start).not.toBeCalled(); expect(animation.start).not.toBeCalled();
@ -359,10 +359,10 @@ describe('Animated tests', () => {
}); });
it('does not animate if iterations is 0', () => { it('does not animate if iterations is 0', () => {
var animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false}; const animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false};
var cb = jest.fn(); const cb = jest.fn();
var loop = Animated.loop(animation, { iterations: 0 }); const loop = Animated.loop(animation, { iterations: 0 });
expect(animation.start).not.toBeCalled(); expect(animation.start).not.toBeCalled();
@ -373,8 +373,8 @@ describe('Animated tests', () => {
}); });
it('supports interrupting an indefinite loop', () => { it('supports interrupting an indefinite loop', () => {
var animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false}; const animation = {start: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false};
var cb = jest.fn(); const cb = jest.fn();
Animated.loop(animation).start(cb); Animated.loop(animation).start(cb);
expect(animation.start).toBeCalled(); expect(animation.start).toBeCalled();
@ -391,10 +391,10 @@ describe('Animated tests', () => {
}); });
it('supports stopping loop', () => { it('supports stopping loop', () => {
var animation = {start: jest.fn(), stop: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false}; const animation = {start: jest.fn(), stop: jest.fn(), reset: jest.fn(), _isUsingNativeDriver: () => false};
var cb = jest.fn(); const cb = jest.fn();
var loop = Animated.loop(animation); const loop = Animated.loop(animation);
loop.start(cb); loop.start(cb);
loop.stop(); loop.stop();
@ -411,14 +411,14 @@ describe('Animated tests', () => {
describe('Animated Parallel', () => { describe('Animated Parallel', () => {
it('works with an empty parallel', () => { it('works with an empty parallel', () => {
var cb = jest.fn(); const cb = jest.fn();
Animated.parallel([]).start(cb); Animated.parallel([]).start(cb);
expect(cb).toBeCalledWith({finished: true}); expect(cb).toBeCalledWith({finished: true});
}); });
it('works with an empty element in array', () => { it('works with an empty element in array', () => {
var anim1 = {start: jest.fn()}; const anim1 = {start: jest.fn()};
var cb = jest.fn(); const cb = jest.fn();
Animated.parallel([null, anim1]).start(cb); Animated.parallel([null, anim1]).start(cb);
expect(anim1.start).toBeCalled(); expect(anim1.start).toBeCalled();
@ -428,11 +428,11 @@ describe('Animated tests', () => {
}); });
it('parellelizes well', () => { it('parellelizes well', () => {
var anim1 = {start: jest.fn()}; const anim1 = {start: jest.fn()};
var anim2 = {start: jest.fn()}; const anim2 = {start: jest.fn()};
var cb = jest.fn(); const cb = jest.fn();
var par = Animated.parallel([anim1, anim2]); const par = Animated.parallel([anim1, anim2]);
expect(anim1.start).not.toBeCalled(); expect(anim1.start).not.toBeCalled();
expect(anim2.start).not.toBeCalled(); expect(anim2.start).not.toBeCalled();
@ -451,11 +451,11 @@ describe('Animated tests', () => {
}); });
it('supports stopping parallel', () => { it('supports stopping parallel', () => {
var anim1 = {start: jest.fn(), stop: jest.fn()}; const anim1 = {start: jest.fn(), stop: jest.fn()};
var anim2 = {start: jest.fn(), stop: jest.fn()}; const anim2 = {start: jest.fn(), stop: jest.fn()};
var cb = jest.fn(); const cb = jest.fn();
var seq = Animated.parallel([anim1, anim2]); const seq = Animated.parallel([anim1, anim2]);
seq.start(cb); seq.start(cb);
seq.stop(); seq.stop();
@ -472,12 +472,12 @@ describe('Animated tests', () => {
it('does not call stop more than once when stopping', () => { it('does not call stop more than once when stopping', () => {
var anim1 = {start: jest.fn(), stop: jest.fn()}; const anim1 = {start: jest.fn(), stop: jest.fn()};
var anim2 = {start: jest.fn(), stop: jest.fn()}; const anim2 = {start: jest.fn(), stop: jest.fn()};
var anim3 = {start: jest.fn(), stop: jest.fn()}; const anim3 = {start: jest.fn(), stop: jest.fn()};
var cb = jest.fn(); const cb = jest.fn();
var seq = Animated.parallel([anim1, anim2, anim3]); const seq = Animated.parallel([anim1, anim2, anim3]);
seq.start(cb); seq.start(cb);
anim1.start.mock.calls[0][0]({finished: false}); anim1.start.mock.calls[0][0]({finished: false});
@ -502,8 +502,8 @@ describe('Animated tests', () => {
describe('Animated delays', () => { describe('Animated delays', () => {
it('should call anim after delay in sequence', () => { it('should call anim after delay in sequence', () => {
var anim = {start: jest.fn(), stop: jest.fn()}; const anim = {start: jest.fn(), stop: jest.fn()};
var cb = jest.fn(); const cb = jest.fn();
Animated.sequence([ Animated.sequence([
Animated.delay(1000), Animated.delay(1000),
anim, anim,
@ -515,7 +515,7 @@ describe('Animated tests', () => {
expect(cb).toBeCalledWith({finished: true}); expect(cb).toBeCalledWith({finished: true});
}); });
it('should run stagger to end', () => { it('should run stagger to end', () => {
var cb = jest.fn(); const cb = jest.fn();
Animated.stagger(1000, [ Animated.stagger(1000, [
Animated.delay(1000), Animated.delay(1000),
Animated.delay(1000), Animated.delay(1000),
@ -528,17 +528,17 @@ describe('Animated tests', () => {
describe('Animated Events', () => { describe('Animated Events', () => {
it('should map events', () => { it('should map events', () => {
var value = new Animated.Value(0); const value = new Animated.Value(0);
var handler = Animated.event( const handler = Animated.event(
[null, {state: {foo: value}}], [null, {state: {foo: value}}],
); );
handler({bar: 'ignoreBar'}, {state: {baz: 'ignoreBaz', foo: 42}}); handler({bar: 'ignoreBar'}, {state: {baz: 'ignoreBaz', foo: 42}});
expect(value.__getValue()).toBe(42); expect(value.__getValue()).toBe(42);
}); });
it('should call listeners', () => { it('should call listeners', () => {
var value = new Animated.Value(0); const value = new Animated.Value(0);
var listener = jest.fn(); const listener = jest.fn();
var handler = Animated.event( const handler = Animated.event(
[{foo: value}], [{foo: value}],
{listener}, {listener},
); );
@ -548,14 +548,14 @@ describe('Animated tests', () => {
expect(listener).toBeCalledWith({foo: 42}); expect(listener).toBeCalledWith({foo: 42});
}); });
it('should call forked event listeners', () => { it('should call forked event listeners', () => {
var value = new Animated.Value(0); const value = new Animated.Value(0);
var listener = jest.fn(); const listener = jest.fn();
var handler = Animated.event( const handler = Animated.event(
[{foo: value}], [{foo: value}],
{listener}, {listener},
); );
var listener2 = jest.fn(); const listener2 = jest.fn();
var forkedHandler = Animated.forkEvent(handler, listener2); const forkedHandler = Animated.forkEvent(handler, listener2);
forkedHandler({foo: 42}); forkedHandler({foo: 42});
expect(value.__getValue()).toBe(42); expect(value.__getValue()).toBe(42);
expect(listener.mock.calls.length).toBe(1); expect(listener.mock.calls.length).toBe(1);
@ -567,9 +567,9 @@ describe('Animated tests', () => {
describe('Animated Interactions', () => { describe('Animated Interactions', () => {
/*eslint-disable no-shadow*/ /*eslint-disable no-shadow*/
var Animated; let Animated;
/*eslint-enable*/ /*eslint-enable*/
var InteractionManager; let InteractionManager;
beforeEach(() => { beforeEach(() => {
jest.mock('InteractionManager'); jest.mock('InteractionManager');
@ -584,8 +584,8 @@ describe('Animated tests', () => {
it('registers an interaction by default', () => { it('registers an interaction by default', () => {
InteractionManager.createInteractionHandle.mockReturnValue(777); InteractionManager.createInteractionHandle.mockReturnValue(777);
var value = new Animated.Value(0); const value = new Animated.Value(0);
var callback = jest.fn(); const callback = jest.fn();
Animated.timing(value, { Animated.timing(value, {
toValue: 100, toValue: 100,
duration: 100, duration: 100,
@ -598,8 +598,8 @@ describe('Animated tests', () => {
}); });
it('does not register an interaction when specified', () => { it('does not register an interaction when specified', () => {
var value = new Animated.Value(0); const value = new Animated.Value(0);
var callback = jest.fn(); const callback = jest.fn();
Animated.timing(value, { Animated.timing(value, {
toValue: 100, toValue: 100,
duration: 100, duration: 100,
@ -615,8 +615,8 @@ describe('Animated tests', () => {
describe('Animated Tracking', () => { describe('Animated Tracking', () => {
it('should track values', () => { it('should track values', () => {
var value1 = new Animated.Value(0); const value1 = new Animated.Value(0);
var value2 = new Animated.Value(0); const value2 = new Animated.Value(0);
Animated.timing(value2, { Animated.timing(value2, {
toValue: value1, toValue: value1,
duration: 0, duration: 0,
@ -628,8 +628,8 @@ describe('Animated tests', () => {
}); });
it('should track interpolated values', () => { it('should track interpolated values', () => {
var value1 = new Animated.Value(0); const value1 = new Animated.Value(0);
var value2 = new Animated.Value(0); const value2 = new Animated.Value(0);
Animated.timing(value2, { Animated.timing(value2, {
toValue: value1.interpolate({ toValue: value1.interpolate({
inputRange: [0, 2], inputRange: [0, 2],
@ -642,8 +642,8 @@ describe('Animated tests', () => {
}); });
it('should stop tracking when animated', () => { it('should stop tracking when animated', () => {
var value1 = new Animated.Value(0); const value1 = new Animated.Value(0);
var value2 = new Animated.Value(0); const value2 = new Animated.Value(0);
Animated.timing(value2, { Animated.timing(value2, {
toValue: value1, toValue: value1,
duration: 0, duration: 0,
@ -661,11 +661,11 @@ describe('Animated tests', () => {
describe('Animated Vectors', () => { describe('Animated Vectors', () => {
it('should animate vectors', () => { it('should animate vectors', () => {
var vec = new Animated.ValueXY(); const vec = new Animated.ValueXY();
var callback = jest.fn(); const callback = jest.fn();
var node = new Animated.__PropsOnlyForTests({ const node = new Animated.__PropsOnlyForTests({
style: { style: {
opacity: vec.x.interpolate({ opacity: vec.x.interpolate({
inputRange: [0, 42], inputRange: [0, 42],
@ -711,8 +711,8 @@ describe('Animated tests', () => {
}); });
it('should track vectors', () => { it('should track vectors', () => {
var value1 = new Animated.ValueXY(); const value1 = new Animated.ValueXY();
var value2 = new Animated.ValueXY(); const value2 = new Animated.ValueXY();
Animated.timing(value2, { Animated.timing(value2, {
toValue: value1, toValue: value1,
duration: 0, duration: 0,
@ -727,8 +727,8 @@ describe('Animated tests', () => {
}); });
it('should track with springs', () => { it('should track with springs', () => {
var value1 = new Animated.ValueXY(); const value1 = new Animated.ValueXY();
var value2 = new Animated.ValueXY(); const value2 = new Animated.ValueXY();
Animated.spring(value2, { Animated.spring(value2, {
toValue: value1, toValue: value1,
tension: 3000, // faster spring for faster test tension: 3000, // faster spring for faster test
@ -747,9 +747,9 @@ describe('Animated tests', () => {
describe('Animated Listeners', () => { describe('Animated Listeners', () => {
it('should get updates', () => { it('should get updates', () => {
var value1 = new Animated.Value(0); const value1 = new Animated.Value(0);
var listener = jest.fn(); const listener = jest.fn();
var id = value1.addListener(listener); const id = value1.addListener(listener);
value1.setValue(42); value1.setValue(42);
expect(listener.mock.calls.length).toBe(1); expect(listener.mock.calls.length).toBe(1);
expect(listener).toBeCalledWith({value: 42}); expect(listener).toBeCalledWith({value: 42});
@ -765,8 +765,8 @@ describe('Animated tests', () => {
}); });
it('should removeAll', () => { it('should removeAll', () => {
var value1 = new Animated.Value(0); const value1 = new Animated.Value(0);
var listener = jest.fn(); const listener = jest.fn();
[1,2,3,4].forEach(() => value1.addListener(listener)); [1,2,3,4].forEach(() => value1.addListener(listener));
value1.setValue(42); value1.setValue(42);
expect(listener.mock.calls.length).toBe(4); expect(listener.mock.calls.length).toBe(4);

Просмотреть файл

@ -8,10 +8,10 @@
*/ */
'use strict'; 'use strict';
var Easing = require('Easing'); const Easing = require('Easing');
describe('Easing', () => { describe('Easing', () => {
it('should work with linear', () => { it('should work with linear', () => {
var easing = Easing.linear; const easing = Easing.linear;
expect(easing(0)).toBe(0); expect(easing(0)).toBe(0);
expect(easing(0.5)).toBe(0.5); expect(easing(0.5)).toBe(0.5);
@ -20,7 +20,7 @@ describe('Easing', () => {
}); });
it('should work with ease in linear', () => { it('should work with ease in linear', () => {
var easing = Easing.in(Easing.linear); const easing = Easing.in(Easing.linear);
expect(easing(0)).toBe(0); expect(easing(0)).toBe(0);
expect(easing(0.5)).toBe(0.5); expect(easing(0.5)).toBe(0.5);
expect(easing(0.8)).toBe(0.8); expect(easing(0.8)).toBe(0.8);
@ -28,7 +28,7 @@ describe('Easing', () => {
}); });
it('should work with easy out linear', () => { it('should work with easy out linear', () => {
var easing = Easing.out(Easing.linear); const easing = Easing.out(Easing.linear);
expect(easing(0)).toBe(0); expect(easing(0)).toBe(0);
expect(easing(0.5)).toBe(0.5); expect(easing(0.5)).toBe(0.5);
expect(easing(0.6)).toBe(0.6); expect(easing(0.6)).toBe(0.6);
@ -39,8 +39,8 @@ describe('Easing', () => {
function easeInQuad(t) { function easeInQuad(t) {
return t * t; return t * t;
} }
var easing = Easing.in(Easing.quad); const easing = Easing.in(Easing.quad);
for (var t = -0.5; t < 1.5; t += 0.1) { for (let t = -0.5; t < 1.5; t += 0.1) {
expect(easing(t)).toBe(easeInQuad(t)); expect(easing(t)).toBe(easeInQuad(t));
} }
}); });
@ -49,8 +49,8 @@ describe('Easing', () => {
function easeOutQuad(t) { function easeOutQuad(t) {
return -t * (t - 2); return -t * (t - 2);
} }
var easing = Easing.out(Easing.quad); const easing = Easing.out(Easing.quad);
for (var t = 0; t <= 1; t += 0.1) { for (let t = 0; t <= 1; t += 0.1) {
expect(easing(1)).toBe(easeOutQuad(1)); expect(easing(1)).toBe(easeOutQuad(1));
} }
}); });
@ -63,31 +63,31 @@ describe('Easing', () => {
} }
return -((t - 1) * (t - 3) - 1) / 2; return -((t - 1) * (t - 3) - 1) / 2;
} }
var easing = Easing.inOut(Easing.quad); const easing = Easing.inOut(Easing.quad);
for (var t = -0.5; t < 1.5; t += 0.1) { for (let t = -0.5; t < 1.5; t += 0.1) {
expect(easing(t)).toBeCloseTo(easeInOutQuad(t), 4); expect(easing(t)).toBeCloseTo(easeInOutQuad(t), 4);
} }
}); });
it('should satisfy boundary conditions with elastic', () => { it('should satisfy boundary conditions with elastic', () => {
for (var b = 0; b < 4; b += 0.3) { for (let b = 0; b < 4; b += 0.3) {
var easing = Easing.elastic(b); const easing = Easing.elastic(b);
expect(easing(0)).toBe(0); expect(easing(0)).toBe(0);
expect(easing(1)).toBe(1); expect(easing(1)).toBe(1);
} }
}); });
function sampleEasingFunction(easing) { function sampleEasingFunction(easing) {
var DURATION = 300; const DURATION = 300;
var tickCount = Math.round(DURATION * 60 / 1000); const tickCount = Math.round(DURATION * 60 / 1000);
var samples = []; const samples = [];
for (var i = 0; i <= tickCount; i++) { for (let i = 0; i <= tickCount; i++) {
samples.push(easing(i / tickCount)); samples.push(easing(i / tickCount));
} }
return samples; return samples;
} }
var Samples = { const Samples = {
in_quad: [0,0.0030864197530864196,0.012345679012345678,0.027777777777777776,0.04938271604938271,0.0771604938271605,0.1111111111111111,0.15123456790123457,0.19753086419753085,0.25,0.308641975308642,0.37345679012345684,0.4444444444444444,0.5216049382716049,0.6049382716049383,0.6944444444444445,0.7901234567901234,0.8919753086419753,1], in_quad: [0,0.0030864197530864196,0.012345679012345678,0.027777777777777776,0.04938271604938271,0.0771604938271605,0.1111111111111111,0.15123456790123457,0.19753086419753085,0.25,0.308641975308642,0.37345679012345684,0.4444444444444444,0.5216049382716049,0.6049382716049383,0.6944444444444445,0.7901234567901234,0.8919753086419753,1],
out_quad: [0,0.10802469135802469,0.20987654320987653,0.3055555555555555,0.3950617283950617,0.47839506172839513,0.5555555555555556,0.6265432098765432,0.691358024691358,0.75,0.8024691358024691,0.8487654320987654,0.888888888888889,0.9228395061728394,0.9506172839506174,0.9722222222222221,0.9876543209876543,0.9969135802469136,1], out_quad: [0,0.10802469135802469,0.20987654320987653,0.3055555555555555,0.3950617283950617,0.47839506172839513,0.5555555555555556,0.6265432098765432,0.691358024691358,0.75,0.8024691358024691,0.8487654320987654,0.888888888888889,0.9228395061728394,0.9506172839506174,0.9722222222222221,0.9876543209876543,0.9969135802469136,1],
inOut_quad: [0,0.006172839506172839,0.024691358024691357,0.05555555555555555,0.09876543209876543,0.154320987654321,0.2222222222222222,0.30246913580246915,0.3950617283950617,0.5,0.6049382716049383,0.697530864197531,0.7777777777777777,0.845679012345679,0.9012345679012346,0.9444444444444444,0.9753086419753086,0.9938271604938271,1], inOut_quad: [0,0.006172839506172839,0.024691358024691357,0.05555555555555555,0.09876543209876543,0.154320987654321,0.2222222222222222,0.30246913580246915,0.3950617283950617,0.5,0.6049382716049383,0.697530864197531,0.7777777777777777,0.845679012345679,0.9012345679012346,0.9444444444444444,0.9753086419753086,0.9938271604938271,1],
@ -109,13 +109,13 @@ describe('Easing', () => {
Object.keys(Samples).forEach(function(type) { Object.keys(Samples).forEach(function(type) {
it('should ease ' + type, function() { it('should ease ' + type, function() {
var [modeName, easingName, isFunction] = type.split('_'); const [modeName, easingName, isFunction] = type.split('_');
var easing = Easing[easingName]; let easing = Easing[easingName];
if (isFunction !== undefined) { if (isFunction !== undefined) {
easing = easing(); easing = easing();
} }
var computed = sampleEasingFunction(Easing[modeName](easing)); const computed = sampleEasingFunction(Easing[modeName](easing));
var samples = Samples[type]; const samples = Samples[type];
computed.forEach((value, key) => { computed.forEach((value, key) => {
expect(value).toBeCloseTo(samples[key], 2); expect(value).toBeCloseTo(samples[key], 2);

Просмотреть файл

@ -8,12 +8,12 @@
*/ */
'use strict'; 'use strict';
var AnimatedInterpolation = require('../nodes/AnimatedInterpolation'); const AnimatedInterpolation = require('../nodes/AnimatedInterpolation');
var Easing = require('Easing'); const Easing = require('Easing');
describe('Interpolation', () => { describe('Interpolation', () => {
it('should work with defaults', () => { it('should work with defaults', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [0, 1], outputRange: [0, 1],
}); });
@ -25,7 +25,7 @@ describe('Interpolation', () => {
}); });
it('should work with output range', () => { it('should work with output range', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [100, 200], outputRange: [100, 200],
}); });
@ -37,7 +37,7 @@ describe('Interpolation', () => {
}); });
it('should work with input range', () => { it('should work with input range', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [100, 200], inputRange: [100, 200],
outputRange: [0, 1], outputRange: [0, 1],
}); });
@ -65,7 +65,7 @@ describe('Interpolation', () => {
}); });
it('should work with empty input range', () => { it('should work with empty input range', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 10, 10], inputRange: [0, 10, 10],
outputRange: [1, 2, 3], outputRange: [1, 2, 3],
extrapolate: 'extend', extrapolate: 'extend',
@ -79,7 +79,7 @@ describe('Interpolation', () => {
}); });
it('should work with empty output range', () => { it('should work with empty output range', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [1, 2, 3], inputRange: [1, 2, 3],
outputRange: [0, 10, 10], outputRange: [0, 10, 10],
extrapolate: 'extend', extrapolate: 'extend',
@ -94,7 +94,7 @@ describe('Interpolation', () => {
}); });
it('should work with easing', () => { it('should work with easing', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [0, 1], outputRange: [0, 1],
easing: Easing.quad, easing: Easing.quad,
@ -107,7 +107,7 @@ describe('Interpolation', () => {
}); });
it('should work with extrapolate', () => { it('should work with extrapolate', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ let interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [0, 1], outputRange: [0, 1],
extrapolate: 'extend', extrapolate: 'extend',
@ -139,7 +139,7 @@ describe('Interpolation', () => {
}); });
it('should work with keyframes with extrapolate', () => { it('should work with keyframes with extrapolate', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 10, 100, 1000], inputRange: [0, 10, 100, 1000],
outputRange: [0, 5, 50, 500], outputRange: [0, 5, 50, 500],
extrapolate: true, extrapolate: true,
@ -157,7 +157,7 @@ describe('Interpolation', () => {
}); });
it('should work with keyframes without extrapolate', () => { it('should work with keyframes without extrapolate', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1, 2], inputRange: [0, 1, 2],
outputRange: [0.2, 1, 0.2], outputRange: [0.2, 1, 0.2],
extrapolate: 'clamp', extrapolate: 'clamp',
@ -183,7 +183,7 @@ describe('Interpolation', () => {
}); });
it('should work with negative infinite', () => { it('should work with negative infinite', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [-Infinity, 0], inputRange: [-Infinity, 0],
outputRange: [-Infinity, 0], outputRange: [-Infinity, 0],
easing: Easing.quad, easing: Easing.quad,
@ -199,7 +199,7 @@ describe('Interpolation', () => {
}); });
it('should work with positive infinite', () => { it('should work with positive infinite', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [5, Infinity], inputRange: [5, Infinity],
outputRange: [5, Infinity], outputRange: [5, Infinity],
easing: Easing.quad, easing: Easing.quad,
@ -217,7 +217,7 @@ describe('Interpolation', () => {
}); });
it('should work with output ranges as string', () => { it('should work with output ranges as string', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: ['rgba(0, 100, 200, 0)', 'rgba(50, 150, 250, 0.4)'], outputRange: ['rgba(0, 100, 200, 0)', 'rgba(50, 150, 250, 0.4)'],
}); });
@ -228,7 +228,7 @@ describe('Interpolation', () => {
}); });
it('should work with output ranges as short hex string', () => { it('should work with output ranges as short hex string', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: ['#024', '#9BF'], outputRange: ['#024', '#9BF'],
}); });
@ -239,7 +239,7 @@ describe('Interpolation', () => {
}); });
it('should work with output ranges as long hex string', () => { it('should work with output ranges as long hex string', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: ['#FF9500', '#87FC70'], outputRange: ['#FF9500', '#87FC70'],
}); });
@ -250,7 +250,7 @@ describe('Interpolation', () => {
}); });
it('should work with output ranges with mixed hex and rgba strings', () => { it('should work with output ranges with mixed hex and rgba strings', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: ['rgba(100, 120, 140, .4)', '#87FC70'], outputRange: ['rgba(100, 120, 140, .4)', '#87FC70'],
}); });
@ -261,7 +261,7 @@ describe('Interpolation', () => {
}); });
it('should work with negative and decimal values in string ranges', () => { it('should work with negative and decimal values in string ranges', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: ['-100.5deg', '100deg'], outputRange: ['-100.5deg', '100deg'],
}); });
@ -272,7 +272,7 @@ describe('Interpolation', () => {
}); });
it('should crash when chaining an interpolation that returns a string', () => { it('should crash when chaining an interpolation that returns a string', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [0, 1], outputRange: [0, 1],
}); });
@ -282,7 +282,7 @@ describe('Interpolation', () => {
}); });
it('should support a mix of color patterns', () => { it('should support a mix of color patterns', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1, 2], inputRange: [0, 1, 2],
outputRange: ['rgba(0, 100, 200, 0)', 'rgb(50, 150, 250)', 'red'], outputRange: ['rgba(0, 100, 200, 0)', 'rgb(50, 150, 250)', 'red'],
}); });
@ -303,7 +303,7 @@ describe('Interpolation', () => {
}); });
it('should round the alpha channel of a color to the nearest thousandth', () => { it('should round the alpha channel of a color to the nearest thousandth', () => {
var interpolation = AnimatedInterpolation.__createInterpolation({ const interpolation = AnimatedInterpolation.__createInterpolation({
inputRange: [0, 1], inputRange: [0, 1],
outputRange: ['rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 1)'], outputRange: ['rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 1)'],
}); });

Просмотреть файл

@ -10,9 +10,9 @@
'use strict'; 'use strict';
var bezier = require('bezier'); const bezier = require('bezier');
var identity = function(x) { const identity = function(x) {
return x; return x;
}; };
@ -30,15 +30,15 @@ function allEquals(be1, be2, samples, assertion) {
if (!assertion) { if (!assertion) {
assertion = assertClose; assertion = assertClose;
} }
for (var i = 0; i <= samples; ++i) { for (let i = 0; i <= samples; ++i) {
var x = i / samples; const x = i / samples;
assertion(be1(x), be2(x)); assertion(be1(x), be2(x));
} }
} }
function repeat(n) { function repeat(n) {
return function(f) { return function(f) {
for (var i = 0; i < n; ++i) { for (let i = 0; i < n; ++i) {
f(i); f(i);
} }
}; };
@ -74,11 +74,8 @@ describe('bezier', function() {
describe('common properties', function() { describe('common properties', function() {
it('should be the right value at extremes', function() { it('should be the right value at extremes', function() {
repeat(10)(function() { repeat(10)(function() {
var a = Math.random(), const a = Math.random(), b = 2 * Math.random() - 0.5, c = Math.random(), d = 2 * Math.random() - 0.5;
b = 2 * Math.random() - 0.5, const easing = bezier(a, b, c, d);
c = Math.random(),
d = 2 * Math.random() - 0.5;
var easing = bezier(a, b, c, d);
expect(easing(0)).toBe(0); expect(easing(0)).toBe(0);
expect(easing(1)).toBe(1); expect(easing(1)).toBe(1);
}); });
@ -86,13 +83,10 @@ describe('bezier', function() {
it('should approach the projected value of its x=y projected curve', function() { it('should approach the projected value of its x=y projected curve', function() {
repeat(10)(function() { repeat(10)(function() {
var a = Math.random(), const a = Math.random(), b = Math.random(), c = Math.random(), d = Math.random();
b = Math.random(), const easing = bezier(a, b, c, d);
c = Math.random(), const projected = bezier(b, a, d, c);
d = Math.random(); const composed = function(x) {
var easing = bezier(a, b, c, d);
var projected = bezier(b, a, d, c);
var composed = function(x) {
return projected(easing(x)); return projected(easing(x));
}; };
allEquals(identity, composed, 100, makeAssertCloseWithPrecision(2)); allEquals(identity, composed, 100, makeAssertCloseWithPrecision(2));
@ -102,10 +96,7 @@ describe('bezier', function() {
describe('two same instances', function() { describe('two same instances', function() {
it('should be strictly equals', function() { it('should be strictly equals', function() {
repeat(10)(function() { repeat(10)(function() {
var a = Math.random(), const a = Math.random(), b = 2 * Math.random() - 0.5, c = Math.random(), d = 2 * Math.random() - 0.5;
b = 2 * Math.random() - 0.5,
c = Math.random(),
d = 2 * Math.random() - 0.5;
allEquals(bezier(a, b, c, d), bezier(a, b, c, d), 100, 0); allEquals(bezier(a, b, c, d), bezier(a, b, c, d), 100, 0);
}); });
}); });
@ -113,22 +104,16 @@ describe('bezier', function() {
describe('symetric curves', function() { describe('symetric curves', function() {
it('should have a central value y~=0.5 at x=0.5', function() { it('should have a central value y~=0.5 at x=0.5', function() {
repeat(10)(function() { repeat(10)(function() {
var a = Math.random(), const a = Math.random(), b = 2 * Math.random() - 0.5, c = 1 - a, d = 1 - b;
b = 2 * Math.random() - 0.5, const easing = bezier(a, b, c, d);
c = 1 - a,
d = 1 - b;
var easing = bezier(a, b, c, d);
assertClose(easing(0.5), 0.5, 2); assertClose(easing(0.5), 0.5, 2);
}); });
}); });
it('should be symmetrical', function() { it('should be symmetrical', function() {
repeat(10)(function() { repeat(10)(function() {
var a = Math.random(), const a = Math.random(), b = 2 * Math.random() - 0.5, c = 1 - a, d = 1 - b;
b = 2 * Math.random() - 0.5, const easing = bezier(a, b, c, d);
c = 1 - a, const sym = function(x) {
d = 1 - b;
var easing = bezier(a, b, c, d);
var sym = function(x) {
return 1 - easing(1 - x); return 1 - easing(1 - x);
}; };
allEquals(easing, sym, 100, makeAssertCloseWithPrecision(2)); allEquals(easing, sym, 100, makeAssertCloseWithPrecision(2));

Просмотреть файл

@ -8,15 +8,15 @@
'use strict'; 'use strict';
// These values are established by empiricism with tests (tradeoff: performance VS precision) // These values are established by empiricism with tests (tradeoff: performance VS precision)
var NEWTON_ITERATIONS = 4; const NEWTON_ITERATIONS = 4;
var NEWTON_MIN_SLOPE = 0.001; const NEWTON_MIN_SLOPE = 0.001;
var SUBDIVISION_PRECISION = 0.0000001; const SUBDIVISION_PRECISION = 0.0000001;
var SUBDIVISION_MAX_ITERATIONS = 10; const SUBDIVISION_MAX_ITERATIONS = 10;
var kSplineTableSize = 11; const kSplineTableSize = 11;
var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0); const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
var float32ArraySupported = typeof Float32Array === 'function'; const float32ArraySupported = typeof Float32Array === 'function';
function A (aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; } function A (aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
function B (aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; } function B (aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
@ -29,7 +29,7 @@
function getSlope (aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); } function getSlope (aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); }
function binarySubdivide (aX, aA, aB, mX1, mX2) { function binarySubdivide (aX, aA, aB, mX1, mX2) {
var currentX, currentT, i = 0; let currentX, currentT, i = 0;
do { do {
currentT = aA + (aB - aA) / 2.0; currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX; currentX = calcBezier(currentT, mX1, mX2) - aX;
@ -43,12 +43,12 @@
} }
function newtonRaphsonIterate (aX, aGuessT, mX1, mX2) { function newtonRaphsonIterate (aX, aGuessT, mX1, mX2) {
for (var i = 0; i < NEWTON_ITERATIONS; ++i) { for (let i = 0; i < NEWTON_ITERATIONS; ++i) {
var currentSlope = getSlope(aGuessT, mX1, mX2); const currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) { if (currentSlope === 0.0) {
return aGuessT; return aGuessT;
} }
var currentX = calcBezier(aGuessT, mX1, mX2) - aX; const currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope; aGuessT -= currentX / currentSlope;
} }
return aGuessT; return aGuessT;
@ -60,17 +60,17 @@
} }
// Precompute samples table // Precompute samples table
var sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize); const sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
if (mX1 !== mY1 || mX2 !== mY2) { if (mX1 !== mY1 || mX2 !== mY2) {
for (var i = 0; i < kSplineTableSize; ++i) { for (let i = 0; i < kSplineTableSize; ++i) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
} }
} }
function getTForX (aX) { function getTForX (aX) {
var intervalStart = 0.0; let intervalStart = 0.0;
var currentSample = 1; let currentSample = 1;
var lastSample = kSplineTableSize - 1; const lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) { for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize; intervalStart += kSampleStepSize;
@ -78,10 +78,10 @@
--currentSample; --currentSample;
// Interpolate to provide an initial guess for t // Interpolate to provide an initial guess for t
var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]); const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
var guessForT = intervalStart + dist * kSampleStepSize; const guessForT = intervalStart + dist * kSampleStepSize;
var initialSlope = getSlope(guessForT, mX1, mX2); const initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) { if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2); return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0.0) { } else if (initialSlope === 0.0) {

Просмотреть файл

@ -7,12 +7,12 @@
* These don't actually exist anywhere in the code. * These don't actually exist anywhere in the code.
*/ */
'use strict'; 'use strict';
var remoteModulesConfig = [ const remoteModulesConfig = [
['RemoteModule1',null,['remoteMethod','promiseMethod'],[]], ['RemoteModule1',null,['remoteMethod','promiseMethod'],[]],
['RemoteModule2',null,['remoteMethod','promiseMethod'],[]], ['RemoteModule2',null,['remoteMethod','promiseMethod'],[]],
]; ];
var MessageQueueTestConfig = { const MessageQueueTestConfig = {
remoteModuleConfig: remoteModulesConfig, remoteModuleConfig: remoteModulesConfig,
}; };

Просмотреть файл

@ -12,7 +12,7 @@
* correctly dispatches to commonJS modules. The `testHook` is overriden by test * correctly dispatches to commonJS modules. The `testHook` is overriden by test
* cases. * cases.
*/ */
var MessageQueueTestModule = { const MessageQueueTestModule = {
testHook1: function() { testHook1: function() {
}, },
testHook2: function() { testHook2: function() {

Просмотреть файл

@ -13,7 +13,7 @@ jest.setMock('NativeModules', {
BlobModule: require('../__mocks__/BlobModule'), BlobModule: require('../__mocks__/BlobModule'),
}); });
var Blob = require('Blob'); const Blob = require('Blob');
describe('Blob', function() { describe('Blob', function() {
it('should create empty blob', () => { it('should create empty blob', () => {

Просмотреть файл

@ -13,8 +13,8 @@ jest.setMock('NativeModules', {
BlobModule: require('../__mocks__/BlobModule'), BlobModule: require('../__mocks__/BlobModule'),
}); });
var Blob = require('Blob'); const Blob = require('Blob');
var BlobManager = require('BlobManager'); const BlobManager = require('BlobManager');
describe('BlobManager', function() { describe('BlobManager', function() {
it('should create blob from parts', () => { it('should create blob from parts', () => {

Просмотреть файл

@ -14,8 +14,8 @@ jest.unmock('event-target-shim').setMock('NativeModules', {
FileReaderModule: require('../__mocks__/FileReaderModule'), FileReaderModule: require('../__mocks__/FileReaderModule'),
}); });
var Blob = require('Blob'); const Blob = require('Blob');
var FileReader = require('FileReader'); const FileReader = require('FileReader');
describe('FileReader', function() { describe('FileReader', function() {
it('should read blob as text', async () => { it('should read blob as text', async () => {

Просмотреть файл

@ -15,16 +15,16 @@
* https://github.com/facebook/react-devtools/blob/master/backend/getData.js * https://github.com/facebook/react-devtools/blob/master/backend/getData.js
*/ */
function getData(element: Object): Object { function getData(element: Object): Object {
var children = null; let children = null;
var props = null; let props = null;
var state = null; let state = null;
var context = null; let context = null;
var updater = null; let updater = null;
var name = null; let name = null;
var type = null; let type = null;
var text = null; let text = null;
var publicInstance = null; let publicInstance = null;
var nodeType = 'Native'; let nodeType = 'Native';
// If the parent is a native node without rendered children, but with // If the parent is a native node without rendered children, but with
// multiple string children, then the `element` that gets passed in here is // multiple string children, then the `element` that gets passed in here is
// a plain value -- a string or number. // a plain value -- a string or number.
@ -80,7 +80,7 @@ function getData(element: Object): Object {
} }
if (element._instance) { if (element._instance) {
var inst = element._instance; const inst = element._instance;
updater = { updater = {
setState: inst.setState && inst.setState.bind(inst), setState: inst.setState && inst.setState.bind(inst),
forceUpdate: inst.forceUpdate && inst.forceUpdate.bind(inst), forceUpdate: inst.forceUpdate && inst.forceUpdate.bind(inst),
@ -113,7 +113,7 @@ function getData(element: Object): Object {
} }
function setInProps(internalInst, path: Array<string | number>, value: any) { function setInProps(internalInst, path: Array<string | number>, value: any) {
var element = internalInst._currentElement; const element = internalInst._currentElement;
internalInst._currentElement = { internalInst._currentElement = {
...element, ...element,
props: copyWithSet(element.props, path, value), props: copyWithSet(element.props, path, value),
@ -132,16 +132,16 @@ function setInContext(inst, path: Array<string | number>, value: any) {
} }
function setIn(obj: Object, path: Array<string | number>, value: any) { function setIn(obj: Object, path: Array<string | number>, value: any) {
var last = path.pop(); const last = path.pop();
var parent = path.reduce((obj_, attr) => obj_ ? obj_[attr] : null, obj); const parent = path.reduce((obj_, attr) => obj_ ? obj_[attr] : null, obj);
if (parent) { if (parent) {
parent[last] = value; parent[last] = value;
} }
} }
function childrenList(children) { function childrenList(children) {
var res = []; const res = [];
for (var name in children) { for (const name in children) {
res.push(children[name]); res.push(children[name]);
} }
return res; return res;
@ -151,8 +151,8 @@ function copyWithSetImpl(obj, path, idx, value) {
if (idx >= path.length) { if (idx >= path.length) {
return value; return value;
} }
var key = path[idx]; const key = path[idx];
var updated = Array.isArray(obj) ? obj.slice() : {...obj}; const updated = Array.isArray(obj) ? obj.slice() : {...obj};
// $FlowFixMe number or string is fine here // $FlowFixMe number or string is fine here
updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value); updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
return updated; return updated;

Просмотреть файл

@ -8,9 +8,9 @@
*/ */
'use strict'; 'use strict';
var RCTImagePicker = require('NativeModules').ImagePickerIOS; const RCTImagePicker = require('NativeModules').ImagePickerIOS;
var ImagePickerIOS = { const ImagePickerIOS = {
canRecordVideos: function(callback: Function) { canRecordVideos: function(callback: Function) {
return RCTImagePicker.canRecordVideos(callback); return RCTImagePicker.canRecordVideos(callback);
}, },

Просмотреть файл

@ -10,7 +10,7 @@
'use strict'; 'use strict';
function normalizeColor(color: string | number): ?number { function normalizeColor(color: string | number): ?number {
var match; let match;
if (typeof color === 'number') { if (typeof color === 'number') {
if (color >>> 0 === color && color >= 0 && color <= 0xffffffff) { if (color >>> 0 === color && color >= 0 && color <= 0xffffffff) {
@ -31,18 +31,18 @@ function normalizeColor(color: string | number): ?number {
if ((match = matchers.rgb.exec(color))) { if ((match = matchers.rgb.exec(color))) {
return ( return (
(// b (// b
parse255(match[1]) << 24 | // r (parse255(match[1]) << 24 | // r
parse255(match[2]) << 16 | // g parse255(match[2]) << 16 | // g
parse255(match[3]) << 8 | 0x000000ff) // a parse255(match[3]) << 8 | 0x000000ff)) // a
) >>> 0; ) >>> 0;
} }
if ((match = matchers.rgba.exec(color))) { if ((match = matchers.rgba.exec(color))) {
return ( return (
(// b (// b
parse255(match[1]) << 24 | // r (parse255(match[1]) << 24 | // r
parse255(match[2]) << 16 | // g parse255(match[2]) << 16 | // g
parse255(match[3]) << 8 | parse1(match[4])) // a parse255(match[3]) << 8 | parse1(match[4]))) // a
) >>> 0; ) >>> 0;
} }
@ -114,11 +114,11 @@ function hue2rgb(p: number, q: number, t: number): number {
} }
function hslToRgb(h: number, s: number, l: number): number { function hslToRgb(h: number, s: number, l: number): number {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s; const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q; const p = 2 * l - q;
var r = hue2rgb(p, q, h + 1 / 3); const r = hue2rgb(p, q, h + 1 / 3);
var g = hue2rgb(p, q, h); const g = hue2rgb(p, q, h);
var b = hue2rgb(p, q, h - 1 / 3); const b = hue2rgb(p, q, h - 1 / 3);
return ( return (
Math.round(r * 255) << 24 | Math.round(r * 255) << 24 |
@ -128,14 +128,14 @@ function hslToRgb(h: number, s: number, l: number): number {
} }
// var INTEGER = '[-+]?\\d+'; // var INTEGER = '[-+]?\\d+';
var NUMBER = '[-+]?\\d*\\.?\\d+'; const NUMBER = '[-+]?\\d*\\.?\\d+';
var PERCENTAGE = NUMBER + '%'; const PERCENTAGE = NUMBER + '%';
function call(...args) { function call(...args) {
return '\\(\\s*(' + args.join(')\\s*,\\s*(') + ')\\s*\\)'; return '\\(\\s*(' + args.join(')\\s*,\\s*(') + ')\\s*\\)';
} }
var matchers = { const matchers = {
rgb: new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER)), rgb: new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER)),
rgba: new RegExp('rgba' + call(NUMBER, NUMBER, NUMBER, NUMBER)), rgba: new RegExp('rgba' + call(NUMBER, NUMBER, NUMBER, NUMBER)),
hsl: new RegExp('hsl' + call(NUMBER, PERCENTAGE, PERCENTAGE)), hsl: new RegExp('hsl' + call(NUMBER, PERCENTAGE, PERCENTAGE)),
@ -147,7 +147,7 @@ var matchers = {
}; };
function parse255(str: string): number { function parse255(str: string): number {
var int = parseInt(str, 10); const int = parseInt(str, 10);
if (int < 0) { if (int < 0) {
return 0; return 0;
} }
@ -158,12 +158,12 @@ function parse255(str: string): number {
} }
function parse360(str: string): number { function parse360(str: string): number {
var int = parseFloat(str); const int = parseFloat(str);
return (((int % 360) + 360) % 360) / 360; return (((int % 360) + 360) % 360) / 360;
} }
function parse1(str: string): number { function parse1(str: string): number {
var num = parseFloat(str); const num = parseFloat(str);
if (num < 0) { if (num < 0) {
return 0; return 0;
} }
@ -175,7 +175,7 @@ function parse1(str: string): number {
function parsePercentage(str: string): number { function parsePercentage(str: string): number {
// parseFloat conveniently ignores the final % // parseFloat conveniently ignores the final %
var int = parseFloat(str); const int = parseFloat(str);
if (int < 0) { if (int < 0) {
return 0; return 0;
} }
@ -185,7 +185,7 @@ function parsePercentage(str: string): number {
return int / 100; return int / 100;
} }
var names = { const names = {
transparent: 0x00000000, transparent: 0x00000000,
// http://www.w3.org/TR/css3-color/#svg-color // http://www.w3.org/TR/css3-color/#svg-color

Просмотреть файл

@ -9,7 +9,7 @@
'use strict'; 'use strict';
var parseErrorStack = require('parseErrorStack'); const parseErrorStack = require('parseErrorStack');
function getFakeError() { function getFakeError() {
return new Error('Happy Cat'); return new Error('Happy Cat');
@ -18,24 +18,24 @@ function getFakeError() {
describe('parseErrorStack', function() { describe('parseErrorStack', function() {
it('parses error stack', function() { it('parses error stack', function() {
var stack = parseErrorStack(getFakeError()); const stack = parseErrorStack(getFakeError());
expect(stack.length).toBeGreaterThan(0); expect(stack.length).toBeGreaterThan(0);
var firstFrame = stack[0]; const firstFrame = stack[0];
expect(firstFrame.methodName).toEqual('getFakeError'); expect(firstFrame.methodName).toEqual('getFakeError');
expect(firstFrame.file).toMatch(/parseErrorStack-test\.js$/); expect(firstFrame.file).toMatch(/parseErrorStack-test\.js$/);
}); });
it('supports framesToPop', function() { it('supports framesToPop', function() {
function getWrappedError() { function getWrappedError() {
var error = getFakeError(); const error = getFakeError();
error.framesToPop = 1; error.framesToPop = 1;
return error; return error;
} }
// Make sure framesToPop == 1 causes it to ignore getFakeError // Make sure framesToPop == 1 causes it to ignore getFakeError
// stack frame // stack frame
var stack = parseErrorStack(getWrappedError()); const stack = parseErrorStack(getWrappedError());
expect(stack[0].methodName).toEqual('getWrappedError'); expect(stack[0].methodName).toEqual('getWrappedError');
}); });

Просмотреть файл

@ -19,7 +19,7 @@ function reportError(error) {
throw error; throw error;
} }
var ErrorUtils = { const ErrorUtils = {
apply: jest.fn(execute), apply: jest.fn(execute),
applyWithGuard: jest.fn(execute), applyWithGuard: jest.fn(execute),
guard: jest.fn(callback => callback), guard: jest.fn(callback => callback),

Просмотреть файл

@ -153,7 +153,7 @@ function burnCPU(milliseconds) {
while (performanceNow() < (start + milliseconds)) {} while (performanceNow() < (start + milliseconds)) {}
} }
var styles = StyleSheet.create({ const styles = StyleSheet.create({
scrollView: { scrollView: {
margin: 10, margin: 10,
backgroundColor: 'white', backgroundColor: 'white',

Просмотреть файл

@ -23,8 +23,8 @@ const LocationEventEmitter = new NativeEventEmitter(RCTLocationObserver);
const Platform = require('Platform'); const Platform = require('Platform');
const PermissionsAndroid = require('PermissionsAndroid'); const PermissionsAndroid = require('PermissionsAndroid');
var subscriptions = []; let subscriptions = [];
var updatesEnabled = false; let updatesEnabled = false;
type GeoConfiguration = { type GeoConfiguration = {
skipPermissionRequests: bool; skipPermissionRequests: bool;
@ -44,7 +44,7 @@ type GeoOptions = {
* *
* See https://facebook.github.io/react-native/docs/geolocation.html * See https://facebook.github.io/react-native/docs/geolocation.html
*/ */
var Geolocation = { const Geolocation = {
/* /*
* Sets configuration options that will be used in all location requests. * Sets configuration options that will be used in all location requests.
@ -116,7 +116,7 @@ var Geolocation = {
RCTLocationObserver.startObserving(options || {}); RCTLocationObserver.startObserving(options || {});
updatesEnabled = true; updatesEnabled = true;
} }
var watchID = subscriptions.length; const watchID = subscriptions.length;
subscriptions.push([ subscriptions.push([
LocationEventEmitter.addListener( LocationEventEmitter.addListener(
'geolocationDidChange', 'geolocationDidChange',
@ -131,7 +131,7 @@ var Geolocation = {
}, },
clearWatch: function(watchID: number) { clearWatch: function(watchID: number) {
var sub = subscriptions[watchID]; const sub = subscriptions[watchID];
if (!sub) { if (!sub) {
// Silently exit when the watchID is invalid or already cleared // Silently exit when the watchID is invalid or already cleared
// This is consistent with timers // This is consistent with timers
@ -140,10 +140,10 @@ var Geolocation = {
sub[0].remove(); sub[0].remove();
// array element refinements not yet enabled in Flow // array element refinements not yet enabled in Flow
var sub1 = sub[1]; sub1 && sub1.remove(); const sub1 = sub[1]; sub1 && sub1.remove();
subscriptions[watchID] = undefined; subscriptions[watchID] = undefined;
var noWatchers = true; let noWatchers = true;
for (var ii = 0; ii < subscriptions.length; ii++) { for (let ii = 0; ii < subscriptions.length; ii++) {
if (subscriptions[ii]) { if (subscriptions[ii]) {
noWatchers = false; // still valid subscriptions noWatchers = false; // still valid subscriptions
} }
@ -157,13 +157,13 @@ var Geolocation = {
if (updatesEnabled) { if (updatesEnabled) {
RCTLocationObserver.stopObserving(); RCTLocationObserver.stopObserving();
updatesEnabled = false; updatesEnabled = false;
for (var ii = 0; ii < subscriptions.length; ii++) { for (let ii = 0; ii < subscriptions.length; ii++) {
var sub = subscriptions[ii]; const sub = subscriptions[ii];
if (sub) { if (sub) {
warning(false, 'Called stopObserving with existing subscriptions.'); warning(false, 'Called stopObserving with existing subscriptions.');
sub[0].remove(); sub[0].remove();
// array element refinements not yet enabled in Flow // array element refinements not yet enabled in Flow
var sub1 = sub[1]; sub1 && sub1.remove(); const sub1 = sub[1]; sub1 && sub1.remove();
} }
} }
subscriptions = []; subscriptions = [];

Просмотреть файл

@ -21,7 +21,7 @@ export type PackagerAsset = {
+type: string, +type: string,
}; };
var assets: Array<PackagerAsset> = []; const assets: Array<PackagerAsset> = [];
function registerAsset(asset: PackagerAsset): number { function registerAsset(asset: PackagerAsset): number {
// `push` returns new array length, so the first asset will // `push` returns new array length, so the first asset will

Просмотреть файл

@ -29,9 +29,9 @@ const invariant = require('fbjs/lib/invariant');
* Returns a path like 'assets/AwesomeModule/icon@2x.png' * Returns a path like 'assets/AwesomeModule/icon@2x.png'
*/ */
function getScaledAssetPath(asset): string { function getScaledAssetPath(asset): string {
var scale = AssetSourceResolver.pickScale(asset.scales, PixelRatio.get()); const scale = AssetSourceResolver.pickScale(asset.scales, PixelRatio.get());
var scaleSuffix = scale === 1 ? '' : '@' + scale + 'x'; const scaleSuffix = scale === 1 ? '' : '@' + scale + 'x';
var assetDir = assetPathUtils.getBasePath(asset); const assetDir = assetPathUtils.getBasePath(asset);
return assetDir + '/' + asset.name + scaleSuffix + '.' + asset.type; return assetDir + '/' + asset.name + scaleSuffix + '.' + asset.type;
} }
@ -39,9 +39,9 @@ function getScaledAssetPath(asset): string {
* Returns a path like 'drawable-mdpi/icon.png' * Returns a path like 'drawable-mdpi/icon.png'
*/ */
function getAssetPathInDrawableFolder(asset): string { function getAssetPathInDrawableFolder(asset): string {
var scale = AssetSourceResolver.pickScale(asset.scales, PixelRatio.get()); const scale = AssetSourceResolver.pickScale(asset.scales, PixelRatio.get());
var drawbleFolder = assetPathUtils.getAndroidResourceFolderName(asset, scale); const drawbleFolder = assetPathUtils.getAndroidResourceFolderName(asset, scale);
var fileName = assetPathUtils.getAndroidResourceIdentifier(asset); const fileName = assetPathUtils.getAndroidResourceIdentifier(asset);
return drawbleFolder + '/' + fileName + '.' + asset.type; return drawbleFolder + '/' + fileName + '.' + asset.type;
} }
@ -151,7 +151,7 @@ class AssetSourceResolver {
static pickScale(scales: Array<number>, deviceScale: number): number { static pickScale(scales: Array<number>, deviceScale: number): number {
// Packager guarantees that `scales` array is sorted // Packager guarantees that `scales` array is sorted
for (var i = 0; i < scales.length; i++) { for (let i = 0; i < scales.length; i++) {
if (scales[i] >= deviceScale) { if (scales[i] >= deviceScale) {
return scales[i]; return scales[i];
} }

Просмотреть файл

@ -10,25 +10,25 @@
'use strict'; 'use strict';
var ImageResizeMode = require('ImageResizeMode'); const ImageResizeMode = require('ImageResizeMode');
var ImageStylePropTypes = require('ImageStylePropTypes'); const ImageStylePropTypes = require('ImageStylePropTypes');
var NativeMethodsMixin = require('NativeMethodsMixin'); const NativeMethodsMixin = require('NativeMethodsMixin');
var NativeModules = require('NativeModules'); const NativeModules = require('NativeModules');
var React = require('React'); const React = require('React');
var PropTypes = require('prop-types'); const PropTypes = require('prop-types');
var ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
var StyleSheet = require('StyleSheet'); const StyleSheet = require('StyleSheet');
var StyleSheetPropType = require('StyleSheetPropType'); const StyleSheetPropType = require('StyleSheetPropType');
const TextAncestor = require('TextAncestor'); const TextAncestor = require('TextAncestor');
var ViewPropTypes = require('ViewPropTypes'); const ViewPropTypes = require('ViewPropTypes');
var createReactClass = require('create-react-class'); const createReactClass = require('create-react-class');
var flattenStyle = require('flattenStyle'); const flattenStyle = require('flattenStyle');
var merge = require('merge'); const merge = require('merge');
var requireNativeComponent = require('requireNativeComponent'); const requireNativeComponent = require('requireNativeComponent');
var resolveAssetSource = require('resolveAssetSource'); const resolveAssetSource = require('resolveAssetSource');
var {ImageLoader} = NativeModules; const {ImageLoader} = NativeModules;
let _requestId = 1; let _requestId = 1;
function generateRequestId() { function generateRequestId() {
@ -42,7 +42,7 @@ function generateRequestId() {
* *
* See https://facebook.github.io/react-native/docs/image.html * See https://facebook.github.io/react-native/docs/image.html
*/ */
var Image = createReactClass({ const Image = createReactClass({
displayName: 'Image', displayName: 'Image',
propTypes: { propTypes: {
...ViewPropTypes, ...ViewPropTypes,
@ -275,13 +275,13 @@ var Image = createReactClass({
}, },
}); });
var styles = StyleSheet.create({ const styles = StyleSheet.create({
base: { base: {
overflow: 'hidden', overflow: 'hidden',
}, },
}); });
var cfg = { const cfg = {
nativeOnly: { nativeOnly: {
src: true, src: true,
headers: true, headers: true,
@ -290,8 +290,8 @@ var cfg = {
shouldNotifyLoadEvents: true, shouldNotifyLoadEvents: true,
}, },
}; };
var RKImage = requireNativeComponent('RCTImageView', Image, cfg); const RKImage = requireNativeComponent('RCTImageView', Image, cfg);
var RCTTextInlineImage = requireNativeComponent( const RCTTextInlineImage = requireNativeComponent(
'RCTTextInlineImage', 'RCTTextInlineImage',
Image, Image,
cfg, cfg,

Просмотреть файл

@ -12,13 +12,13 @@
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and * found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */ * run Flow. */
var keyMirror = require('fbjs/lib/keyMirror'); const keyMirror = require('fbjs/lib/keyMirror');
/** /**
* ImageResizeMode - Enum for different image resizing modes, set via * ImageResizeMode - Enum for different image resizing modes, set via
* `resizeMode` style property on `<Image>` components. * `resizeMode` style property on `<Image>` components.
*/ */
var ImageResizeMode = keyMirror({ const ImageResizeMode = keyMirror({
/** /**
* contain - The image will be resized such that it will be completely * contain - The image will be resized such that it will be completely
* visible, contained within the frame of the View. * visible, contained within the frame of the View.

Просмотреть файл

@ -9,14 +9,14 @@
*/ */
'use strict'; 'use strict';
var ColorPropType = require('ColorPropType'); const ColorPropType = require('ColorPropType');
var ImageResizeMode = require('ImageResizeMode'); const ImageResizeMode = require('ImageResizeMode');
var LayoutPropTypes = require('LayoutPropTypes'); const LayoutPropTypes = require('LayoutPropTypes');
var ReactPropTypes = require('prop-types'); const ReactPropTypes = require('prop-types');
var ShadowPropTypesIOS = require('ShadowPropTypesIOS'); const ShadowPropTypesIOS = require('ShadowPropTypesIOS');
var TransformPropTypes = require('TransformPropTypes'); const TransformPropTypes = require('TransformPropTypes');
var ImageStylePropTypes = { const ImageStylePropTypes = {
...LayoutPropTypes, ...LayoutPropTypes,
...ShadowPropTypesIOS, ...ShadowPropTypesIOS,
...TransformPropTypes, ...TransformPropTypes,

Просмотреть файл

@ -11,7 +11,7 @@
// This is a stub for flow to make it understand require('./icon.png') // This is a stub for flow to make it understand require('./icon.png')
// See metro/src/Bundler/index.js // See metro/src/Bundler/index.js
var AssetRegistry = require('AssetRegistry'); const AssetRegistry = require('AssetRegistry');
module.exports = AssetRegistry.registerAsset({ module.exports = AssetRegistry.registerAsset({
__packager_asset: true, __packager_asset: true,

Просмотреть файл

@ -8,13 +8,13 @@
*/ */
'use strict'; 'use strict';
var AssetRegistry = require('AssetRegistry'); const AssetRegistry = require('AssetRegistry');
var Platform = require('Platform'); const Platform = require('Platform');
var NativeModules = require('NativeModules'); const NativeModules = require('NativeModules');
var resolveAssetSource = require('../resolveAssetSource'); const resolveAssetSource = require('../resolveAssetSource');
function expectResolvesAsset(input, expectedSource) { function expectResolvesAsset(input, expectedSource) {
var assetId = AssetRegistry.registerAsset(input); const assetId = AssetRegistry.registerAsset(input);
expect(resolveAssetSource(assetId)).toEqual(expectedSource); expect(resolveAssetSource(assetId)).toEqual(expectedSource);
} }
@ -24,10 +24,10 @@ describe('resolveAssetSource', () => {
}); });
it('returns same source for simple static and network images', () => { it('returns same source for simple static and network images', () => {
var source1 = {uri: 'https://www.facebook.com/logo'}; const source1 = {uri: 'https://www.facebook.com/logo'};
expect(resolveAssetSource(source1)).toBe(source1); expect(resolveAssetSource(source1)).toBe(source1);
var source2 = {uri: 'logo'}; const source2 = {uri: 'logo'};
expect(resolveAssetSource(source2)).toBe(source2); expect(resolveAssetSource(source2)).toBe(source2);
}); });

Просмотреть файл

@ -85,7 +85,7 @@ function resolveAssetSource(source: any): ?ResolvedAssetSource {
return source; return source;
} }
var asset = AssetRegistry.getAssetByID(source); const asset = AssetRegistry.getAssetByID(source);
if (!asset) { if (!asset) {
return null; return null;
} }

Просмотреть файл

@ -8,16 +8,16 @@
*/ */
'use strict'; 'use strict';
var React = require('React'); const React = require('React');
var View = require('View'); const View = require('View');
class BorderBox extends React.Component<$FlowFixMeProps> { class BorderBox extends React.Component<$FlowFixMeProps> {
render() { render() {
var box = this.props.box; const box = this.props.box;
if (!box) { if (!box) {
return this.props.children; return this.props.children;
} }
var style = { const style = {
borderTopWidth: box.top, borderTopWidth: box.top,
borderBottomWidth: box.bottom, borderBottomWidth: box.bottom,
borderLeftWidth: box.left, borderLeftWidth: box.left,

Просмотреть файл

@ -8,13 +8,13 @@
*/ */
'use strict'; 'use strict';
var React = require('React'); const React = require('React');
var StyleSheet = require('StyleSheet'); const StyleSheet = require('StyleSheet');
var Text = require('Text'); const Text = require('Text');
var View = require('View'); const View = require('View');
var resolveBoxStyle = require('resolveBoxStyle'); const resolveBoxStyle = require('resolveBoxStyle');
var blank = { const blank = {
top: 0, top: 0,
left: 0, left: 0,
right: 0, right: 0,
@ -23,10 +23,10 @@ var blank = {
class BoxInspector extends React.Component<$FlowFixMeProps> { class BoxInspector extends React.Component<$FlowFixMeProps> {
render() { render() {
var frame = this.props.frame; const frame = this.props.frame;
var style = this.props.style; const style = this.props.style;
var margin = style && resolveBoxStyle('margin', style) || blank; const margin = style && resolveBoxStyle('margin', style) || blank;
var padding = style && resolveBoxStyle('padding', style) || blank; const padding = style && resolveBoxStyle('padding', style) || blank;
return ( return (
<BoxContainer title="margin" titleStyle={styles.marginLabel} box={margin}> <BoxContainer title="margin" titleStyle={styles.marginLabel} box={margin}>
<BoxContainer title="padding" box={padding}> <BoxContainer title="padding" box={padding}>
@ -46,7 +46,7 @@ class BoxInspector extends React.Component<$FlowFixMeProps> {
class BoxContainer extends React.Component<$FlowFixMeProps> { class BoxContainer extends React.Component<$FlowFixMeProps> {
render() { render() {
var box = this.props.box; const box = this.props.box;
return ( return (
<View style={styles.box}> <View style={styles.box}>
<View style={styles.row}> <View style={styles.row}>
@ -66,7 +66,7 @@ class BoxContainer extends React.Component<$FlowFixMeProps> {
} }
} }
var styles = StyleSheet.create({ const styles = StyleSheet.create({
row: { row: {
flexDirection: 'row', flexDirection: 'row',
alignItems: 'center', alignItems: 'center',

Просмотреть файл

@ -8,20 +8,20 @@
*/ */
'use strict'; 'use strict';
var React = require('React'); const React = require('React');
var View = require('View'); const View = require('View');
var StyleSheet = require('StyleSheet'); const StyleSheet = require('StyleSheet');
var BorderBox = require('BorderBox'); const BorderBox = require('BorderBox');
var resolveBoxStyle = require('resolveBoxStyle'); const resolveBoxStyle = require('resolveBoxStyle');
var flattenStyle = require('flattenStyle'); const flattenStyle = require('flattenStyle');
class ElementBox extends React.Component<$FlowFixMeProps> { class ElementBox extends React.Component<$FlowFixMeProps> {
render() { render() {
var style = flattenStyle(this.props.style) || {}; const style = flattenStyle(this.props.style) || {};
var margin = resolveBoxStyle('margin', style); const margin = resolveBoxStyle('margin', style);
var padding = resolveBoxStyle('padding', style); const padding = resolveBoxStyle('padding', style);
var frameStyle = this.props.frame; let frameStyle = this.props.frame;
if (margin) { if (margin) {
frameStyle = { frameStyle = {
top: frameStyle.top - margin.top, top: frameStyle.top - margin.top,
@ -30,7 +30,7 @@ class ElementBox extends React.Component<$FlowFixMeProps> {
width: frameStyle.width + margin.left + margin.right, width: frameStyle.width + margin.left + margin.right,
}; };
} }
var contentStyle = { let contentStyle = {
width: this.props.frame.width, width: this.props.frame.width,
height: this.props.frame.height, height: this.props.frame.height,
}; };
@ -52,7 +52,7 @@ class ElementBox extends React.Component<$FlowFixMeProps> {
} }
} }
var styles = StyleSheet.create({ const styles = StyleSheet.create({
frame: { frame: {
position: 'absolute', position: 'absolute',
}, },

Просмотреть файл

@ -8,13 +8,13 @@
*/ */
'use strict'; 'use strict';
var Dimensions = require('Dimensions'); const Dimensions = require('Dimensions');
var ElementBox = require('ElementBox'); const ElementBox = require('ElementBox');
var PropTypes = require('prop-types'); const PropTypes = require('prop-types');
var React = require('React'); const React = require('React');
var StyleSheet = require('StyleSheet'); const StyleSheet = require('StyleSheet');
var UIManager = require('UIManager'); const UIManager = require('UIManager');
var View = require('View'); const View = require('View');
type EventLike = { type EventLike = {
nativeEvent: Object, nativeEvent: Object,
@ -38,7 +38,7 @@ class InspectorOverlay extends React.Component<{
}; };
findViewForTouchEvent = (e: EventLike) => { findViewForTouchEvent = (e: EventLike) => {
var {locationX, locationY} = e.nativeEvent.touches[0]; const {locationX, locationY} = e.nativeEvent.touches[0];
UIManager.findSubviewIn( UIManager.findSubviewIn(
this.props.inspectedViewTag, this.props.inspectedViewTag,
[locationX, locationY], [locationX, locationY],
@ -54,7 +54,7 @@ class InspectorOverlay extends React.Component<{
}; };
render() { render() {
var content = null; let content = null;
if (this.props.inspected) { if (this.props.inspected) {
content = <ElementBox frame={this.props.inspected.frame} style={this.props.inspected.style} />; content = <ElementBox frame={this.props.inspected.frame} style={this.props.inspected.style} />;
} }
@ -70,7 +70,7 @@ class InspectorOverlay extends React.Component<{
} }
} }
var styles = StyleSheet.create({ const styles = StyleSheet.create({
inspector: { inspector: {
backgroundColor: 'transparent', backgroundColor: 'transparent',
position: 'absolute', position: 'absolute',

Просмотреть файл

@ -8,20 +8,20 @@
*/ */
'use strict'; 'use strict';
var PerformanceLogger = require('PerformanceLogger'); const PerformanceLogger = require('PerformanceLogger');
var React = require('React'); const React = require('React');
var StyleSheet = require('StyleSheet'); const StyleSheet = require('StyleSheet');
var Text = require('Text'); const Text = require('Text');
var View = require('View'); const View = require('View');
class PerformanceOverlay extends React.Component<{}> { class PerformanceOverlay extends React.Component<{}> {
render() { render() {
var perfLogs = PerformanceLogger.getTimespans(); const perfLogs = PerformanceLogger.getTimespans();
var items = []; const items = [];
for (var key in perfLogs) { for (const key in perfLogs) {
if (perfLogs[key].totalTime) { if (perfLogs[key].totalTime) {
var unit = (key === 'BundleSize') ? 'b' : 'ms'; const unit = (key === 'BundleSize') ? 'b' : 'ms';
items.push( items.push(
<View style={styles.row} key={key}> <View style={styles.row} key={key}>
<Text style={[styles.text, styles.label]}>{key}</Text> <Text style={[styles.text, styles.label]}>{key}</Text>
@ -41,7 +41,7 @@ class PerformanceOverlay extends React.Component<{}> {
} }
} }
var styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
height: 100, height: 100,
paddingTop: 10, paddingTop: 10,

Просмотреть файл

@ -8,17 +8,17 @@
*/ */
'use strict'; 'use strict';
var React = require('React'); const React = require('React');
var StyleSheet = require('StyleSheet'); const StyleSheet = require('StyleSheet');
var Text = require('Text'); const Text = require('Text');
var View = require('View'); const View = require('View');
class StyleInspector extends React.Component<$FlowFixMeProps> { class StyleInspector extends React.Component<$FlowFixMeProps> {
render() { render() {
if (!this.props.style) { if (!this.props.style) {
return <Text style={styles.noStyle}>No style</Text>; return <Text style={styles.noStyle}>No style</Text>;
} }
var names = Object.keys(this.props.style); const names = Object.keys(this.props.style);
return ( return (
<View style={styles.container}> <View style={styles.container}>
<View> <View>
@ -27,7 +27,7 @@ class StyleInspector extends React.Component<$FlowFixMeProps> {
<View> <View>
{names.map(name => { {names.map(name => {
var value = typeof this.props.style[name] === 'object' ? JSON.stringify(this.props.style[name]) : this.props.style[name]; const value = typeof this.props.style[name] === 'object' ? JSON.stringify(this.props.style[name]) : this.props.style[name];
return <Text key={name} style={styles.value}>{value}</Text>; return <Text key={name} style={styles.value}>{value}</Text>;
} ) } } ) }
</View> </View>
@ -36,7 +36,7 @@ class StyleInspector extends React.Component<$FlowFixMeProps> {
} }
} }
var styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
flexDirection: 'row', flexDirection: 'row',
}, },

Просмотреть файл

@ -18,9 +18,9 @@
* If none are set, returns false. * If none are set, returns false.
*/ */
function resolveBoxStyle(prefix: string, style: Object): ?Object { function resolveBoxStyle(prefix: string, style: Object): ?Object {
var res = {}; const res = {};
var subs = ['top', 'left', 'bottom', 'right']; const subs = ['top', 'left', 'bottom', 'right'];
var set = false; let set = false;
subs.forEach(sub => { subs.forEach(sub => {
res[sub] = style[prefix] || 0; res[sub] = style[prefix] || 0;
}); });
@ -36,7 +36,7 @@ function resolveBoxStyle(prefix: string, style: Object): ?Object {
set = true; set = true;
} }
subs.forEach(sub => { subs.forEach(sub => {
var val = style[prefix + capFirst(sub)]; const val = style[prefix + capFirst(sub)];
if (val) { if (val) {
res[sub] = val; res[sub] = val;
set = true; set = true;

Просмотреть файл

@ -77,7 +77,7 @@ const DEBUG = false;
* allowing events such as touches to start interactions and block queued tasks * allowing events such as touches to start interactions and block queued tasks
* from executing, making apps more responsive. * from executing, making apps more responsive.
*/ */
var InteractionManager = { const InteractionManager = {
Events: keyMirror({ Events: keyMirror({
interactionStart: true, interactionStart: true,
interactionComplete: true, interactionComplete: true,
@ -118,7 +118,7 @@ var InteractionManager = {
createInteractionHandle(): Handle { createInteractionHandle(): Handle {
DEBUG && infoLog('create interaction handle'); DEBUG && infoLog('create interaction handle');
_scheduleUpdate(); _scheduleUpdate();
var handle = ++_inc; const handle = ++_inc;
_addInteractionSet.add(handle); _addInteractionSet.add(handle);
return handle; return handle;
}, },
@ -181,14 +181,14 @@ function _scheduleUpdate() {
function _processUpdate() { function _processUpdate() {
_nextUpdateHandle = 0; _nextUpdateHandle = 0;
var interactionCount = _interactionSet.size; const interactionCount = _interactionSet.size;
_addInteractionSet.forEach(handle => _addInteractionSet.forEach(handle =>
_interactionSet.add(handle) _interactionSet.add(handle)
); );
_deleteInteractionSet.forEach(handle => _deleteInteractionSet.forEach(handle =>
_interactionSet.delete(handle) _interactionSet.delete(handle)
); );
var nextInteractionCount = _interactionSet.size; const nextInteractionCount = _interactionSet.size;
if (interactionCount !== 0 && nextInteractionCount === 0) { if (interactionCount !== 0 && nextInteractionCount === 0) {
// transition from 1+ --> 0 interactions // transition from 1+ --> 0 interactions

Просмотреть файл

@ -8,14 +8,14 @@
*/ */
'use strict'; 'use strict';
var InteractionManager = require('InteractionManager'); const InteractionManager = require('InteractionManager');
/** /**
* This mixin provides safe versions of InteractionManager start/end methods * This mixin provides safe versions of InteractionManager start/end methods
* that ensures `clearInteractionHandle` is always called * that ensures `clearInteractionHandle` is always called
* once per start, even if the component is unmounted. * once per start, even if the component is unmounted.
*/ */
var InteractionMixin = { const InteractionMixin = {
componentWillUnmount: function() { componentWillUnmount: function() {
while (this._interactionMixinHandles.length) { while (this._interactionMixinHandles.length) {
InteractionManager.clearInteractionHandle( InteractionManager.clearInteractionHandle(
@ -27,7 +27,7 @@ var InteractionMixin = {
_interactionMixinHandles: ([]: Array<number>), _interactionMixinHandles: ([]: Array<number>),
createInteractionHandle: function() { createInteractionHandle: function() {
var handle = InteractionManager.createInteractionHandle(); const handle = InteractionManager.createInteractionHandle();
this._interactionMixinHandles.push(handle); this._interactionMixinHandles.push(handle);
return handle; return handle;
}, },

Просмотреть файл

@ -11,9 +11,9 @@
jest.enableAutomock().unmock('InteractionMixin'); jest.enableAutomock().unmock('InteractionMixin');
describe('InteractionMixin', () => { describe('InteractionMixin', () => {
var InteractionManager; let InteractionManager;
var InteractionMixin; let InteractionMixin;
var component; let component;
beforeEach(() => { beforeEach(() => {
jest.resetModules(); jest.resetModules();
@ -29,19 +29,19 @@ describe('InteractionMixin', () => {
}); });
it('should end interactions', () => { it('should end interactions', () => {
var handle = {}; const handle = {};
component.clearInteractionHandle(handle); component.clearInteractionHandle(handle);
expect(InteractionManager.clearInteractionHandle).toBeCalledWith(handle); expect(InteractionManager.clearInteractionHandle).toBeCalledWith(handle);
}); });
it('should schedule tasks', () => { it('should schedule tasks', () => {
var task = jest.fn(); const task = jest.fn();
component.runAfterInteractions(task); component.runAfterInteractions(task);
expect(InteractionManager.runAfterInteractions).toBeCalledWith(task); expect(InteractionManager.runAfterInteractions).toBeCalledWith(task);
}); });
it('should end unfinished interactions in componentWillUnmount', () => { it('should end unfinished interactions in componentWillUnmount', () => {
var handle = component.createInteractionHandle(); const handle = component.createInteractionHandle();
component.componentWillUnmount(); component.componentWillUnmount();
expect(InteractionManager.clearInteractionHandle).toBeCalledWith(handle); expect(InteractionManager.clearInteractionHandle).toBeCalledWith(handle);
}); });

Просмотреть файл

@ -9,34 +9,34 @@
*/ */
'use strict'; 'use strict';
var ListViewDataSource = require('ListViewDataSource'); const ListViewDataSource = require('ListViewDataSource');
var Platform = require('Platform'); const Platform = require('Platform');
var React = require('React'); const React = require('React');
var PropTypes = require('prop-types'); const PropTypes = require('prop-types');
var ReactNative = require('ReactNative'); const ReactNative = require('ReactNative');
var RCTScrollViewManager = require('NativeModules').ScrollViewManager; const RCTScrollViewManager = require('NativeModules').ScrollViewManager;
var ScrollView = require('ScrollView'); const ScrollView = require('ScrollView');
var ScrollResponder = require('ScrollResponder'); const ScrollResponder = require('ScrollResponder');
var StaticRenderer = require('StaticRenderer'); const StaticRenderer = require('StaticRenderer');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and * found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */ * run Flow. */
var TimerMixin = require('react-timer-mixin'); const TimerMixin = require('react-timer-mixin');
var View = require('View'); const View = require('View');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and * found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */ * run Flow. */
var cloneReferencedElement = require('react-clone-referenced-element'); const cloneReferencedElement = require('react-clone-referenced-element');
var createReactClass = require('create-react-class'); const createReactClass = require('create-react-class');
var isEmpty = require('isEmpty'); const isEmpty = require('isEmpty');
var merge = require('merge'); const merge = require('merge');
var DEFAULT_PAGE_SIZE = 1; const DEFAULT_PAGE_SIZE = 1;
var DEFAULT_INITIAL_ROWS = 10; const DEFAULT_INITIAL_ROWS = 10;
var DEFAULT_SCROLL_RENDER_AHEAD = 1000; const DEFAULT_SCROLL_RENDER_AHEAD = 1000;
var DEFAULT_END_REACHED_THRESHOLD = 1000; const DEFAULT_END_REACHED_THRESHOLD = 1000;
var DEFAULT_SCROLL_CALLBACK_THROTTLE = 50; const DEFAULT_SCROLL_CALLBACK_THROTTLE = 50;
/** /**
* DEPRECATED - use one of the new list components, such as [`FlatList`](docs/flatlist.html) * DEPRECATED - use one of the new list components, such as [`FlatList`](docs/flatlist.html)
@ -95,7 +95,7 @@ var DEFAULT_SCROLL_CALLBACK_THROTTLE = 50;
* rendering rows. * rendering rows.
*/ */
var ListView = createReactClass({ const ListView = createReactClass({
displayName: 'ListView', displayName: 'ListView',
_childFrames: ([]: Array<Object>), _childFrames: ([]: Array<Object>),
_sentEndForContentLength: (null: ?number), _sentEndForContentLength: (null: ?number),
@ -405,28 +405,28 @@ var ListView = createReactClass({
}, },
render: function() { render: function() {
var bodyComponents = []; const bodyComponents = [];
var dataSource = this.props.dataSource; const dataSource = this.props.dataSource;
var allRowIDs = dataSource.rowIdentities; const allRowIDs = dataSource.rowIdentities;
var rowCount = 0; let rowCount = 0;
var stickySectionHeaderIndices = []; const stickySectionHeaderIndices = [];
const {renderSectionHeader} = this.props; const {renderSectionHeader} = this.props;
var header = this.props.renderHeader && this.props.renderHeader(); const header = this.props.renderHeader && this.props.renderHeader();
var footer = this.props.renderFooter && this.props.renderFooter(); const footer = this.props.renderFooter && this.props.renderFooter();
var totalIndex = header ? 1 : 0; let totalIndex = header ? 1 : 0;
for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) { for (let sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) {
var sectionID = dataSource.sectionIdentities[sectionIdx]; const sectionID = dataSource.sectionIdentities[sectionIdx];
var rowIDs = allRowIDs[sectionIdx]; const rowIDs = allRowIDs[sectionIdx];
if (rowIDs.length === 0) { if (rowIDs.length === 0) {
if (this.props.enableEmptySections === undefined) { if (this.props.enableEmptySections === undefined) {
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses
* an error found when Flow v0.54 was deployed. To see the error * an error found when Flow v0.54 was deployed. To see the error
* delete this comment and run Flow. */ * delete this comment and run Flow. */
var warning = require('fbjs/lib/warning'); const warning = require('fbjs/lib/warning');
warning( warning(
false, false,
'In next release empty section headers will be rendered.' + 'In next release empty section headers will be rendered.' +
@ -434,7 +434,7 @@ var ListView = createReactClass({
); );
continue; continue;
} else { } else {
var invariant = require('fbjs/lib/invariant'); const invariant = require('fbjs/lib/invariant');
invariant( invariant(
this.props.enableEmptySections, this.props.enableEmptySections,
"In next release 'enableEmptySections' flag will be deprecated, empty section headers will always be rendered." + "In next release 'enableEmptySections' flag will be deprecated, empty section headers will always be rendered." +
@ -460,13 +460,13 @@ var ListView = createReactClass({
} }
} }
for (var rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) { for (let rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) {
var rowID = rowIDs[rowIdx]; const rowID = rowIDs[rowIdx];
var comboID = sectionID + '_' + rowID; const comboID = sectionID + '_' + rowID;
var shouldUpdateRow = const shouldUpdateRow =
rowCount >= this._prevRenderedRowsCount && rowCount >= this._prevRenderedRowsCount &&
dataSource.rowShouldUpdate(sectionIdx, rowIdx); dataSource.rowShouldUpdate(sectionIdx, rowIdx);
var row = ( const row = (
<StaticRenderer <StaticRenderer
key={'r_' + comboID} key={'r_' + comboID}
shouldUpdate={!!shouldUpdateRow} shouldUpdate={!!shouldUpdateRow}
@ -486,11 +486,11 @@ var ListView = createReactClass({
this.props.renderSeparator && this.props.renderSeparator &&
(rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1) (rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1)
) { ) {
var adjacentRowHighlighted = const adjacentRowHighlighted =
this.state.highlightedRow.sectionID === sectionID && this.state.highlightedRow.sectionID === sectionID &&
(this.state.highlightedRow.rowID === rowID || (this.state.highlightedRow.rowID === rowID ||
this.state.highlightedRow.rowID === rowIDs[rowIdx + 1]); this.state.highlightedRow.rowID === rowIDs[rowIdx + 1]);
var separator = this.props.renderSeparator( const separator = this.props.renderSeparator(
sectionID, sectionID,
rowID, rowID,
adjacentRowHighlighted, adjacentRowHighlighted,
@ -509,7 +509,7 @@ var ListView = createReactClass({
} }
} }
var {renderScrollComponent, ...props} = this.props; const {renderScrollComponent, ...props} = this.props;
if (!props.scrollEventThrottle) { if (!props.scrollEventThrottle) {
props.scrollEventThrottle = DEFAULT_SCROLL_CALLBACK_THROTTLE; props.scrollEventThrottle = DEFAULT_SCROLL_CALLBACK_THROTTLE;
} }
@ -550,7 +550,7 @@ var ListView = createReactClass({
*/ */
_measureAndUpdateScrollProps: function() { _measureAndUpdateScrollProps: function() {
var scrollComponent = this.getScrollResponder(); const scrollComponent = this.getScrollResponder();
if (!scrollComponent || !scrollComponent.getInnerViewNode) { if (!scrollComponent || !scrollComponent.getInnerViewNode) {
return; return;
} }
@ -570,7 +570,7 @@ var ListView = createReactClass({
}, },
_onContentSizeChange: function(width: number, height: number) { _onContentSizeChange: function(width: number, height: number) {
var contentLength = !this.props.horizontal ? height : width; const contentLength = !this.props.horizontal ? height : width;
if (contentLength !== this.scrollProperties.contentLength) { if (contentLength !== this.scrollProperties.contentLength) {
this.scrollProperties.contentLength = contentLength; this.scrollProperties.contentLength = contentLength;
this._updateVisibleRows(); this._updateVisibleRows();
@ -581,8 +581,8 @@ var ListView = createReactClass({
}, },
_onLayout: function(event: Object) { _onLayout: function(event: Object) {
var {width, height} = event.nativeEvent.layout; const {width, height} = event.nativeEvent.layout;
var visibleLength = !this.props.horizontal ? height : width; const visibleLength = !this.props.horizontal ? height : width;
if (visibleLength !== this.scrollProperties.visibleLength) { if (visibleLength !== this.scrollProperties.visibleLength) {
this.scrollProperties.visibleLength = visibleLength; this.scrollProperties.visibleLength = visibleLength;
this._updateVisibleRows(); this._updateVisibleRows();
@ -622,7 +622,7 @@ var ListView = createReactClass({
return; return;
} }
var distanceFromEnd = this._getDistanceFromEnd(this.scrollProperties); const distanceFromEnd = this._getDistanceFromEnd(this.scrollProperties);
if (distanceFromEnd < this.props.scrollRenderAheadDistance) { if (distanceFromEnd < this.props.scrollRenderAheadDistance) {
this._pageInNewRows(); this._pageInNewRows();
} }
@ -631,7 +631,7 @@ var ListView = createReactClass({
_pageInNewRows: function() { _pageInNewRows: function() {
this.setState( this.setState(
(state, props) => { (state, props) => {
var rowsToRender = Math.min( const rowsToRender = Math.min(
state.curRenderedRowsCount + props.pageSize, state.curRenderedRowsCount + props.pageSize,
props.enableEmptySections props.enableEmptySections
? props.dataSource.getRowAndSectionCount() ? props.dataSource.getRowAndSectionCount()
@ -666,32 +666,32 @@ var ListView = createReactClass({
this._childFrames[newFrame.index] = merge(newFrame); this._childFrames[newFrame.index] = merge(newFrame);
}); });
} }
var isVertical = !this.props.horizontal; const isVertical = !this.props.horizontal;
var dataSource = this.props.dataSource; const dataSource = this.props.dataSource;
var visibleMin = this.scrollProperties.offset; const visibleMin = this.scrollProperties.offset;
var visibleMax = visibleMin + this.scrollProperties.visibleLength; const visibleMax = visibleMin + this.scrollProperties.visibleLength;
var allRowIDs = dataSource.rowIdentities; const allRowIDs = dataSource.rowIdentities;
var header = this.props.renderHeader && this.props.renderHeader(); const header = this.props.renderHeader && this.props.renderHeader();
var totalIndex = header ? 1 : 0; let totalIndex = header ? 1 : 0;
var visibilityChanged = false; let visibilityChanged = false;
var changedRows = {}; const changedRows = {};
for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) { for (let sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) {
var rowIDs = allRowIDs[sectionIdx]; const rowIDs = allRowIDs[sectionIdx];
if (rowIDs.length === 0) { if (rowIDs.length === 0) {
continue; continue;
} }
var sectionID = dataSource.sectionIdentities[sectionIdx]; const sectionID = dataSource.sectionIdentities[sectionIdx];
if (this.props.renderSectionHeader) { if (this.props.renderSectionHeader) {
totalIndex++; totalIndex++;
} }
var visibleSection = this._visibleRows[sectionID]; let visibleSection = this._visibleRows[sectionID];
if (!visibleSection) { if (!visibleSection) {
visibleSection = {}; visibleSection = {};
} }
for (var rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) { for (let rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) {
var rowID = rowIDs[rowIdx]; const rowID = rowIDs[rowIdx];
var frame = this._childFrames[totalIndex]; const frame = this._childFrames[totalIndex];
totalIndex++; totalIndex++;
if ( if (
this.props.renderSeparator && this.props.renderSeparator &&
@ -702,9 +702,9 @@ var ListView = createReactClass({
if (!frame) { if (!frame) {
break; break;
} }
var rowVisible = visibleSection[rowID]; const rowVisible = visibleSection[rowID];
var min = isVertical ? frame.y : frame.x; const min = isVertical ? frame.y : frame.x;
var max = min + (isVertical ? frame.height : frame.width); const max = min + (isVertical ? frame.height : frame.width);
if ((!min && !max) || min === max) { if ((!min && !max) || min === max) {
break; break;
} }
@ -737,7 +737,7 @@ var ListView = createReactClass({
}, },
_onScroll: function(e: Object) { _onScroll: function(e: Object) {
var isVertical = !this.props.horizontal; const isVertical = !this.props.horizontal;
this.scrollProperties.visibleLength = this.scrollProperties.visibleLength =
e.nativeEvent.layoutMeasurement[isVertical ? 'height' : 'width']; e.nativeEvent.layoutMeasurement[isVertical ? 'height' : 'width'];
this.scrollProperties.contentLength = this.scrollProperties.contentLength =

Просмотреть файл

@ -9,12 +9,12 @@
*/ */
'use strict'; 'use strict';
var invariant = require('fbjs/lib/invariant'); const invariant = require('fbjs/lib/invariant');
var isEmpty = require('isEmpty'); const isEmpty = require('isEmpty');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and * found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */ * run Flow. */
var warning = require('fbjs/lib/warning'); const warning = require('fbjs/lib/warning');
function defaultGetRowData( function defaultGetRowData(
dataBlob: any, dataBlob: any,
@ -142,7 +142,7 @@ class ListViewDataSource {
dataBlob: $ReadOnlyArray<any> | {+[key: string]: any}, dataBlob: $ReadOnlyArray<any> | {+[key: string]: any},
rowIdentities: ?$ReadOnlyArray<string>, rowIdentities: ?$ReadOnlyArray<string>,
): ListViewDataSource { ): ListViewDataSource {
var rowIds = rowIdentities ? [[...rowIdentities]] : null; const rowIds = rowIdentities ? [[...rowIdentities]] : null;
if (!this._sectionHeaderHasChanged) { if (!this._sectionHeaderHasChanged) {
this._sectionHeaderHasChanged = () => false; this._sectionHeaderHasChanged = () => false;
} }
@ -184,7 +184,7 @@ class ListViewDataSource {
'row and section ids lengths must be the same', 'row and section ids lengths must be the same',
); );
var newSource = new ListViewDataSource({ const newSource = new ListViewDataSource({
getRowData: this._getRowData, getRowData: this._getRowData,
getSectionHeaderData: this._getSectionHeaderData, getSectionHeaderData: this._getSectionHeaderData,
rowHasChanged: this._rowHasChanged, rowHasChanged: this._rowHasChanged,
@ -237,7 +237,7 @@ class ListViewDataSource {
* Returns if the row is dirtied and needs to be rerendered * Returns if the row is dirtied and needs to be rerendered
*/ */
rowShouldUpdate(sectionIndex: number, rowIndex: number): boolean { rowShouldUpdate(sectionIndex: number, rowIndex: number): boolean {
var needsUpdate = this._dirtyRows[sectionIndex][rowIndex]; const needsUpdate = this._dirtyRows[sectionIndex][rowIndex];
warning( warning(
needsUpdate !== undefined, needsUpdate !== undefined,
'missing dirtyBit for section, row: ' + sectionIndex + ', ' + rowIndex, 'missing dirtyBit for section, row: ' + sectionIndex + ', ' + rowIndex,
@ -249,8 +249,8 @@ class ListViewDataSource {
* Gets the data required to render the row. * Gets the data required to render the row.
*/ */
getRowData(sectionIndex: number, rowIndex: number): any { getRowData(sectionIndex: number, rowIndex: number): any {
var sectionID = this.sectionIdentities[sectionIndex]; const sectionID = this.sectionIdentities[sectionIndex];
var rowID = this.rowIdentities[sectionIndex][rowIndex]; const rowID = this.rowIdentities[sectionIndex][rowIndex];
warning( warning(
sectionID !== undefined && rowID !== undefined, sectionID !== undefined && rowID !== undefined,
'rendering invalid section, row: ' + sectionIndex + ', ' + rowIndex, 'rendering invalid section, row: ' + sectionIndex + ', ' + rowIndex,
@ -263,8 +263,8 @@ class ListViewDataSource {
* or null of out of range indexes. * or null of out of range indexes.
*/ */
getRowIDForFlatIndex(index: number): ?string { getRowIDForFlatIndex(index: number): ?string {
var accessIndex = index; let accessIndex = index;
for (var ii = 0; ii < this.sectionIdentities.length; ii++) { for (let ii = 0; ii < this.sectionIdentities.length; ii++) {
if (accessIndex >= this.rowIdentities[ii].length) { if (accessIndex >= this.rowIdentities[ii].length) {
accessIndex -= this.rowIdentities[ii].length; accessIndex -= this.rowIdentities[ii].length;
} else { } else {
@ -279,8 +279,8 @@ class ListViewDataSource {
* or null for out of range indexes. * or null for out of range indexes.
*/ */
getSectionIDForFlatIndex(index: number): ?string { getSectionIDForFlatIndex(index: number): ?string {
var accessIndex = index; let accessIndex = index;
for (var ii = 0; ii < this.sectionIdentities.length; ii++) { for (let ii = 0; ii < this.sectionIdentities.length; ii++) {
if (accessIndex >= this.rowIdentities[ii].length) { if (accessIndex >= this.rowIdentities[ii].length) {
accessIndex -= this.rowIdentities[ii].length; accessIndex -= this.rowIdentities[ii].length;
} else { } else {
@ -294,8 +294,8 @@ class ListViewDataSource {
* Returns an array containing the number of rows in each section * Returns an array containing the number of rows in each section
*/ */
getSectionLengths(): Array<number> { getSectionLengths(): Array<number> {
var results = []; const results = [];
for (var ii = 0; ii < this.sectionIdentities.length; ii++) { for (let ii = 0; ii < this.sectionIdentities.length; ii++) {
results.push(this.rowIdentities[ii].length); results.push(this.rowIdentities[ii].length);
} }
return results; return results;
@ -305,7 +305,7 @@ class ListViewDataSource {
* Returns if the section header is dirtied and needs to be rerendered * Returns if the section header is dirtied and needs to be rerendered
*/ */
sectionHeaderShouldUpdate(sectionIndex: number): boolean { sectionHeaderShouldUpdate(sectionIndex: number): boolean {
var needsUpdate = this._dirtySections[sectionIndex]; const needsUpdate = this._dirtySections[sectionIndex];
warning( warning(
needsUpdate !== undefined, needsUpdate !== undefined,
'missing dirtyBit for section: ' + sectionIndex, 'missing dirtyBit for section: ' + sectionIndex,
@ -320,7 +320,7 @@ class ListViewDataSource {
if (!this._getSectionHeaderData) { if (!this._getSectionHeaderData) {
return null; return null;
} }
var sectionID = this.sectionIdentities[sectionIndex]; const sectionID = this.sectionIdentities[sectionIndex];
warning( warning(
sectionID !== undefined, sectionID !== undefined,
'renderSection called on invalid section: ' + sectionIndex, 'renderSection called on invalid section: ' + sectionIndex,
@ -353,9 +353,9 @@ class ListViewDataSource {
prevRowIDs: Array<Array<string>>, prevRowIDs: Array<Array<string>>,
): void { ): void {
// construct a hashmap of the existing (old) id arrays // construct a hashmap of the existing (old) id arrays
var prevSectionsHash = keyedDictionaryFromArray(prevSectionIDs); const prevSectionsHash = keyedDictionaryFromArray(prevSectionIDs);
var prevRowsHash = {}; const prevRowsHash = {};
for (var ii = 0; ii < prevRowIDs.length; ii++) { for (let ii = 0; ii < prevRowIDs.length; ii++) {
var sectionID = prevSectionIDs[ii]; var sectionID = prevSectionIDs[ii];
warning( warning(
!prevRowsHash[sectionID], !prevRowsHash[sectionID],
@ -368,12 +368,12 @@ class ListViewDataSource {
this._dirtySections = []; this._dirtySections = [];
this._dirtyRows = []; this._dirtyRows = [];
var dirty; let dirty;
for (var sIndex = 0; sIndex < this.sectionIdentities.length; sIndex++) { for (let sIndex = 0; sIndex < this.sectionIdentities.length; sIndex++) {
var sectionID = this.sectionIdentities[sIndex]; var sectionID = this.sectionIdentities[sIndex];
// dirty if the sectionHeader is new or _sectionHasChanged is true // dirty if the sectionHeader is new or _sectionHasChanged is true
dirty = !prevSectionsHash[sectionID]; dirty = !prevSectionsHash[sectionID];
var sectionHeaderHasChanged = this._sectionHeaderHasChanged; const sectionHeaderHasChanged = this._sectionHeaderHasChanged;
if (!dirty && sectionHeaderHasChanged) { if (!dirty && sectionHeaderHasChanged) {
dirty = sectionHeaderHasChanged( dirty = sectionHeaderHasChanged(
this._getSectionHeaderData(prevDataBlob, sectionID), this._getSectionHeaderData(prevDataBlob, sectionID),
@ -384,11 +384,11 @@ class ListViewDataSource {
this._dirtyRows[sIndex] = []; this._dirtyRows[sIndex] = [];
for ( for (
var rIndex = 0; let rIndex = 0;
rIndex < this.rowIdentities[sIndex].length; rIndex < this.rowIdentities[sIndex].length;
rIndex++ rIndex++
) { ) {
var rowID = this.rowIdentities[sIndex][rIndex]; const rowID = this.rowIdentities[sIndex][rIndex];
// dirty if the section is new, row is new or _rowHasChanged is true // dirty if the section is new, row is new or _rowHasChanged is true
dirty = dirty =
!prevSectionsHash[sectionID] || !prevSectionsHash[sectionID] ||
@ -404,9 +404,9 @@ class ListViewDataSource {
} }
function countRows(allRowIDs) { function countRows(allRowIDs) {
var totalRows = 0; let totalRows = 0;
for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) { for (let sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) {
var rowIDs = allRowIDs[sectionIdx]; const rowIDs = allRowIDs[sectionIdx];
totalRows += rowIDs.length; totalRows += rowIDs.length;
} }
return totalRows; return totalRows;
@ -416,9 +416,9 @@ function keyedDictionaryFromArray(arr) {
if (isEmpty(arr)) { if (isEmpty(arr)) {
return {}; return {};
} }
var result = {}; const result = {};
for (var ii = 0; ii < arr.length; ii++) { for (let ii = 0; ii < arr.length; ii++) {
var key = arr[ii]; const key = arr[ii];
warning(!result[key], 'Value appears more than once in array: ' + key); warning(!result[key], 'Value appears more than once in array: ' + key);
result[key] = true; result[key] = true;
} }

Просмотреть файл

@ -36,7 +36,7 @@ import type EmitterSubscription from 'EmitterSubscription';
// <Modal> on screen. There can be different ones, either nested or as siblings. // <Modal> on screen. There can be different ones, either nested or as siblings.
// We cannot pass the onDismiss callback to native as the view will be // We cannot pass the onDismiss callback to native as the view will be
// destroyed before the callback is fired. // destroyed before the callback is fired.
var uniqueModalIdentifier = 0; let uniqueModalIdentifier = 0;
class Modal extends React.Component<Object> { class Modal extends React.Component<Object> {
static propTypes = { static propTypes = {

Просмотреть файл

@ -60,9 +60,9 @@ class FormData {
getParts(): Array<FormDataPart> { getParts(): Array<FormDataPart> {
return this._parts.map(([name, value]) => { return this._parts.map(([name, value]) => {
var contentDisposition = 'form-data; name="' + name + '"'; const contentDisposition = 'form-data; name="' + name + '"';
var headers: Headers = {'content-disposition': contentDisposition}; const headers: Headers = {'content-disposition': contentDisposition};
// The body part is a "blob", which in React Native just means // The body part is a "blob", which in React Native just means
// an object with a `uri` attribute. Optionally, it can also // an object with a `uri` attribute. Optionally, it can also

Просмотреть файл

@ -12,13 +12,13 @@ const originalXHROpen = XMLHttpRequest.prototype.open;
const originalXHRSend = XMLHttpRequest.prototype.send; const originalXHRSend = XMLHttpRequest.prototype.send;
const originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader; const originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
var openCallback; let openCallback;
var sendCallback; let sendCallback;
var requestHeaderCallback; let requestHeaderCallback;
var headerReceivedCallback; let headerReceivedCallback;
var responseCallback; let responseCallback;
var isInterceptorEnabled = false; let isInterceptorEnabled = false;
/** /**
* A network interceptor which monkey-patches XMLHttpRequest methods * A network interceptor which monkey-patches XMLHttpRequest methods

Просмотреть файл

@ -421,14 +421,14 @@ class XMLHttpRequest extends EventTarget(...XHR_EVENTS) {
// according to the spec, return null if no response has been received // according to the spec, return null if no response has been received
return null; return null;
} }
var headers = this.responseHeaders || {}; const headers = this.responseHeaders || {};
return Object.keys(headers).map((headerName) => { return Object.keys(headers).map((headerName) => {
return headerName + ': ' + headers[headerName]; return headerName + ': ' + headers[headerName];
}).join('\r\n'); }).join('\r\n');
} }
getResponseHeader(header: string): ?string { getResponseHeader(header: string): ?string {
var value = this._lowerCaseResponseHeaders[header.toLowerCase()]; const value = this._lowerCaseResponseHeaders[header.toLowerCase()];
return value !== undefined ? value : null; return value !== undefined ? value : null;
} }
@ -545,7 +545,7 @@ class XMLHttpRequest extends EventTarget(...XHR_EVENTS) {
setResponseHeaders(responseHeaders: ?Object): void { setResponseHeaders(responseHeaders: ?Object): void {
this.responseHeaders = responseHeaders || null; this.responseHeaders = responseHeaders || null;
var headers = responseHeaders || {}; const headers = responseHeaders || {};
this._lowerCaseResponseHeaders = this._lowerCaseResponseHeaders =
Object.keys(headers).reduce((lcaseHeaders, headerName) => { Object.keys(headers).reduce((lcaseHeaders, headerName) => {
lcaseHeaders[headerName.toLowerCase()] = headers[headerName]; lcaseHeaders[headerName.toLowerCase()] = headers[headerName];

Просмотреть файл

@ -182,7 +182,7 @@ class PushNotificationIOS {
type === 'notification' || type === 'register' || type === 'registrationError' || type === 'localNotification', type === 'notification' || type === 'register' || type === 'registrationError' || type === 'localNotification',
'PushNotificationIOS only supports `notification`, `register`, `registrationError`, and `localNotification` events' 'PushNotificationIOS only supports `notification`, `register`, `registrationError`, and `localNotification` events'
); );
var listener; let listener;
if (type === 'notification') { if (type === 'notification') {
listener = PushNotificationEmitter.addListener( listener = PushNotificationEmitter.addListener(
DEVICE_NOTIF_EVENT, DEVICE_NOTIF_EVENT,
@ -226,7 +226,7 @@ class PushNotificationIOS {
type === 'notification' || type === 'register' || type === 'registrationError' || type === 'localNotification', type === 'notification' || type === 'register' || type === 'registrationError' || type === 'localNotification',
'PushNotificationIOS only supports `notification`, `register`, `registrationError`, and `localNotification` events' 'PushNotificationIOS only supports `notification`, `register`, `registrationError`, and `localNotification` events'
); );
var listener = _notifHandlers.get(type); const listener = _notifHandlers.get(type);
if (!listener) { if (!listener) {
return; return;
} }
@ -251,7 +251,7 @@ class PushNotificationIOS {
badge: boolean, badge: boolean,
sound: boolean sound: boolean
}> { }> {
var requestedPermissions = {}; let requestedPermissions = {};
if (permissions) { if (permissions) {
requestedPermissions = { requestedPermissions = {
alert: !!permissions.alert, alert: !!permissions.alert,
@ -321,7 +321,7 @@ class PushNotificationIOS {
// Extract data from Apple's `aps` dict as defined: // Extract data from Apple's `aps` dict as defined:
// https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html // https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html
Object.keys(nativeNotif).forEach((notifKey) => { Object.keys(nativeNotif).forEach((notifKey) => {
var notifVal = nativeNotif[notifKey]; const notifVal = nativeNotif[notifKey];
if (notifKey === 'aps') { if (notifKey === 'aps') {
this._alert = notifVal.alert; this._alert = notifVal.alert;
this._sound = notifVal.sound; this._sound = notifVal.sound;

Просмотреть файл

@ -8,16 +8,16 @@
*/ */
'use strict'; 'use strict';
var React = require('React'); const React = require('React');
const PropTypes = require('prop-types'); const PropTypes = require('prop-types');
var StyleSheet = require('StyleSheet'); const StyleSheet = require('StyleSheet');
var { TestModule } = require('NativeModules'); const { TestModule } = require('NativeModules');
var UIManager = require('UIManager'); const UIManager = require('UIManager');
var View = require('View'); const View = require('View');
const ViewPropTypes = require('ViewPropTypes'); const ViewPropTypes = require('ViewPropTypes');
var requireNativeComponent = require('requireNativeComponent'); const requireNativeComponent = require('requireNativeComponent');
class SnapshotViewIOS extends React.Component<{ class SnapshotViewIOS extends React.Component<{
onSnapshotReady?: Function, onSnapshotReady?: Function,
@ -37,8 +37,8 @@ class SnapshotViewIOS extends React.Component<{
}; };
render() { render() {
var testIdentifier = this.props.testIdentifier || 'test'; const testIdentifier = this.props.testIdentifier || 'test';
var onSnapshotReady = this.props.onSnapshotReady || this.onDefaultAction; const onSnapshotReady = this.props.onSnapshotReady || this.onDefaultAction;
return ( return (
<RCTSnapshot <RCTSnapshot
style={style.snapshot} style={style.snapshot}
@ -50,7 +50,7 @@ class SnapshotViewIOS extends React.Component<{
} }
} }
var style = StyleSheet.create({ const style = StyleSheet.create({
snapshot: { snapshot: {
flex: 1, flex: 1,
}, },
@ -59,7 +59,7 @@ var style = StyleSheet.create({
// Verify that RCTSnapshot is part of the UIManager since it is only loaded // Verify that RCTSnapshot is part of the UIManager since it is only loaded
// if you have linked against RCTTest like in tests, otherwise we will have // if you have linked against RCTTest like in tests, otherwise we will have
// a warning printed out // a warning printed out
var RCTSnapshot = UIManager.RCTSnapshot ? const RCTSnapshot = UIManager.RCTSnapshot ?
requireNativeComponent('RCTSnapshot', SnapshotViewIOS) : requireNativeComponent('RCTSnapshot', SnapshotViewIOS) :
View; View;

Просмотреть файл

@ -9,17 +9,17 @@
*/ */
'use strict'; 'use strict';
var UIManager = require('UIManager'); const UIManager = require('UIManager');
var installed = false; let installed = false;
var UIManagerStatTracker = { const UIManagerStatTracker = {
install: function() { install: function() {
if (installed) { if (installed) {
return; return;
} }
installed = true; installed = true;
var statLogHandle; let statLogHandle;
var stats = {}; const stats = {};
function printStats() { function printStats() {
console.log({UIManagerStatTracker: stats}); console.log({UIManagerStatTracker: stats});
statLogHandle = null; statLogHandle = null;
@ -30,19 +30,19 @@ var UIManagerStatTracker = {
statLogHandle = setImmediate(printStats); statLogHandle = setImmediate(printStats);
} }
} }
var createViewOrig = UIManager.createView; const createViewOrig = UIManager.createView;
UIManager.createView = function(tag, className, rootTag, props) { UIManager.createView = function(tag, className, rootTag, props) {
incStat('createView', 1); incStat('createView', 1);
incStat('setProp', Object.keys(props || []).length); incStat('setProp', Object.keys(props || []).length);
createViewOrig(tag, className, rootTag, props); createViewOrig(tag, className, rootTag, props);
}; };
var updateViewOrig = UIManager.updateView; const updateViewOrig = UIManager.updateView;
UIManager.updateView = function(tag, className, props) { UIManager.updateView = function(tag, className, props) {
incStat('updateView', 1); incStat('updateView', 1);
incStat('setProp', Object.keys(props || []).length); incStat('setProp', Object.keys(props || []).length);
updateViewOrig(tag, className, props); updateViewOrig(tag, className, props);
}; };
var manageChildrenOrig = UIManager.manageChildren; const manageChildrenOrig = UIManager.manageChildren;
UIManager.manageChildren = function( UIManager.manageChildren = function(
tag, tag,
moveFrom, moveFrom,

Просмотреть файл

@ -452,7 +452,7 @@ const rowHeight = 46;
const elevation = const elevation =
Platform.OS === 'android' ? Number.MAX_SAFE_INTEGER : undefined; Platform.OS === 'android' ? Number.MAX_SAFE_INTEGER : undefined;
var styles = StyleSheet.create({ const styles = StyleSheet.create({
fullScreen: { fullScreen: {
height: '100%', height: '100%',
width: '100%', width: '100%',

Просмотреть файл

@ -9,7 +9,7 @@
*/ */
'use strict'; 'use strict';
var UIManager = require('UIManager'); const UIManager = require('UIManager');
type OnSuccessCallback = ( type OnSuccessCallback = (
left: number, left: number,
@ -42,7 +42,7 @@ type OnErrorCallback = (error: any) => void;
* @param {function} onError `func(error)` * @param {function} onError `func(error)`
* @param {function} onSuccess `func(left, top, width, height, pageX, pageY)` * @param {function} onSuccess `func(left, top, width, height, pageX, pageY)`
*/ */
var queryLayoutByID = function( const queryLayoutByID = function(
tag: ?number, tag: ?number,
onError: OnErrorCallback, onError: OnErrorCallback,
onSuccess: OnSuccessCallback, onSuccess: OnSuccessCallback,

Просмотреть файл

@ -5,9 +5,9 @@
*/ */
'use strict'; 'use strict';
var warning = require('fbjs/lib/warning'); const warning = require('fbjs/lib/warning');
var Sample = { const Sample = {
test: function() { test: function() {
warning('Not yet implemented for Android.'); warning('Not yet implemented for Android.');
} }

Просмотреть файл

@ -3,13 +3,13 @@
*/ */
'use strict'; 'use strict';
var NativeSample = require('NativeModules').Sample; const NativeSample = require('NativeModules').Sample;
/** /**
* High-level docs for the Sample iOS API can be written here. * High-level docs for the Sample iOS API can be written here.
*/ */
var Sample = { const Sample = {
test: function() { test: function() {
NativeSample.test(); NativeSample.test();
} }

Просмотреть файл

@ -8,7 +8,7 @@
*/ */
'use strict'; 'use strict';
var Settings = { const Settings = {
get(key: string): mixed { get(key: string): mixed {
console.warn('Settings is not yet supported on Android'); console.warn('Settings is not yet supported on Android');
return null; return null;

Просмотреть файл

@ -8,14 +8,14 @@
*/ */
'use strict'; 'use strict';
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var RCTSettingsManager = require('NativeModules').SettingsManager; const RCTSettingsManager = require('NativeModules').SettingsManager;
var invariant = require('fbjs/lib/invariant'); const invariant = require('fbjs/lib/invariant');
var subscriptions: Array<{keys: Array<string>, callback: ?Function}> = []; const subscriptions: Array<{keys: Array<string>, callback: ?Function}> = [];
var Settings = { const Settings = {
_settings: RCTSettingsManager && RCTSettingsManager.settings, _settings: RCTSettingsManager && RCTSettingsManager.settings,
get(key: string): mixed { get(key: string): mixed {
@ -37,7 +37,7 @@ var Settings = {
'keys should be a string or array of strings' 'keys should be a string or array of strings'
); );
var sid = subscriptions.length; const sid = subscriptions.length;
subscriptions.push({keys: keys, callback: callback}); subscriptions.push({keys: keys, callback: callback});
return sid; return sid;
}, },
@ -50,8 +50,8 @@ var Settings = {
_sendObservations(body: Object) { _sendObservations(body: Object) {
Object.keys(body).forEach((key) => { Object.keys(body).forEach((key) => {
var newValue = body[key]; const newValue = body[key];
var didChange = this._settings[key] !== newValue; const didChange = this._settings[key] !== newValue;
this._settings[key] = newValue; this._settings[key] = newValue;
if (didChange) { if (didChange) {

Просмотреть файл

@ -24,7 +24,7 @@ const RCTAsyncStorage = NativeModules.AsyncRocksDBStorage ||
* *
* See http://facebook.github.io/react-native/docs/asyncstorage.html * See http://facebook.github.io/react-native/docs/asyncstorage.html
*/ */
var AsyncStorage = { const AsyncStorage = {
_getRequests: ([]: Array<any>), _getRequests: ([]: Array<any>),
_getKeys: ([]: Array<string>), _getKeys: ([]: Array<string>),
_immediate: (null: ?number), _immediate: (null: ?number),
@ -41,8 +41,8 @@ var AsyncStorage = {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
RCTAsyncStorage.multiGet([key], function(errors, result) { RCTAsyncStorage.multiGet([key], function(errors, result) {
// Unpack result to get value from [[key,value]] // Unpack result to get value from [[key,value]]
var value = (result && result[0] && result[0][1]) ? result[0][1] : null; const value = (result && result[0] && result[0][1]) ? result[0][1] : null;
var errs = convertErrors(errors); const errs = convertErrors(errors);
callback && callback(errs && errs[0], value); callback && callback(errs && errs[0], value);
if (errs) { if (errs) {
reject(errs[0]); reject(errs[0]);
@ -65,7 +65,7 @@ var AsyncStorage = {
): Promise { ): Promise {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
RCTAsyncStorage.multiSet([[key,value]], function(errors) { RCTAsyncStorage.multiSet([[key,value]], function(errors) {
var errs = convertErrors(errors); const errs = convertErrors(errors);
callback && callback(errs && errs[0]); callback && callback(errs && errs[0]);
if (errs) { if (errs) {
reject(errs[0]); reject(errs[0]);
@ -87,7 +87,7 @@ var AsyncStorage = {
): Promise { ): Promise {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
RCTAsyncStorage.multiRemove([key], function(errors) { RCTAsyncStorage.multiRemove([key], function(errors) {
var errs = convertErrors(errors); const errs = convertErrors(errors);
callback && callback(errs && errs[0]); callback && callback(errs && errs[0]);
if (errs) { if (errs) {
reject(errs[0]); reject(errs[0]);
@ -113,7 +113,7 @@ var AsyncStorage = {
): Promise { ): Promise {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
RCTAsyncStorage.multiMerge([[key,value]], function(errors) { RCTAsyncStorage.multiMerge([[key,value]], function(errors) {
var errs = convertErrors(errors); const errs = convertErrors(errors);
callback && callback(errs && errs[0]); callback && callback(errs && errs[0]);
if (errs) { if (errs) {
reject(errs[0]); reject(errs[0]);
@ -222,7 +222,7 @@ var AsyncStorage = {
}); });
} }
var getRequest = { const getRequest = {
keys: keys, keys: keys,
callback: callback, callback: callback,
// do we need this? // do we need this?
@ -231,7 +231,7 @@ var AsyncStorage = {
reject: null, reject: null,
}; };
var promiseResult = new Promise((resolve, reject) => { const promiseResult = new Promise((resolve, reject) => {
getRequest.resolve = resolve; getRequest.resolve = resolve;
getRequest.reject = reject; getRequest.reject = reject;
}); });
@ -259,7 +259,7 @@ var AsyncStorage = {
): Promise { ): Promise {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
RCTAsyncStorage.multiSet(keyValuePairs, function(errors) { RCTAsyncStorage.multiSet(keyValuePairs, function(errors) {
var error = convertErrors(errors); const error = convertErrors(errors);
callback && callback(error); callback && callback(error);
if (error) { if (error) {
reject(error); reject(error);
@ -281,7 +281,7 @@ var AsyncStorage = {
): Promise { ): Promise {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
RCTAsyncStorage.multiRemove(keys, function(errors) { RCTAsyncStorage.multiRemove(keys, function(errors) {
var error = convertErrors(errors); const error = convertErrors(errors);
callback && callback(error); callback && callback(error);
if (error) { if (error) {
reject(error); reject(error);
@ -306,7 +306,7 @@ var AsyncStorage = {
): Promise { ): Promise {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
RCTAsyncStorage.multiMerge(keyValuePairs, function(errors) { RCTAsyncStorage.multiMerge(keyValuePairs, function(errors) {
var error = convertErrors(errors); const error = convertErrors(errors);
callback && callback(error); callback && callback(error);
if (error) { if (error) {
reject(error); reject(error);
@ -335,7 +335,7 @@ function convertError(error) {
if (!error) { if (!error) {
return null; return null;
} }
var out = new Error(error.message); const out = new Error(error.message);
out.key = error.key; // flow doesn't like this :( out.key = error.key; // flow doesn't like this :(
return out; return out;
} }

Просмотреть файл

@ -7,10 +7,10 @@
*/ */
'use strict'; 'use strict';
var normalizeColor = require('normalizeColor'); const normalizeColor = require('normalizeColor');
var colorPropType = function(isRequired, props, propName, componentName, location, propFullName) { const colorPropType = function(isRequired, props, propName, componentName, location, propFullName) {
var color = props[propName]; const color = props[propName];
if (color === undefined || color === null) { if (color === undefined || color === null) {
if (isRequired) { if (isRequired) {
return new Error( return new Error(
@ -48,7 +48,7 @@ var colorPropType = function(isRequired, props, propName, componentName, locatio
} }
}; };
var ColorPropType = colorPropType.bind(null, false /* isRequired */); const ColorPropType = colorPropType.bind(null, false /* isRequired */);
ColorPropType.isRequired = colorPropType.bind(null, true /* isRequired */); ColorPropType.isRequired = colorPropType.bind(null, true /* isRequired */);
module.exports = ColorPropType; module.exports = ColorPropType;

Просмотреть файл

@ -8,7 +8,7 @@
*/ */
'use strict'; 'use strict';
var ReactPropTypes = require('prop-types'); const ReactPropTypes = require('prop-types');
/** /**
* React Native's layout system is based on Flexbox and is powered both * React Native's layout system is based on Flexbox and is powered both
@ -23,7 +23,7 @@ var ReactPropTypes = require('prop-types');
* These properties are a subset of our styles that are consumed by the layout * These properties are a subset of our styles that are consumed by the layout
* algorithm and affect the positioning and sizing of views. * algorithm and affect the positioning and sizing of views.
*/ */
var LayoutPropTypes = { const LayoutPropTypes = {
/** `display` sets the display type of this component. /** `display` sets the display type of this component.
* *
* It works similarly to `display` in CSS, but only support 'flex' and 'none'. * It works similarly to `display` in CSS, but only support 'flex' and 'none'.

Просмотреть файл

@ -8,11 +8,11 @@
*/ */
'use strict'; 'use strict';
var PropTypes = require('prop-types'); const PropTypes = require('prop-types');
var createStrictShapeTypeChecker = require('createStrictShapeTypeChecker'); const createStrictShapeTypeChecker = require('createStrictShapeTypeChecker');
var PointPropType = createStrictShapeTypeChecker({ const PointPropType = createStrictShapeTypeChecker({
x: PropTypes.number, x: PropTypes.number,
y: PropTypes.number, y: PropTypes.number,
}); });

Просмотреть файл

@ -8,15 +8,15 @@
*/ */
'use strict'; 'use strict';
var createStrictShapeTypeChecker = require('createStrictShapeTypeChecker'); const createStrictShapeTypeChecker = require('createStrictShapeTypeChecker');
var flattenStyle = require('flattenStyle'); const flattenStyle = require('flattenStyle');
function StyleSheetPropType( function StyleSheetPropType(
shape: {[key: string]: ReactPropsCheckType} shape: {[key: string]: ReactPropsCheckType}
): ReactPropsCheckType { ): ReactPropsCheckType {
var shapePropType = createStrictShapeTypeChecker(shape); const shapePropType = createStrictShapeTypeChecker(shape);
return function(props, propName, componentName, location?, ...rest) { return function(props, propName, componentName, location?, ...rest) {
var newProps = props; let newProps = props;
if (props[propName]) { if (props[propName]) {
// Just make a dummy prop object with only the flattened style // Just make a dummy prop object with only the flattened style
newProps = {}; newProps = {};

Просмотреть файл

@ -8,11 +8,11 @@
*/ */
'use strict'; 'use strict';
var ImageStylePropTypes = require('ImageStylePropTypes'); const ImageStylePropTypes = require('ImageStylePropTypes');
var TextStylePropTypes = require('TextStylePropTypes'); const TextStylePropTypes = require('TextStylePropTypes');
var ViewStylePropTypes = require('ViewStylePropTypes'); const ViewStylePropTypes = require('ViewStylePropTypes');
var invariant = require('fbjs/lib/invariant'); const invariant = require('fbjs/lib/invariant');
// Hardcoded because this is a legit case but we don't want to load it from // Hardcoded because this is a legit case but we don't want to load it from
// a private API. We might likely want to unify style sheet creation with how it // a private API. We might likely want to unify style sheet creation with how it
@ -26,12 +26,12 @@ class StyleSheetValidation {
return; return;
} }
if (allStylePropTypes[prop] === undefined) { if (allStylePropTypes[prop] === undefined) {
var message1 = '"' + prop + '" is not a valid style property.'; const message1 = '"' + prop + '" is not a valid style property.';
var message2 = '\nValid style props: ' + const message2 = '\nValid style props: ' +
JSON.stringify(Object.keys(allStylePropTypes).sort(), null, ' '); JSON.stringify(Object.keys(allStylePropTypes).sort(), null, ' ');
styleError(message1, style, caller, message2); styleError(message1, style, caller, message2);
} }
var error = allStylePropTypes[prop]( const error = allStylePropTypes[prop](
style, style,
prop, prop,
caller, caller,
@ -48,19 +48,19 @@ class StyleSheetValidation {
if (!__DEV__) { if (!__DEV__) {
return; return;
} }
for (var prop in styles[name]) { for (const prop in styles[name]) {
StyleSheetValidation.validateStyleProp(prop, styles[name], 'StyleSheet ' + name); StyleSheetValidation.validateStyleProp(prop, styles[name], 'StyleSheet ' + name);
} }
} }
static addValidStylePropTypes(stylePropTypes) { static addValidStylePropTypes(stylePropTypes) {
for (var key in stylePropTypes) { for (const key in stylePropTypes) {
allStylePropTypes[key] = stylePropTypes[key]; allStylePropTypes[key] = stylePropTypes[key];
} }
} }
} }
var styleError = function(message1, style, caller?, message2?) { const styleError = function(message1, style, caller?, message2?) {
invariant( invariant(
false, false,
message1 + '\n' + (caller || '<<unknown>>') + ': ' + message1 + '\n' + (caller || '<<unknown>>') + ': ' +
@ -68,7 +68,7 @@ var styleError = function(message1, style, caller?, message2?) {
); );
}; };
var allStylePropTypes = {}; const allStylePropTypes = {};
StyleSheetValidation.addValidStylePropTypes(ImageStylePropTypes); StyleSheetValidation.addValidStylePropTypes(ImageStylePropTypes);
StyleSheetValidation.addValidStylePropTypes(TextStylePropTypes); StyleSheetValidation.addValidStylePropTypes(TextStylePropTypes);

Просмотреть файл

@ -8,11 +8,11 @@
*/ */
'use strict'; 'use strict';
var ReactPropTypes = require('prop-types'); const ReactPropTypes = require('prop-types');
var deprecatedPropType = require('deprecatedPropType'); const deprecatedPropType = require('deprecatedPropType');
var TransformMatrixPropType = function( const TransformMatrixPropType = function(
props : Object, props : Object,
propName : string, propName : string,
componentName : string componentName : string
@ -25,7 +25,7 @@ var TransformMatrixPropType = function(
} }
}; };
var DecomposedMatrixPropType = function( const DecomposedMatrixPropType = function(
props : Object, props : Object,
propName : string, propName : string,
componentName : string componentName : string
@ -38,7 +38,7 @@ var DecomposedMatrixPropType = function(
} }
}; };
var TransformPropTypes = { const TransformPropTypes = {
/** /**
* `transform` accepts an array of transformation objects. Each object specifies * `transform` accepts an array of transformation objects. Each object specifies
* the property that will be transformed as the key, and the value to use in the * the property that will be transformed as the key, and the value to use in the

Просмотреть файл

@ -83,8 +83,8 @@ describe('flattenStyle', () => {
it('should not allocate an object when there is a single class', () => { it('should not allocate an object when there is a single class', () => {
const fixture = getFixture(); const fixture = getFixture();
var singleStyle = flattenStyle(fixture.elementA); const singleStyle = flattenStyle(fixture.elementA);
var singleStyleAgain = flattenStyle(fixture.elementA); const singleStyleAgain = flattenStyle(fixture.elementA);
expect(singleStyle).toBe(singleStyleAgain); expect(singleStyle).toBe(singleStyleAgain);
expect(singleStyle).toEqual({ expect(singleStyle).toEqual({
@ -95,8 +95,8 @@ describe('flattenStyle', () => {
it('should merge single class and style properly', () => { it('should merge single class and style properly', () => {
const fixture = getFixture(); const fixture = getFixture();
var style = {styleA: 'overrideA', styleC: 'overrideC'}; const style = {styleA: 'overrideA', styleC: 'overrideC'};
var arrayStyle = flattenStyle([fixture.elementA, style]); const arrayStyle = flattenStyle([fixture.elementA, style]);
expect(arrayStyle).toEqual({ expect(arrayStyle).toEqual({
styleA: 'overrideA', styleA: 'overrideA',
@ -107,8 +107,8 @@ describe('flattenStyle', () => {
it('should merge multiple classes', () => { it('should merge multiple classes', () => {
const fixture = getFixture(); const fixture = getFixture();
var AthenB = flattenStyle([fixture.elementA, fixture.elementB]); const AthenB = flattenStyle([fixture.elementA, fixture.elementB]);
var BthenA = flattenStyle([fixture.elementB, fixture.elementA]); const BthenA = flattenStyle([fixture.elementB, fixture.elementA]);
expect(AthenB).toEqual({ expect(AthenB).toEqual({
styleA: 'moduleA/elementA/styleA', styleA: 'moduleA/elementA/styleA',
@ -122,9 +122,9 @@ describe('flattenStyle', () => {
it('should merge multiple classes with style', () => { it('should merge multiple classes with style', () => {
const fixture = getFixture(); const fixture = getFixture();
var style = {styleA: 'overrideA'}; const style = {styleA: 'overrideA'};
var AthenB = flattenStyle([fixture.elementA, fixture.elementB, style]); const AthenB = flattenStyle([fixture.elementA, fixture.elementB, style]);
var BthenA = flattenStyle([fixture.elementB, fixture.elementA, style]); const BthenA = flattenStyle([fixture.elementB, fixture.elementA, style]);
expect(AthenB).toEqual({ expect(AthenB).toEqual({
styleA: 'overrideA', styleA: 'overrideA',
@ -138,8 +138,8 @@ describe('flattenStyle', () => {
it('should flatten recursively', () => { it('should flatten recursively', () => {
const fixture = getFixture(); const fixture = getFixture();
var style = [{styleA: 'newA', styleB: 'newB'}, {styleA: 'newA2'}]; const style = [{styleA: 'newA', styleB: 'newB'}, {styleA: 'newA2'}];
var AthenB = flattenStyle([fixture.elementA, fixture.elementB, style]); const AthenB = flattenStyle([fixture.elementA, fixture.elementB, style]);
expect(AthenB).toEqual({ expect(AthenB).toEqual({
styleA: 'newA2', styleA: 'newA2',
@ -148,7 +148,7 @@ describe('flattenStyle', () => {
}); });
it('should ignore invalid class names', () => { it('should ignore invalid class names', () => {
var invalid = flattenStyle(1234, null); const invalid = flattenStyle(1234, null);
expect(invalid).toEqual(undefined); expect(invalid).toEqual(undefined);
// Invalid class name 1234 skipping ... // Invalid class name 1234 skipping ...

Просмотреть файл

@ -8,7 +8,7 @@
*/ */
'use strict'; 'use strict';
var normalizeColor = require('normalizeColor'); const normalizeColor = require('normalizeColor');
describe('normalizeColor', function() { describe('normalizeColor', function() {
it('should accept only spec compliant colors', function() { it('should accept only spec compliant colors', function() {

Просмотреть файл

@ -20,26 +20,26 @@ describe('processColor', () => {
describe('predefined color names', () => { describe('predefined color names', () => {
it('should convert red', () => { it('should convert red', () => {
var colorFromString = processColor('red'); const colorFromString = processColor('red');
var expectedInt = 0xFFFF0000; const expectedInt = 0xFFFF0000;
expect(colorFromString).toEqual(platformSpecific(expectedInt)); expect(colorFromString).toEqual(platformSpecific(expectedInt));
}); });
it('should convert white', () => { it('should convert white', () => {
var colorFromString = processColor('white'); const colorFromString = processColor('white');
var expectedInt = 0xFFFFFFFF; const expectedInt = 0xFFFFFFFF;
expect(colorFromString).toEqual(platformSpecific(expectedInt)); expect(colorFromString).toEqual(platformSpecific(expectedInt));
}); });
it('should convert black', () => { it('should convert black', () => {
var colorFromString = processColor('black'); const colorFromString = processColor('black');
var expectedInt = 0xFF000000; const expectedInt = 0xFF000000;
expect(colorFromString).toEqual(platformSpecific(expectedInt)); expect(colorFromString).toEqual(platformSpecific(expectedInt));
}); });
it('should convert transparent', () => { it('should convert transparent', () => {
var colorFromString = processColor('transparent'); const colorFromString = processColor('transparent');
var expectedInt = 0x00000000; const expectedInt = 0x00000000;
expect(colorFromString).toEqual(platformSpecific(expectedInt)); expect(colorFromString).toEqual(platformSpecific(expectedInt));
}); });
}); });
@ -47,8 +47,8 @@ describe('processColor', () => {
describe('RGB strings', () => { describe('RGB strings', () => {
it('should convert rgb(x, y, z)', () => { it('should convert rgb(x, y, z)', () => {
var colorFromString = processColor('rgb(10, 20, 30)'); const colorFromString = processColor('rgb(10, 20, 30)');
var expectedInt = 0xFF0A141E; const expectedInt = 0xFF0A141E;
expect(colorFromString).toEqual(platformSpecific(expectedInt)); expect(colorFromString).toEqual(platformSpecific(expectedInt));
}); });
@ -57,8 +57,8 @@ describe('processColor', () => {
describe('RGBA strings', () => { describe('RGBA strings', () => {
it('should convert rgba(x, y, z, a)', () => { it('should convert rgba(x, y, z, a)', () => {
var colorFromString = processColor('rgba(10, 20, 30, 0.4)'); const colorFromString = processColor('rgba(10, 20, 30, 0.4)');
var expectedInt = 0x660A141E; const expectedInt = 0x660A141E;
expect(colorFromString).toEqual(platformSpecific(expectedInt)); expect(colorFromString).toEqual(platformSpecific(expectedInt));
}); });
@ -67,8 +67,8 @@ describe('processColor', () => {
describe('HSL strings', () => { describe('HSL strings', () => {
it('should convert hsl(x, y%, z%)', () => { it('should convert hsl(x, y%, z%)', () => {
var colorFromString = processColor('hsl(318, 69%, 55%)'); const colorFromString = processColor('hsl(318, 69%, 55%)');
var expectedInt = 0xFFDB3DAC; const expectedInt = 0xFFDB3DAC;
expect(colorFromString).toEqual(platformSpecific(expectedInt)); expect(colorFromString).toEqual(platformSpecific(expectedInt));
}); });
@ -77,8 +77,8 @@ describe('processColor', () => {
describe('HSLA strings', () => { describe('HSLA strings', () => {
it('should convert hsla(x, y%, z%, a)', () => { it('should convert hsla(x, y%, z%, a)', () => {
var colorFromString = processColor('hsla(318, 69%, 55%, 0.25)'); const colorFromString = processColor('hsla(318, 69%, 55%, 0.25)');
var expectedInt = 0x40DB3DAC; const expectedInt = 0x40DB3DAC;
expect(colorFromString).toEqual(platformSpecific(expectedInt)); expect(colorFromString).toEqual(platformSpecific(expectedInt));
}); });
@ -87,8 +87,8 @@ describe('processColor', () => {
describe('hex strings', () => { describe('hex strings', () => {
it('should convert #xxxxxx', () => { it('should convert #xxxxxx', () => {
var colorFromString = processColor('#1e83c9'); const colorFromString = processColor('#1e83c9');
var expectedInt = 0xFF1E83C9; const expectedInt = 0xFF1E83C9;
expect(colorFromString).toEqual(platformSpecific(expectedInt)); expect(colorFromString).toEqual(platformSpecific(expectedInt));
}); });

Просмотреть файл

@ -8,8 +8,8 @@
*/ */
'use strict'; 'use strict';
var setNormalizedColorAlpha = require('setNormalizedColorAlpha'); const setNormalizedColorAlpha = require('setNormalizedColorAlpha');
var normalizeColor = require('normalizeColor'); const normalizeColor = require('normalizeColor');
describe('setNormalizedColorAlpha', function() { describe('setNormalizedColorAlpha', function() {
it('should adjust the alpha of the color passed in', function() { it('should adjust the alpha of the color passed in', function() {
@ -27,7 +27,7 @@ describe('setNormalizedColorAlpha', function() {
}); });
it('should return the original color when alpha is unchanged', function() { it('should return the original color when alpha is unchanged', function() {
var originalColor = normalizeColor('blue'); const originalColor = normalizeColor('blue');
expect(setNormalizedColorAlpha(originalColor, 1)).toBe(originalColor); expect(setNormalizedColorAlpha(originalColor, 1)).toBe(originalColor);
}); });
}); });

Просмотреть файл

@ -25,11 +25,11 @@ function flattenStyle(
return style; return style;
} }
var result = {}; const result = {};
for (var i = 0, styleLength = style.length; i < styleLength; ++i) { for (let i = 0, styleLength = style.length; i < styleLength; ++i) {
var computedStyle = flattenStyle(style[i]); const computedStyle = flattenStyle(style[i]);
if (computedStyle) { if (computedStyle) {
for (var key in computedStyle) { for (const key in computedStyle) {
result[key] = computedStyle[key]; result[key] = computedStyle[key];
} }
} }

Просмотреть файл

@ -8,11 +8,11 @@
*/ */
'use strict'; 'use strict';
var MatrixMath = require('MatrixMath'); const MatrixMath = require('MatrixMath');
var Platform = require('Platform'); const Platform = require('Platform');
var invariant = require('fbjs/lib/invariant'); const invariant = require('fbjs/lib/invariant');
var stringifySafe = require('stringifySafe'); const stringifySafe = require('stringifySafe');
/** /**
* Generate a transform matrix based on the provided transforms, and use that * Generate a transform matrix based on the provided transforms, and use that
@ -34,11 +34,11 @@ function processTransform(transform: Array<Object>): Array<Object> | Array<numbe
return transform; return transform;
} }
var result = MatrixMath.createIdentityMatrix(); const result = MatrixMath.createIdentityMatrix();
transform.forEach(transformation => { transform.forEach(transformation => {
var key = Object.keys(transformation)[0]; const key = Object.keys(transformation)[0];
var value = transformation[key]; const value = transformation[key];
switch (key) { switch (key) {
case 'matrix': case 'matrix':
@ -97,8 +97,8 @@ function _multiplyTransform(
matrixMathFunction: Function, matrixMathFunction: Function,
args: Array<number> args: Array<number>
): void { ): void {
var matrixToApply = MatrixMath.createIdentityMatrix(); const matrixToApply = MatrixMath.createIdentityMatrix();
var argsWithIdentity = [matrixToApply].concat(args); const argsWithIdentity = [matrixToApply].concat(args);
matrixMathFunction.apply(this, argsWithIdentity); matrixMathFunction.apply(this, argsWithIdentity);
MatrixMath.multiplyInto(result, result, matrixToApply); MatrixMath.multiplyInto(result, result, matrixToApply);
} }
@ -108,20 +108,20 @@ function _multiplyTransform(
* Note that validation on the string is done in `_validateTransform()`. * Note that validation on the string is done in `_validateTransform()`.
*/ */
function _convertToRadians(value: string): number { function _convertToRadians(value: string): number {
var floatValue = parseFloat(value); const floatValue = parseFloat(value);
return value.indexOf('rad') > -1 ? floatValue : floatValue * Math.PI / 180; return value.indexOf('rad') > -1 ? floatValue : floatValue * Math.PI / 180;
} }
function _validateTransforms(transform: Array<Object>): void { function _validateTransforms(transform: Array<Object>): void {
transform.forEach(transformation => { transform.forEach(transformation => {
var keys = Object.keys(transformation); const keys = Object.keys(transformation);
invariant( invariant(
keys.length === 1, keys.length === 1,
'You must specify exactly one property per transform object. Passed properties: %s', 'You must specify exactly one property per transform object. Passed properties: %s',
stringifySafe(transformation), stringifySafe(transformation),
); );
var key = keys[0]; const key = keys[0];
var value = transformation[key]; const value = transformation[key];
_validateTransform(key, value, transformation); _validateTransform(key, value, transformation);
}); });
} }
@ -134,7 +134,7 @@ function _validateTransform(key, value, transformation) {
'replace <View /> by <Animated.View />.' 'replace <View /> by <Animated.View />.'
); );
var multivalueTransforms = [ const multivalueTransforms = [
'matrix', 'matrix',
'translate', 'translate',
]; ];

Просмотреть файл

@ -8,22 +8,22 @@
*/ */
'use strict'; 'use strict';
var React = require('react'); const React = require('react');
var createReactClass = require('create-react-class'); const createReactClass = require('create-react-class');
var ReactNative = require('react-native'); const ReactNative = require('react-native');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and * found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */ * run Flow. */
var TimerMixin = require('react-timer-mixin'); const TimerMixin = require('react-timer-mixin');
var { const {
NativeModules, NativeModules,
StyleSheet, StyleSheet,
Text, Text,
} = ReactNative; } = ReactNative;
var TestManager = NativeModules.TestManager || NativeModules.SnapshotTestManager; const TestManager = NativeModules.TestManager || NativeModules.SnapshotTestManager;
var TextUpdateTest = createReactClass({ const TextUpdateTest = createReactClass({
displayName: 'TextUpdateTest', displayName: 'TextUpdateTest',
mixins: [TimerMixin], mixins: [TimerMixin],
getInitialState: function() { getInitialState: function() {
@ -48,7 +48,7 @@ var TextUpdateTest = createReactClass({
}, },
}); });
var styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
margin: 10, margin: 10,
marginTop: 100, marginTop: 100,

Просмотреть файл

@ -11,14 +11,14 @@
'use strict'; 'use strict';
var BackHandler = require('BackHandler'); const BackHandler = require('BackHandler');
var warning = require('fbjs/lib/warning'); const warning = require('fbjs/lib/warning');
/** /**
* Deprecated. Use BackHandler instead. * Deprecated. Use BackHandler instead.
*/ */
var BackAndroid = { const BackAndroid = {
exitApp: function() { exitApp: function() {
warning(false, 'BackAndroid is deprecated. Please use BackHandler instead.'); warning(false, 'BackAndroid is deprecated. Please use BackHandler instead.');

Просмотреть файл

@ -8,22 +8,22 @@
'use strict'; 'use strict';
var DeviceEventManager = require('NativeModules').DeviceEventManager; const DeviceEventManager = require('NativeModules').DeviceEventManager;
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var DEVICE_BACK_EVENT = 'hardwareBackPress'; const DEVICE_BACK_EVENT = 'hardwareBackPress';
type BackPressEventName = $Enum<{ type BackPressEventName = $Enum<{
backPress: string, backPress: string,
}>; }>;
var _backPressSubscriptions = new Set(); const _backPressSubscriptions = new Set();
RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() { RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
var invokeDefault = true; let invokeDefault = true;
var subscriptions = Array.from(_backPressSubscriptions.values()).reverse(); const subscriptions = Array.from(_backPressSubscriptions.values()).reverse();
for (var i = 0; i < subscriptions.length; ++i) { for (let i = 0; i < subscriptions.length; ++i) {
if (subscriptions[i]()) { if (subscriptions[i]()) {
invokeDefault = false; invokeDefault = false;
break; break;
@ -65,7 +65,7 @@ RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
* }); * });
* ``` * ```
*/ */
var BackHandler = { const BackHandler = {
exitApp: function() { exitApp: function() {
DeviceEventManager.invokeDefaultBackPressHandler(); DeviceEventManager.invokeDefaultBackPressHandler();

Просмотреть файл

@ -54,14 +54,14 @@ let BackHandler;
if (Platform.isTVOS) { if (Platform.isTVOS) {
const _tvEventHandler = new TVEventHandler(); const _tvEventHandler = new TVEventHandler();
var _backPressSubscriptions = new Set(); const _backPressSubscriptions = new Set();
_tvEventHandler.enable(this, function(cmp, evt) { _tvEventHandler.enable(this, function(cmp, evt) {
if (evt && evt.eventType === 'menu') { if (evt && evt.eventType === 'menu') {
var invokeDefault = true; let invokeDefault = true;
var subscriptions = Array.from(_backPressSubscriptions.values()).reverse(); const subscriptions = Array.from(_backPressSubscriptions.values()).reverse();
for (var i = 0; i < subscriptions.length; ++i) { for (let i = 0; i < subscriptions.length; ++i) {
if (subscriptions[i]()) { if (subscriptions[i]()) {
invokeDefault = false; invokeDefault = false;
break; break;

Просмотреть файл

@ -8,15 +8,15 @@
*/ */
'use strict'; 'use strict';
var EventEmitter = require('EventEmitter'); const EventEmitter = require('EventEmitter');
var Platform = require('Platform'); const Platform = require('Platform');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var invariant = require('fbjs/lib/invariant'); const invariant = require('fbjs/lib/invariant');
var eventEmitter = new EventEmitter(); const eventEmitter = new EventEmitter();
var dimensionsInitialized = false; let dimensionsInitialized = false;
var dimensions = {}; const dimensions = {};
class Dimensions { class Dimensions {
/** /**
* This should only be called from native code by sending the * This should only be called from native code by sending the

Просмотреть файл

@ -9,7 +9,7 @@
'use strict'; 'use strict';
var ToastAndroid = require('ToastAndroid'); const ToastAndroid = require('ToastAndroid');
const TOAST_SHORT_DELAY = 2000; const TOAST_SHORT_DELAY = 2000;

Просмотреть файл

@ -8,9 +8,9 @@
*/ */
'use strict'; 'use strict';
var HeapCapture = { const HeapCapture = {
captureHeap: function (path: string) { captureHeap: function (path: string) {
var error = null; let error = null;
try { try {
global.nativeCaptureHeap(path); global.nativeCaptureHeap(path);
console.log('HeapCapture.captureHeap succeeded: ' + path); console.log('HeapCapture.captureHeap succeeded: ' + path);

Просмотреть файл

@ -9,13 +9,13 @@
/* eslint-disable space-infix-ops */ /* eslint-disable space-infix-ops */
'use strict'; 'use strict';
var invariant = require('fbjs/lib/invariant'); const invariant = require('fbjs/lib/invariant');
/** /**
* Memory conservative (mutative) matrix math utilities. Uses "command" * Memory conservative (mutative) matrix math utilities. Uses "command"
* matrices, which are reusable. * matrices, which are reusable.
*/ */
var MatrixMath = { const MatrixMath = {
createIdentityMatrix: function() { createIdentityMatrix: function() {
return [ return [
1,0,0,0, 1,0,0,0,
@ -35,13 +35,13 @@ var MatrixMath = {
}, },
createOrthographic: function(left, right, bottom, top, near, far) { createOrthographic: function(left, right, bottom, top, near, far) {
var a = 2 / (right - left); const a = 2 / (right - left);
var b = 2 / (top - bottom); const b = 2 / (top - bottom);
var c = -2 / (far - near); const c = -2 / (far - near);
var tx = -(right + left) / (right - left); const tx = -(right + left) / (right - left);
var ty = -(top + bottom) / (top - bottom); const ty = -(top + bottom) / (top - bottom);
var tz = -(far + near) / (far - near); const tz = -(far + near) / (far - near);
return [ return [
a, 0, 0, 0, a, 0, 0, 0,
@ -52,15 +52,15 @@ var MatrixMath = {
}, },
createFrustum: function(left, right, bottom, top, near, far) { createFrustum: function(left, right, bottom, top, near, far) {
var r_width = 1 / (right - left); const r_width = 1 / (right - left);
var r_height = 1 / (top - bottom); const r_height = 1 / (top - bottom);
var r_depth = 1 / (near - far); const r_depth = 1 / (near - far);
var x = 2 * (near * r_width); const x = 2 * (near * r_width);
var y = 2 * (near * r_height); const y = 2 * (near * r_height);
var A = (right + left) * r_width; const A = (right + left) * r_width;
var B = (top + bottom) * r_height; const B = (top + bottom) * r_height;
var C = (far + near) * r_depth; const C = (far + near) * r_depth;
var D = 2 * (far * near * r_depth); const D = 2 * (far * near * r_depth);
return [ return [
x, 0, 0, 0, x, 0, 0, 0,
0, y, 0, 0, 0, y, 0, 0,
@ -76,10 +76,10 @@ var MatrixMath = {
* @param fovInRadians - field of view in randians * @param fovInRadians - field of view in randians
*/ */
createPerspective: function(fovInRadians, aspect, near, far) { createPerspective: function(fovInRadians, aspect, near, far) {
var h = 1 / Math.tan(fovInRadians / 2); const h = 1 / Math.tan(fovInRadians / 2);
var r_depth = 1 / (near - far); const r_depth = 1 / (near - far);
var C = (far + near) * r_depth; const C = (far + near) * r_depth;
var D = 2 * (far * near * r_depth); const D = 2 * (far * near * r_depth);
return [ return [
h/aspect, 0, 0, 0, h/aspect, 0, 0, 0,
0, h, 0, 0, 0, h, 0, 0,
@ -89,7 +89,7 @@ var MatrixMath = {
}, },
createTranslate2d: function(x, y) { createTranslate2d: function(x, y) {
var mat = MatrixMath.createIdentityMatrix(); const mat = MatrixMath.createIdentityMatrix();
MatrixMath.reuseTranslate2dCommand(mat, x, y); MatrixMath.reuseTranslate2dCommand(mat, x, y);
return mat; return mat;
}, },
@ -106,7 +106,7 @@ var MatrixMath = {
}, },
createScale: function(factor) { createScale: function(factor) {
var mat = MatrixMath.createIdentityMatrix(); const mat = MatrixMath.createIdentityMatrix();
MatrixMath.reuseScaleCommand(mat, factor); MatrixMath.reuseScaleCommand(mat, factor);
return mat; return mat;
}, },
@ -161,7 +161,7 @@ var MatrixMath = {
}, },
createRotateZ: function(radians) { createRotateZ: function(radians) {
var mat = MatrixMath.createIdentityMatrix(); const mat = MatrixMath.createIdentityMatrix();
MatrixMath.reuseRotateZCommand(mat, radians); MatrixMath.reuseRotateZCommand(mat, radians);
return mat; return mat;
}, },
@ -175,12 +175,9 @@ var MatrixMath = {
}, },
multiplyInto: function(out, a, b) { multiplyInto: function(out, a, b) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; let b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
@ -206,7 +203,7 @@ var MatrixMath = {
}, },
determinant(matrix: Array<number>): number { determinant(matrix: Array<number>): number {
var [ const [
m00, m01, m02, m03, m00, m01, m02, m03,
m10, m11, m12, m13, m10, m11, m12, m13,
m20, m21, m22, m23, m20, m21, m22, m23,
@ -236,11 +233,11 @@ var MatrixMath = {
* http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm * http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
*/ */
inverse(matrix: Array<number>): Array<number> { inverse(matrix: Array<number>): Array<number> {
var det = MatrixMath.determinant(matrix); const det = MatrixMath.determinant(matrix);
if (!det) { if (!det) {
return matrix; return matrix;
} }
var [ const [
m00, m01, m02, m03, m00, m01, m02, m03,
m10, m11, m12, m13, m10, m11, m12, m13,
m20, m21, m22, m23, m20, m21, m22, m23,
@ -285,7 +282,7 @@ var MatrixMath = {
v: Array<number>, v: Array<number>,
m: Array<number> m: Array<number>
): Array<number> { ): Array<number> {
var [vx, vy, vz, vw] = v; const [vx, vy, vz, vw] = v;
return [ return [
vx * m[0] + vy * m[4] + vz * m[8] + vw * m[12], vx * m[0] + vy * m[4] + vz * m[8] + vw * m[12],
vx * m[1] + vy * m[5] + vz * m[9] + vw * m[13], vx * m[1] + vy * m[5] + vz * m[9] + vw * m[13],
@ -308,7 +305,7 @@ var MatrixMath = {
vector: Array<number>, vector: Array<number>,
v3Length: number v3Length: number
): Array<number> { ): Array<number> {
var im = 1 / (v3Length || MatrixMath.v3Length(vector)); const im = 1 / (v3Length || MatrixMath.v3Length(vector));
return [ return [
vector[0] * im, vector[0] * im,
vector[1] * im, vector[1] * im,
@ -372,14 +369,14 @@ var MatrixMath = {
* roll === bank === x-axis * roll === bank === x-axis
*/ */
quaternionToDegreesXYZ(q: Array<number>, matrix, row): Array<number> { quaternionToDegreesXYZ(q: Array<number>, matrix, row): Array<number> {
var [qx, qy, qz, qw] = q; const [qx, qy, qz, qw] = q;
var qw2 = qw * qw; const qw2 = qw * qw;
var qx2 = qx * qx; const qx2 = qx * qx;
var qy2 = qy * qy; const qy2 = qy * qy;
var qz2 = qz * qz; const qz2 = qz * qz;
var test = qx * qy + qz * qw; const test = qx * qy + qz * qw;
var unit = qw2 + qx2 + qy2 + qz2; const unit = qw2 + qx2 + qy2 + qz2;
var conv = 180 / Math.PI; const conv = 180 / Math.PI;
if (test > 0.49999 * unit) { if (test > 0.49999 * unit) {
return [0, 2 * Math.atan2(qx, qw) * conv, 90]; return [0, 2 * Math.atan2(qx, qw) * conv, 90];
@ -406,7 +403,7 @@ var MatrixMath = {
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
*/ */
roundTo3Places(n: number): number { roundTo3Places(n: number): number {
var arr = n.toString().split('e'); const arr = n.toString().split('e');
return Math.round(arr[0] + 'e' + (arr[1] ? (+arr[1] - 3) : 3)) * 0.001; return Math.round(arr[0] + 'e' + (arr[1] ? (+arr[1] - 3) : 3)) * 0.001;
}, },
@ -431,22 +428,22 @@ var MatrixMath = {
// output values // output values
var perspective = []; var perspective = [];
var quaternion = []; const quaternion = [];
var scale = []; const scale = [];
var skew = []; const skew = [];
var translation = []; const translation = [];
// create normalized, 2d array matrix // create normalized, 2d array matrix
// and normalized 1d array perspectiveMatrix with redefined 4th column // and normalized 1d array perspectiveMatrix with redefined 4th column
if (!transformMatrix[15]) { if (!transformMatrix[15]) {
return; return;
} }
var matrix = []; const matrix = [];
var perspectiveMatrix = []; const perspectiveMatrix = [];
for (var i = 0; i < 4; i++) { for (var i = 0; i < 4; i++) {
matrix.push([]); matrix.push([]);
for (var j = 0; j < 4; j++) { for (let j = 0; j < 4; j++) {
var value = transformMatrix[(i * 4) + j] / transformMatrix[15]; const value = transformMatrix[(i * 4) + j] / transformMatrix[15];
matrix[i].push(value); matrix[i].push(value);
perspectiveMatrix.push(j === 3 ? 0 : value); perspectiveMatrix.push(j === 3 ? 0 : value);
} }
@ -462,7 +459,7 @@ var MatrixMath = {
if (matrix[0][3] !== 0 || matrix[1][3] !== 0 || matrix[2][3] !== 0) { if (matrix[0][3] !== 0 || matrix[1][3] !== 0 || matrix[2][3] !== 0) {
// rightHandSide is the right hand side of the equation. // rightHandSide is the right hand side of the equation.
// rightHandSide is a vector, or point in 3d space relative to the origin. // rightHandSide is a vector, or point in 3d space relative to the origin.
var rightHandSide = [ const rightHandSide = [
matrix[0][3], matrix[0][3],
matrix[1][3], matrix[1][3],
matrix[2][3], matrix[2][3],
@ -471,10 +468,10 @@ var MatrixMath = {
// Solve the equation by inverting perspectiveMatrix and multiplying // Solve the equation by inverting perspectiveMatrix and multiplying
// rightHandSide by the inverse. // rightHandSide by the inverse.
var inversePerspectiveMatrix = MatrixMath.inverse( const inversePerspectiveMatrix = MatrixMath.inverse(
perspectiveMatrix perspectiveMatrix
); );
var transposedInversePerspectiveMatrix = MatrixMath.transpose( const transposedInversePerspectiveMatrix = MatrixMath.transpose(
inversePerspectiveMatrix inversePerspectiveMatrix
); );
var perspective = MatrixMath.multiplyVectorByMatrix( var perspective = MatrixMath.multiplyVectorByMatrix(
@ -494,7 +491,7 @@ var MatrixMath = {
// Now get scale and shear. // Now get scale and shear.
// 'row' is a 3 element array of 3 component vectors // 'row' is a 3 element array of 3 component vectors
var row = []; const row = [];
for (i = 0; i < 3; i++) { for (i = 0; i < 3; i++) {
row[i] = [ row[i] = [
matrix[i][0], matrix[i][0],
@ -535,7 +532,7 @@ var MatrixMath = {
// At this point, the matrix (in rows) is orthonormal. // At this point, the matrix (in rows) is orthonormal.
// Check for a coordinate system flip. If the determinant // Check for a coordinate system flip. If the determinant
// is -1, then negate the matrix and the scaling factors. // is -1, then negate the matrix and the scaling factors.
var pdum3 = MatrixMath.v3Cross(row[1], row[2]); const pdum3 = MatrixMath.v3Cross(row[1], row[2]);
if (MatrixMath.v3Dot(row[0], pdum3) < 0) { if (MatrixMath.v3Dot(row[0], pdum3) < 0) {
for (i = 0; i < 3; i++) { for (i = 0; i < 3; i++) {
scale[i] *= -1; scale[i] *= -1;
@ -566,7 +563,7 @@ var MatrixMath = {
} }
// correct for occasional, weird Euler synonyms for 2d rotation // correct for occasional, weird Euler synonyms for 2d rotation
var rotationDegrees; let rotationDegrees;
if ( if (
quaternion[0] < 0.001 && quaternion[0] >= 0 && quaternion[0] < 0.001 && quaternion[0] >= 0 &&
quaternion[1] < 0.001 && quaternion[1] >= 0 quaternion[1] < 0.001 && quaternion[1] >= 0

Просмотреть файл

@ -8,7 +8,7 @@
*/ */
'use strict'; 'use strict';
var Dimensions = require('Dimensions'); const Dimensions = require('Dimensions');
/** /**
* PixelRatio class gives access to the device pixel density. * PixelRatio class gives access to the device pixel density.
@ -108,7 +108,7 @@ class PixelRatio {
* exactly (8.33 * 3) = 25 pixels. * exactly (8.33 * 3) = 25 pixels.
*/ */
static roundToNearestPixel(layoutSize: number): number { static roundToNearestPixel(layoutSize: number): number {
var ratio = PixelRatio.get(); const ratio = PixelRatio.get();
return Math.round(layoutSize * ratio) / ratio; return Math.round(layoutSize * ratio) / ratio;
} }

Просмотреть файл

@ -8,7 +8,7 @@
*/ */
'use strict'; 'use strict';
var MatrixMath = require('MatrixMath'); const MatrixMath = require('MatrixMath');
function degreesToRadians(degrees) { function degreesToRadians(degrees) {
return degrees * Math.PI / 180; return degrees * Math.PI / 180;
@ -26,7 +26,7 @@ describe('MatrixMath', () => {
]).rotationDegrees).toEqual([0, 0, 0]); ]).rotationDegrees).toEqual([0, 0, 0]);
[30, 45, 60, 75, 90, 100, 115, 120, 133, 167].forEach(angle => { [30, 45, 60, 75, 90, 100, 115, 120, 133, 167].forEach(angle => {
var mat = MatrixMath.createRotateZ(degreesToRadians(angle)); let mat = MatrixMath.createRotateZ(degreesToRadians(angle));
expect(convertZeroes(MatrixMath.decomposeMatrix(mat).rotationDegrees)) expect(convertZeroes(MatrixMath.decomposeMatrix(mat).rotationDegrees))
.toEqual([0, 0, angle]); .toEqual([0, 0, angle]);
@ -80,7 +80,7 @@ describe('MatrixMath', () => {
}); });
it('decomposes a 4x4 matrix to produce accurate Y-axis angles', () => { it('decomposes a 4x4 matrix to produce accurate Y-axis angles', () => {
var mat; let mat;
[30, 45, 60, 75, 90, 100, 110, 120, 133, 167].forEach(angle => { [30, 45, 60, 75, 90, 100, 110, 120, 133, 167].forEach(angle => {
mat = MatrixMath.createIdentityMatrix(); mat = MatrixMath.createIdentityMatrix();
MatrixMath.reuseRotateYCommand(mat, degreesToRadians(angle)); MatrixMath.reuseRotateYCommand(mat, degreesToRadians(angle));
@ -112,7 +112,7 @@ describe('MatrixMath', () => {
}); });
it('decomposes a 4x4 matrix to produce accurate X-axis angles', () => { it('decomposes a 4x4 matrix to produce accurate X-axis angles', () => {
var mat; let mat;
[30, 45, 60, 75, 90, 100, 110, 120, 133, 167].forEach(angle => { [30, 45, 60, 75, 90, 100, 110, 120, 133, 167].forEach(angle => {
mat = MatrixMath.createIdentityMatrix(); mat = MatrixMath.createIdentityMatrix();
MatrixMath.reuseRotateXCommand(mat, degreesToRadians(angle)); MatrixMath.reuseRotateXCommand(mat, degreesToRadians(angle));

Просмотреть файл

@ -8,8 +8,8 @@
*/ */
'use strict'; 'use strict';
var PlatformIOS = require('../Platform.ios'); const PlatformIOS = require('../Platform.ios');
var PlatformAndroid = require('../Platform.android'); const PlatformAndroid = require('../Platform.android');
describe('Platform', () => { describe('Platform', () => {

Просмотреть файл

@ -8,11 +8,11 @@
*/ */
'use strict'; 'use strict';
var buildStyleInterpolator = require('buildStyleInterpolator'); const buildStyleInterpolator = require('buildStyleInterpolator');
var validateEmpty = function(interpolator, value, validator) { const validateEmpty = function(interpolator, value, validator) {
var emptyObject = {}; const emptyObject = {};
var changed = interpolator(emptyObject, value); let changed = interpolator(emptyObject, value);
validator(emptyObject); validator(emptyObject);
expect(changed).toBe(true); expect(changed).toBe(true);
changed = interpolator(emptyObject, value); changed = interpolator(emptyObject, value);
@ -20,7 +20,7 @@ var validateEmpty = function(interpolator, value, validator) {
}; };
describe('buildStyleInterpolator', function() { describe('buildStyleInterpolator', function() {
it('should linearly interpolate without extrapolating', function() { it('should linearly interpolate without extrapolating', function() {
var testAnim = { const testAnim = {
opacity: { opacity: {
from: 100, from: 100,
to: 200, to: 200,
@ -42,7 +42,7 @@ describe('buildStyleInterpolator', function() {
value: 23.5, value: 23.5,
}, },
}; };
var interpolator = buildStyleInterpolator(testAnim); const interpolator = buildStyleInterpolator(testAnim);
validateEmpty(interpolator, 0, function(res) { validateEmpty(interpolator, 0, function(res) {
expect(res).toEqual({ expect(res).toEqual({
opacity: 100, opacity: 100,
@ -80,7 +80,7 @@ describe('buildStyleInterpolator', function() {
}); });
}); });
it('should linearly interpolate with extrapolating', function() { it('should linearly interpolate with extrapolating', function() {
var testAnim = { const testAnim = {
opacity: { opacity: {
from: 100, from: 100,
to: 200, to: 200,
@ -104,7 +104,7 @@ describe('buildStyleInterpolator', function() {
value: 23.5, value: 23.5,
}, },
}; };
var interpolator = buildStyleInterpolator(testAnim); const interpolator = buildStyleInterpolator(testAnim);
validateEmpty(interpolator, 0, function(res) { validateEmpty(interpolator, 0, function(res) {
expect(res).toEqual({ expect(res).toEqual({
opacity: 100, opacity: 100,
@ -142,7 +142,7 @@ describe('buildStyleInterpolator', function() {
}); });
}); });
it('should round accordingly', function() { it('should round accordingly', function() {
var testAnim = { const testAnim = {
opacity: { opacity: {
from: 0, from: 0,
to: 1, to: 1,
@ -153,7 +153,7 @@ describe('buildStyleInterpolator', function() {
extrapolate: true, extrapolate: true,
}, },
}; };
var interpolator = buildStyleInterpolator(testAnim); const interpolator = buildStyleInterpolator(testAnim);
validateEmpty(interpolator, 0, function(res) { validateEmpty(interpolator, 0, function(res) {
expect(res).toEqual({ expect(res).toEqual({
opacity: 0, opacity: 0,
@ -186,7 +186,7 @@ describe('buildStyleInterpolator', function() {
}); });
}); });
it('should detect chnages correctly', function() { it('should detect chnages correctly', function() {
var testAnim = { const testAnim = {
opacity: { opacity: {
from: 0, from: 0,
to: 1, to: 1,
@ -197,9 +197,9 @@ describe('buildStyleInterpolator', function() {
extrapolate: false, extrapolate: false,
}, },
}; };
var interpolator = buildStyleInterpolator(testAnim); const interpolator = buildStyleInterpolator(testAnim);
var obj = {}; const obj = {};
var res = interpolator(obj, 0); let res = interpolator(obj, 0);
expect(obj).toEqual({ expect(obj).toEqual({
opacity: 0, opacity: 0,
}); });
@ -227,14 +227,14 @@ describe('buildStyleInterpolator', function() {
expect(res).toBe(false); expect(res).toBe(false);
}); });
it('should handle identity', function() { it('should handle identity', function() {
var testAnim = { const testAnim = {
opacity: { opacity: {
type: 'identity', type: 'identity',
}, },
}; };
var interpolator = buildStyleInterpolator(testAnim); const interpolator = buildStyleInterpolator(testAnim);
var obj = {}; const obj = {};
var res = interpolator(obj, 0.5); let res = interpolator(obj, 0.5);
expect(obj).toEqual({ expect(obj).toEqual({
opacity: 0.5, opacity: 0.5,
}); });
@ -248,7 +248,7 @@ describe('buildStyleInterpolator', function() {
expect(res).toBe(false); expect(res).toBe(false);
}); });
it('should translate', function() { it('should translate', function() {
var testAnim = { const testAnim = {
transformTranslate: { transformTranslate: {
from: {x: 1, y: 10, z: 100}, from: {x: 1, y: 10, z: 100},
to: {x: 5, y: 50, z: 500}, to: {x: 5, y: 50, z: 500},
@ -257,9 +257,9 @@ describe('buildStyleInterpolator', function() {
type: 'linear', type: 'linear',
}, },
}; };
var interpolator = buildStyleInterpolator(testAnim); const interpolator = buildStyleInterpolator(testAnim);
var obj = {}; const obj = {};
var res = interpolator(obj, 1); const res = interpolator(obj, 1);
expect(obj).toEqual({ expect(obj).toEqual({
transform: [{matrix: [1, 0, 0, 0, transform: [{matrix: [1, 0, 0, 0,
0, 1, 0, 0, 0, 1, 0, 0,
@ -269,7 +269,7 @@ describe('buildStyleInterpolator', function() {
expect(res).toBe(true); expect(res).toBe(true);
}); });
it('should scale', function() { it('should scale', function() {
var testAnim = { const testAnim = {
transformScale: { transformScale: {
from: {x: 1, y: 10, z: 100}, from: {x: 1, y: 10, z: 100},
to: {x: 5, y: 50, z: 500}, to: {x: 5, y: 50, z: 500},
@ -278,9 +278,9 @@ describe('buildStyleInterpolator', function() {
type: 'linear', type: 'linear',
}, },
}; };
var interpolator = buildStyleInterpolator(testAnim); const interpolator = buildStyleInterpolator(testAnim);
var obj = {}; const obj = {};
var res = interpolator(obj, 1); const res = interpolator(obj, 1);
expect(obj).toEqual({ expect(obj).toEqual({
transform: [{matrix: [2, 0, 0, 0, transform: [{matrix: [2, 0, 0, 0,
0, 20, 0, 0, 0, 20, 0, 0,
@ -290,7 +290,7 @@ describe('buildStyleInterpolator', function() {
expect(res).toBe(true); expect(res).toBe(true);
}); });
it('should combine scale and translate', function() { it('should combine scale and translate', function() {
var testAnim = { const testAnim = {
transformScale: { transformScale: {
from: {x: 1, y: 10, z: 100}, from: {x: 1, y: 10, z: 100},
to: {x: 5, y: 50, z: 500}, to: {x: 5, y: 50, z: 500},
@ -306,9 +306,9 @@ describe('buildStyleInterpolator', function() {
type: 'linear', type: 'linear',
}, },
}; };
var interpolator = buildStyleInterpolator(testAnim); const interpolator = buildStyleInterpolator(testAnim);
var obj = {}; const obj = {};
var res = interpolator(obj, 1); const res = interpolator(obj, 1);
expect(obj).toEqual({ expect(obj).toEqual({
transform: [{matrix: [2, 0, 0, 0, transform: [{matrix: [2, 0, 0, 0,
0, 20, 0, 0, 0, 20, 0, 0,
@ -318,7 +318,7 @@ describe('buildStyleInterpolator', function() {
expect(res).toBe(true); expect(res).toBe(true);
}); });
it('should step', function() { it('should step', function() {
var testAnim = { const testAnim = {
opacity: { opacity: {
threshold: 13, threshold: 13,
from: 10, from: 10,
@ -326,9 +326,9 @@ describe('buildStyleInterpolator', function() {
type: 'step', type: 'step',
}, },
}; };
var interpolator = buildStyleInterpolator(testAnim); const interpolator = buildStyleInterpolator(testAnim);
var obj = {}; const obj = {};
var res = interpolator(obj, 0); let res = interpolator(obj, 0);
expect(obj).toEqual({ expect(obj).toEqual({
opacity: 10, opacity: 10,
}); });

Просмотреть файл

@ -6,7 +6,7 @@
* *
* @emails oncall+react_native * @emails oncall+react_native
*/ */
var deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev'); const deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
describe('deepFreezeAndThrowOnMutationInDev', function() { describe('deepFreezeAndThrowOnMutationInDev', function() {
@ -28,7 +28,7 @@ describe('deepFreezeAndThrowOnMutationInDev', function() {
it('should throw on mutation in dev with strict', () => { it('should throw on mutation in dev with strict', () => {
'use strict'; 'use strict';
__DEV__ = true; __DEV__ = true;
var o = {key: 'oldValue'}; const o = {key: 'oldValue'};
deepFreezeAndThrowOnMutationInDev(o); deepFreezeAndThrowOnMutationInDev(o);
expect(() => { o.key = 'newValue'; }).toThrowError( expect(() => { o.key = 'newValue'; }).toThrowError(
'You attempted to set the key `key` with the value `"newValue"` ' + 'You attempted to set the key `key` with the value `"newValue"` ' +
@ -39,7 +39,7 @@ describe('deepFreezeAndThrowOnMutationInDev', function() {
it('should throw on mutation in dev without strict', () => { it('should throw on mutation in dev without strict', () => {
__DEV__ = true; __DEV__ = true;
var o = {key: 'oldValue'}; const o = {key: 'oldValue'};
deepFreezeAndThrowOnMutationInDev(o); deepFreezeAndThrowOnMutationInDev(o);
expect(() => { o.key = 'newValue'; }).toThrowError( expect(() => { o.key = 'newValue'; }).toThrowError(
'You attempted to set the key `key` with the value `"newValue"` ' + 'You attempted to set the key `key` with the value `"newValue"` ' +
@ -51,7 +51,7 @@ describe('deepFreezeAndThrowOnMutationInDev', function() {
it('should throw on nested mutation in dev with strict', () => { it('should throw on nested mutation in dev with strict', () => {
'use strict'; 'use strict';
__DEV__ = true; __DEV__ = true;
var o = {key1: {key2: {key3: 'oldValue'}}}; const o = {key1: {key2: {key3: 'oldValue'}}};
deepFreezeAndThrowOnMutationInDev(o); deepFreezeAndThrowOnMutationInDev(o);
expect(() => { o.key1.key2.key3 = 'newValue'; }).toThrowError( expect(() => { o.key1.key2.key3 = 'newValue'; }).toThrowError(
'You attempted to set the key `key3` with the value `"newValue"` ' + 'You attempted to set the key `key3` with the value `"newValue"` ' +
@ -62,7 +62,7 @@ describe('deepFreezeAndThrowOnMutationInDev', function() {
it('should throw on nested mutation in dev without strict', () => { it('should throw on nested mutation in dev without strict', () => {
__DEV__ = true; __DEV__ = true;
var o = {key1: {key2: {key3: 'oldValue'}}}; const o = {key1: {key2: {key3: 'oldValue'}}};
deepFreezeAndThrowOnMutationInDev(o); deepFreezeAndThrowOnMutationInDev(o);
expect(() => { o.key1.key2.key3 = 'newValue'; }).toThrowError( expect(() => { o.key1.key2.key3 = 'newValue'; }).toThrowError(
'You attempted to set the key `key3` with the value `"newValue"` ' + 'You attempted to set the key `key3` with the value `"newValue"` ' +
@ -74,7 +74,7 @@ describe('deepFreezeAndThrowOnMutationInDev', function() {
it('should throw on insertion in dev with strict', () => { it('should throw on insertion in dev with strict', () => {
'use strict'; 'use strict';
__DEV__ = true; __DEV__ = true;
var o = {oldKey: 'value'}; const o = {oldKey: 'value'};
deepFreezeAndThrowOnMutationInDev(o); deepFreezeAndThrowOnMutationInDev(o);
expect(() => { o.newKey = 'value'; }) expect(() => { o.newKey = 'value'; })
.toThrowError( .toThrowError(
@ -85,7 +85,7 @@ describe('deepFreezeAndThrowOnMutationInDev', function() {
it('should not throw on insertion in dev without strict', () => { it('should not throw on insertion in dev without strict', () => {
__DEV__ = true; __DEV__ = true;
var o = {oldKey: 'value'}; const o = {oldKey: 'value'};
deepFreezeAndThrowOnMutationInDev(o); deepFreezeAndThrowOnMutationInDev(o);
expect(() => { o.newKey = 'value'; }).not.toThrow(); expect(() => { o.newKey = 'value'; }).not.toThrow();
expect(o.newKey).toBe(undefined); expect(o.newKey).toBe(undefined);
@ -94,7 +94,7 @@ describe('deepFreezeAndThrowOnMutationInDev', function() {
it('should mutate and not throw on mutation in prod', () => { it('should mutate and not throw on mutation in prod', () => {
'use strict'; 'use strict';
__DEV__ = false; __DEV__ = false;
var o = {key: 'oldValue'}; const o = {key: 'oldValue'};
deepFreezeAndThrowOnMutationInDev(o); deepFreezeAndThrowOnMutationInDev(o);
expect(() => { o.key = 'newValue'; }).not.toThrow(); expect(() => { o.key = 'newValue'; }).not.toThrow();
expect(o.key).toBe('newValue'); expect(o.key).toBe('newValue');
@ -104,7 +104,7 @@ describe('deepFreezeAndThrowOnMutationInDev', function() {
it('should not deep freeze already frozen objects', () => { it('should not deep freeze already frozen objects', () => {
'use strict'; 'use strict';
__DEV__ = true; __DEV__ = true;
var o = {key1: {key2: 'oldValue'}}; const o = {key1: {key2: 'oldValue'}};
Object.freeze(o); Object.freeze(o);
deepFreezeAndThrowOnMutationInDev(o); deepFreezeAndThrowOnMutationInDev(o);
expect(() => { o.key1.key2 = 'newValue'; }).not.toThrow(); expect(() => { o.key1.key2 = 'newValue'; }).not.toThrow();
@ -113,7 +113,7 @@ describe('deepFreezeAndThrowOnMutationInDev', function() {
it("shouldn't recurse infinitely", () => { it("shouldn't recurse infinitely", () => {
__DEV__ = true; __DEV__ = true;
var o = {}; const o = {};
o.circular = o; o.circular = o;
deepFreezeAndThrowOnMutationInDev(o); deepFreezeAndThrowOnMutationInDev(o);
}); });

Просмотреть файл

@ -9,7 +9,7 @@
'use strict'; 'use strict';
describe('groupByEveryN', () => { describe('groupByEveryN', () => {
var groupByEveryN = require('groupByEveryN'); const groupByEveryN = require('groupByEveryN');
it('should group by with different n', () => { it('should group by with different n', () => {
expect(groupByEveryN([1, 2, 3, 4, 5, 6, 7, 8, 9], 1)) expect(groupByEveryN([1, 2, 3, 4, 5, 6, 7, 8, 9], 1))

Просмотреть файл

@ -10,7 +10,7 @@
describe('truncate', () => { describe('truncate', () => {
var truncate = require('truncate'); const truncate = require('truncate');
it('should truncate', () => { it('should truncate', () => {
expect(truncate('Hello, world.', 5)) expect(truncate('Hello, world.', 5))

Просмотреть файл

@ -8,18 +8,18 @@
'use strict'; 'use strict';
var keyOf = require('fbjs/lib/keyOf'); const keyOf = require('fbjs/lib/keyOf');
var X_DIM = keyOf({x: null}); const X_DIM = keyOf({x: null});
var Y_DIM = keyOf({y: null}); const Y_DIM = keyOf({y: null});
var Z_DIM = keyOf({z: null}); const Z_DIM = keyOf({z: null});
var InitialOperationField = { const InitialOperationField = {
transformTranslate: [0, 0, 0], transformTranslate: [0, 0, 0],
transformScale: [1, 1, 1], transformScale: [1, 1, 1],
}; };
var InterpolateMatrix = { const InterpolateMatrix = {
transformScale: function(mat, x, y, z) { transformScale: function(mat, x, y, z) {
mat[0] = mat[0] * x; mat[0] = mat[0] * x;
mat[1] = mat[1] * x; mat[1] = mat[1] * x;
@ -42,27 +42,27 @@ var InterpolateMatrix = {
} }
}; };
var computeNextValLinear = function(anim, from, to, value) { const computeNextValLinear = function(anim, from, to, value) {
var hasRoundRatio = 'round' in anim; const hasRoundRatio = 'round' in anim;
var roundRatio = anim.round; const roundRatio = anim.round;
var ratio = (value - anim.min) / (anim.max - anim.min); let ratio = (value - anim.min) / (anim.max - anim.min);
if (!anim.extrapolate) { if (!anim.extrapolate) {
ratio = ratio > 1 ? 1 : (ratio < 0 ? 0 : ratio); ratio = ratio > 1 ? 1 : (ratio < 0 ? 0 : ratio);
} }
var nextVal = from * (1 - ratio) + to * ratio; let nextVal = from * (1 - ratio) + to * ratio;
if (hasRoundRatio) { if (hasRoundRatio) {
nextVal = Math.round(roundRatio * nextVal) / roundRatio; nextVal = Math.round(roundRatio * nextVal) / roundRatio;
} }
return nextVal; return nextVal;
}; };
var computeNextValLinearScalar = function(anim, value) { const computeNextValLinearScalar = function(anim, value) {
return computeNextValLinear(anim, anim.from, anim.to, value); return computeNextValLinear(anim, anim.from, anim.to, value);
}; };
var setNextValAndDetectChange = function(result, name, nextVal, didChange) { const setNextValAndDetectChange = function(result, name, nextVal, didChange) {
if (!didChange) { if (!didChange) {
var prevVal = result[name]; const prevVal = result[name];
result[name] = nextVal; result[name] = nextVal;
didChange = didChange || (nextVal !== prevVal); didChange = didChange || (nextVal !== prevVal);
} else { } else {
@ -71,7 +71,7 @@ var setNextValAndDetectChange = function(result, name, nextVal, didChange) {
return didChange; return didChange;
}; };
var initIdentity = function(mat) { const initIdentity = function(mat) {
mat[0] = 1; mat[0] = 1;
mat[1] = 0; mat[1] = 0;
mat[2] = 0; mat[2] = 0;
@ -90,7 +90,7 @@ var initIdentity = function(mat) {
mat[15] = 1; mat[15] = 1;
}; };
var computeNextMatrixOperationField = function(anim, name, dim, index, value) { const computeNextMatrixOperationField = function(anim, name, dim, index, value) {
if (anim.from[dim] !== undefined && anim.to[dim] !== undefined) { if (anim.from[dim] !== undefined && anim.to[dim] !== undefined) {
return computeNextValLinear(anim, anim.from[dim], anim.to[dim], value); return computeNextValLinear(anim, anim.from[dim], anim.to[dim], value);
} else { } else {
@ -98,33 +98,33 @@ var computeNextMatrixOperationField = function(anim, name, dim, index, value) {
} }
}; };
var computeTransform = function(anim, name, value, result, const computeTransform = function(anim, name, value, result,
didChange, didMatrix) { didChange, didMatrix) {
var transform = result.transform !== undefined ? const transform = result.transform !== undefined ?
result.transform : (result.transform = [{ matrix: [] }]); result.transform : (result.transform = [{ matrix: [] }]);
var mat = transform[0].matrix; const mat = transform[0].matrix;
var m0 = mat[0]; const m0 = mat[0];
var m1 = mat[1]; const m1 = mat[1];
var m2 = mat[2]; const m2 = mat[2];
var m3 = mat[3]; const m3 = mat[3];
var m4 = mat[4]; const m4 = mat[4];
var m5 = mat[5]; const m5 = mat[5];
var m6 = mat[6]; const m6 = mat[6];
var m7 = mat[7]; const m7 = mat[7];
var m8 = mat[8]; const m8 = mat[8];
var m9 = mat[9]; const m9 = mat[9];
var m10 = mat[10]; const m10 = mat[10];
var m11 = mat[11]; const m11 = mat[11];
var m12 = mat[12]; const m12 = mat[12];
var m13 = mat[13]; const m13 = mat[13];
var m14 = mat[14]; const m14 = mat[14];
var m15 = mat[15]; const m15 = mat[15];
if (!didMatrix) { if (!didMatrix) {
initIdentity(mat); // This will be the first transform. initIdentity(mat); // This will be the first transform.
} }
var x = computeNextMatrixOperationField(anim, name, X_DIM, 0, value); const x = computeNextMatrixOperationField(anim, name, X_DIM, 0, value);
var y = computeNextMatrixOperationField(anim, name, Y_DIM, 1, value); const y = computeNextMatrixOperationField(anim, name, Y_DIM, 1, value);
var z = computeNextMatrixOperationField(anim, name, Z_DIM, 2, value); const z = computeNextMatrixOperationField(anim, name, Z_DIM, 2, value);
InterpolateMatrix[name](mat, x, y, z); InterpolateMatrix[name](mat, x, y, z);
if (!didChange) { if (!didChange) {
didChange = m0 !== mat[0] || m1 !== mat[1] || didChange = m0 !== mat[0] || m1 !== mat[1] ||
@ -144,12 +144,12 @@ var computeTransform = function(anim, name, value, result,
* @return {function} Function accepting style object, that mutates that style * @return {function} Function accepting style object, that mutates that style
* object and returns a boolean describing if any update was actually applied. * object and returns a boolean describing if any update was actually applied.
*/ */
var buildStyleInterpolator = function(anims) { const buildStyleInterpolator = function(anims) {
function styleInterpolator(result, value) { function styleInterpolator(result, value) {
var didChange = false; let didChange = false;
var didMatrix = false; let didMatrix = false;
for (var name in anims) { for (const name in anims) {
var anim = anims[name]; const anim = anims[name];
if (anim.type === 'linear') { if (anim.type === 'linear') {
if (name in InterpolateMatrix) { if (name in InterpolateMatrix) {
didChange = computeTransform(anim, name, value, result, didChange = computeTransform(anim, name, value, result,

Просмотреть файл

@ -8,8 +8,8 @@
*/ */
'use strict'; 'use strict';
var invariant = require('fbjs/lib/invariant'); const invariant = require('fbjs/lib/invariant');
var merge = require('merge'); const merge = require('merge');
function createStrictShapeTypeChecker( function createStrictShapeTypeChecker(
shapeTypes: {[key: string]: ReactPropsCheckType} shapeTypes: {[key: string]: ReactPropsCheckType}
@ -25,9 +25,9 @@ function createStrictShapeTypeChecker(
} }
return; return;
} }
var propValue = props[propName]; const propValue = props[propName];
var propType = typeof propValue; const propType = typeof propValue;
var locationName = location || '(unknown)'; const locationName = location || '(unknown)';
if (propType !== 'object') { if (propType !== 'object') {
invariant( invariant(
false, false,
@ -37,9 +37,9 @@ function createStrictShapeTypeChecker(
} }
// We need to check all keys in case some are required but missing from // We need to check all keys in case some are required but missing from
// props. // props.
var allKeys = merge(props[propName], shapeTypes); const allKeys = merge(props[propName], shapeTypes);
for (var key in allKeys) { for (const key in allKeys) {
var checker = shapeTypes[key]; const checker = shapeTypes[key];
if (!checker) { if (!checker) {
invariant( invariant(
false, false,
@ -48,7 +48,7 @@ function createStrictShapeTypeChecker(
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
); );
} }
var error = checker(propValue, key, componentName, location, ...rest); const error = checker(propValue, key, componentName, location, ...rest);
if (error) { if (error) {
invariant( invariant(
false, false,

Просмотреть файл

@ -35,7 +35,7 @@ function deepFreezeAndThrowOnMutationInDev<T: Object>(object: T): T {
return object; return object;
} }
var keys = Object.keys(object); const keys = Object.keys(object);
for (var i = 0; i < keys.length; i++) { for (var i = 0; i < keys.length; i++) {
var key = keys[i]; var key = keys[i];

Просмотреть файл

@ -8,7 +8,7 @@
*/ */
'use strict'; 'use strict';
var deepDiffer = require('deepDiffer'); const deepDiffer = require('deepDiffer');
describe('deepDiffer', function() { describe('deepDiffer', function() {
it('should diff primitives of the same type', () => { it('should diff primitives of the same type', () => {
@ -95,7 +95,7 @@ describe('deepDiffer', function() {
expect(deepDiffer(['a', 'b'], {length: 2, 0: 'a', 1: 'b'})).toBe(true); expect(deepDiffer(['a', 'b'], {length: 2, 0: 'a', 1: 'b'})).toBe(true);
}); });
it('should diff same object', () => { it('should diff same object', () => {
var obj = [1,[2,3]]; const obj = [1,[2,3]];
expect(deepDiffer(obj, obj)).toBe(false); expect(deepDiffer(obj, obj)).toBe(false);
}); });
it('should respect maxDepth arg', () => { it('should respect maxDepth arg', () => {

Просмотреть файл

@ -11,7 +11,7 @@
/* /*
* @returns {bool} true if different, false if equal * @returns {bool} true if different, false if equal
*/ */
var deepDiffer = function(one: any, two: any, maxDepth: number = -1): bool { const deepDiffer = function(one: any, two: any, maxDepth: number = -1): bool {
if (maxDepth === 0) { if (maxDepth === 0) {
return true; return true;
} }
@ -37,22 +37,22 @@ var deepDiffer = function(one: any, two: any, maxDepth: number = -1): bool {
} }
if (Array.isArray(one)) { if (Array.isArray(one)) {
// We know two is also an array because the constructors are equal // We know two is also an array because the constructors are equal
var len = one.length; const len = one.length;
if (two.length !== len) { if (two.length !== len) {
return true; return true;
} }
for (var ii = 0; ii < len; ii++) { for (let ii = 0; ii < len; ii++) {
if (deepDiffer(one[ii], two[ii], maxDepth - 1)) { if (deepDiffer(one[ii], two[ii], maxDepth - 1)) {
return true; return true;
} }
} }
} else { } else {
for (var key in one) { for (const key in one) {
if (deepDiffer(one[key], two[key], maxDepth - 1)) { if (deepDiffer(one[key], two[key], maxDepth - 1)) {
return true; return true;
} }
} }
for (var twoKey in two) { for (const twoKey in two) {
// The only case we haven't checked yet is keys that are in two but aren't // The only case we haven't checked yet is keys that are in two but aren't
// in one, which means they are different. // in one, which means they are different.
if (one[twoKey] === undefined && two[twoKey] !== undefined) { if (one[twoKey] === undefined && two[twoKey] !== undefined) {

Просмотреть файл

@ -15,14 +15,14 @@ type Inset = {
bottom: ?number, bottom: ?number,
} }
var dummyInsets = { const dummyInsets = {
top: undefined, top: undefined,
left: undefined, left: undefined,
right: undefined, right: undefined,
bottom: undefined, bottom: undefined,
}; };
var insetsDiffer = function( const insetsDiffer = function(
one: ?Inset, one: ?Inset,
two: ?Inset two: ?Inset
): bool { ): bool {

Просмотреть файл

@ -16,7 +16,7 @@
* @param {MatrixMath.Matrix} two Second matrix. * @param {MatrixMath.Matrix} two Second matrix.
* @return {boolean} Whether or not the two matrices differ. * @return {boolean} Whether or not the two matrices differ.
*/ */
var matricesDiffer = function(one, two) { const matricesDiffer = function(one, two) {
if (one === two) { if (one === two) {
return false; return false;
} }

Просмотреть файл

@ -13,9 +13,9 @@ type Point = {
y: ?number, y: ?number,
} }
var dummyPoint = {x: undefined, y: undefined}; const dummyPoint = {x: undefined, y: undefined};
var pointsDiffer = function(one: ?Point, two: ?Point): bool { const pointsDiffer = function(one: ?Point, two: ?Point): bool {
one = one || dummyPoint; one = one || dummyPoint;
two = two || dummyPoint; two = two || dummyPoint;
return one !== two && ( return one !== two && (

Просмотреть файл

@ -7,9 +7,9 @@
*/ */
'use strict'; 'use strict';
var dummySize = {width: undefined, height: undefined}; const dummySize = {width: undefined, height: undefined};
var sizesDiffer = function(one, two) { const sizesDiffer = function(one, two) {
one = one || dummySize; one = one || dummySize;
two = two || dummySize; two = two || dummySize;
return one !== two && ( return one !== two && (

Просмотреть файл

@ -9,7 +9,7 @@
*/ */
'use strict'; 'use strict';
var TextInputState = require('TextInputState'); const TextInputState = require('TextInputState');
function dismissKeyboard() { function dismissKeyboard() {
TextInputState.blurTextInput(TextInputState.currentlyFocusedField()); TextInputState.blurTextInput(TextInputState.currentlyFocusedField());

Просмотреть файл

@ -25,10 +25,10 @@
'use strict'; 'use strict';
function groupByEveryN<T>(array: Array<T>, n: number): Array<Array<?T>> { function groupByEveryN<T>(array: Array<T>, n: number): Array<Array<?T>> {
var result = []; const result = [];
var temp = []; let temp = [];
for (var i = 0; i < array.length; ++i) { for (let i = 0; i < array.length; ++i) {
if (i > 0 && i % n === 0) { if (i > 0 && i % n === 0) {
result.push(temp); result.push(temp);
temp = []; temp = [];

Просмотреть файл

@ -13,9 +13,9 @@
* `console.error` as a failure callback - it's not properly bound. If passes an * `console.error` as a failure callback - it's not properly bound. If passes an
* `Error` object, it will print the message and stack. * `Error` object, it will print the message and stack.
*/ */
var logError = function(...args: $ReadOnlyArray<mixed>) { const logError = function(...args: $ReadOnlyArray<mixed>) {
if (args.length === 1 && args[0] instanceof Error) { if (args.length === 1 && args[0] instanceof Error) {
var err = args[0]; const err = args[0];
console.error('Error: "' + err.message + '". Stack:\n' + err.stack); console.error('Error: "' + err.message + '". Stack:\n' + err.stack);
} else { } else {
console.error.apply(console, args); console.error.apply(console, args);

Просмотреть файл

@ -15,8 +15,8 @@
* @param {object} one Object to assign to. * @param {object} one Object to assign to.
* @param {object} two Object to assign from. * @param {object} two Object to assign from.
*/ */
var mergeIntoFast = function(one: Object, two: Object): void { const mergeIntoFast = function(one: Object, two: Object): void {
for (var keyTwo in two) { for (const keyTwo in two) {
one[keyTwo] = two[keyTwo]; one[keyTwo] = two[keyTwo];
} }
}; };

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше