Compare commits

..
Author SHA1 Message Date
Hector Ramos 84c063c4a3 Remove StyleGuide.md 2017-07-28 11:42:04 -07:00
Hector Ramos 36890d78d8 What to Expect from Maintainers
Summary:
Adds a new maintainers guide, and updates the contributor's guide to be consistent with regards to this new guide.

Some additional style changes made in order to support the display of bot commands. Changed the wording for the "Edit this page on GitHub" link.

Finally, the contributor's guide is now synced to `CONTRIBUTING.md` on the repo.

```
cd website && npm start
```

Verify that `CONTRIBUTING.md` is updated whenever the website is regenerated.

Verify everything rendered correctly. Expand the details below to see screenshots.

<details>

![screencapture-localhost-8079-react-native-docs-contributing-html-1501016495792](https://user-images.githubusercontent.com/165856/28593706-33d1e03c-7142-11e7-9878-04ead7561abc.png)

![screencapture-localhost-8079-react-native-docs-maintainers-html-1501016508744](https://user-images.githubusercontent.com/165856/28593719-3812d7fa-7142-11e7-9db2-f9599057d726.png)
</details>
Closes https://github.com/facebook/react-native/pull/15202

Differential Revision: D5494246

Pulled By: hramos

fbshipit-source-id: e28d5624d1e4795e212f10e8d5713d91a0eae15f
2017-07-28 11:41:22 -07:00
Hector Ramos d41957d7e5 How to Contribute updates
Summary:
Rename "Testing" guide. Add docs for several new GitHub bot commands. Format commands table.

Built website and verified everything looks good.
Closes https://github.com/facebook/react-native/pull/15111

Differential Revision: D5458660

Pulled By: hramos

fbshipit-source-id: 151ea0cbd18489bc527193682464ca291d6ab467
2017-07-20 09:15:05 -07:00
Hector Ramos d4e6bcd9cd Move CONTRIBUTING guidelines to a standalone doc in the website.
Reviewed By: TheSavior

Differential Revision: D5448961

fbshipit-source-id: c8491b003413e8af22987ea578d6f7bbe1552b31
2017-07-19 12:50:51 -07:00
Mike Grabowski 1e2a924ba6 [0.46.4] Bump version numbers 2017-07-17 13:49:59 -07:00
ArturKlajnerok 713ca68396 Removing test-driver symlink in ios third party install script
Summary:
After execution of `scripts/ios-install-third-party.sh` a symlink is created :
`<YOUR-APP-PATH>/node_modules/react-native/third-party/glog-0.3.4/test-driver`
that is pointing to `test-driver -> /usr/share/automake-1.14/test-driver`
This can be executed indirectly by `react-native run-ios`.

This breaks the bundle process if the system don't contain a given file under the link and having this strict dependency on the system setup is not a good practice.

Once the `test-driver` symlink is created android app release is failing, for :
`./gradlew assembleRelease`
the `:app:bundleReleaseJsAndAssets` returns :
```
FAILURE: Build failed with an exception.

* What went wrong:
Could not list contents of '<YOUR-APP-PATH>/node_modules/react-native/third-party/glog-0.3.4/test-driver'. Couldn't follow symbolic link.
```
Related issues:
https://github.com/facebook/react-native/issues/14417
https://github.com/facebook/react-native/issues/14464
https://github.com/facebook/react-native/issues/14548

1. Create new project with `react-native init <YOUR-APP>`
2. cd `<YOUR-APP>/`
3. Run app on iOS `react-native run-ios` so `scripts/ios-install-third-party.sh` is executed.
4. cd `android/`
5. Run android app release `./gradlew assembleRelease` (it will work properly after this fix and fail if the `test-driver` symlink exists)

IMHO we should resolve the issue with this quick fix and apply the proper fix later after the new version of `google/glog` will be released.
The proper cleanup of files generated by autotools was already applied : https://github.com/google/glog/pull/188

Please let me know if I should provide more details : javache, mhorowitz, hramos
Closes https://github.com/facebook/react-native/pull/14638

Differential Revision: D5292362

Pulled By: javache

fbshipit-source-id: 81ff2273420ea078d624a76e781a5b67b96e6a4e
2017-07-17 13:49:38 -07:00
Hector Ramos 579e574c9b [0.46.3] Bump version numbers 2017-07-14 12:50:25 -07:00
Janic Duplessis 206765acb8 Fix configure glog script when building from xcodebuild
Summary:
I encountered an issue when building with fastlane gym / xcodebuild where glog would not build because of missing config.h header file. I tracked it down to the ios-configure-glog.sh script that ended up error-ing because of missing valid c compiler. I guess it didn't enter the if to set c compiler env in xcodebuild and that env doesn't have proper values set like it does in xcode so just removing this check fixed it. Also tested that it still works properly in xcode.
Closes https://github.com/facebook/react-native/pull/14267

Differential Revision: D5285691

Pulled By: javache

fbshipit-source-id: df5315926c2d2d78806618df3d9c9bbbb974d1ea
2017-07-14 12:46:57 -07:00
Hector Ramos 0ea75f537a [0.46.2] Bump version numbers 2017-07-12 16:14:29 -07:00
Seth Fitzsimmons 82fc0f3714 Replace React.createClass with create-react-class
Summary:
This replaces all uses of `React.createClass` with `createReactClass` from the `create-react-class` package, attempting to match use of `var` and `const` according to local style.

Fixes #14620
Refs #14712
Closes https://github.com/facebook/react-native/pull/14729

Differential Revision: D5321810

Pulled By: hramos

fbshipit-source-id: ae7b40640b2773fd89c3fb727ec87f688bebf585
2017-07-12 16:13:28 -07:00
Seth Fitzsimmons e76eb32058 react@16 did away with PropTypes; require prop-types instead
Summary:
react@16 (a peerDependency) did away with the PropTypes export in favor of the prop-types module.

This updates all of the remaining references to `React.PropTypes`.
Closes https://github.com/facebook/react-native/pull/14641

Differential Revision: D5287167

Pulled By: javache

fbshipit-source-id: a917e29aa0e5470260568995dfe97f5528ec265e
2017-07-12 16:07:11 -07:00
Andrew Imm 708f1cf5a2 Update remaining PropTypes references
Reviewed By: bvaughn

Differential Revision: D5231309

fbshipit-source-id: d54ee4f73dae63124f4462c138383447829a2551
2017-07-12 16:06:55 -07:00
Mike Grabowski 3a9d4963a3 [0.46.1] Bump version numbers 2017-07-07 18:22:18 +02:00
Tim Yung 12f945f20c RN: Expose unstable_batchedUpdates on react-native
Reviewed By: spicyj

Differential Revision: D5284484

fbshipit-source-id: bdc0a1c3babfa1a5c3343f084bdd5d4ff4f2d46a
2017-07-07 18:19:05 +02:00
Parashuram N b5674f22c1 Updating the usage of inquirer API
Summary:
Inquirer was changed to a later version in https://github.com/facebook/react-native/commit/bada25d158e070fd683a10b8ff9cdcb8d2498b14. However, the API also needed to be updated to use a promise based version.
Closes https://github.com/facebook/react-native/pull/14848

Differential Revision: D5375663

Pulled By: javache

fbshipit-source-id: 635798a43905301c65db5f63b9cfba1c16964870
2017-07-07 18:18:08 +02:00
Mike Grabowski a42ebc18ce [0.46.0] Bump version numbers 2017-07-05 16:50:01 +02:00
Mike Grabowski 2679473a87 Bump react-docgen version to support create-react-class 2017-07-05 16:48:04 +02:00
Seth Fitzsimmons 084a18de64 Replace React.createClass with create-react-class 2017-07-05 15:34:50 +02:00
Marc Horowitz 2d742e7d5d Remove unused folly/File.{h,cpp} from OSS React Xcode project
Summary: This fixes https://github.com/facebook/react-native/issues/14328

Reviewed By: javache

Differential Revision: D5254711

fbshipit-source-id: e9b81e537cca9d6648f44ed61acd127015d2e1f8
2017-07-04 10:25:59 +02:00
Seth Fitzsimmons dee6aab88a react@16 did away with PropTypes; require prop-types instead
Summary:
react@16 (a peerDependency) did away with the PropTypes export in favor of the prop-types module.

This updates all of the remaining references to `React.PropTypes`.
Closes https://github.com/facebook/react-native/pull/14641

Differential Revision: D5287167

Pulled By: javache

fbshipit-source-id: a917e29aa0e5470260568995dfe97f5528ec265e
2017-07-04 10:23:19 +02:00
Andrew Imm 415fe90ff3 Update remaining PropTypes references
Reviewed By: bvaughn

Differential Revision: D5231309

fbshipit-source-id: d54ee4f73dae63124f4462c138383447829a2551
2017-07-04 10:23:14 +02:00
Aaron Chiu 1ad887eea6 fix dev reloading
Reviewed By: achen1

Differential Revision: D5187906

fbshipit-source-id: 8c35ee0747bdc0f6748ecdca54e223eafe37e105
2017-07-04 10:22:44 +02:00
Janic Duplessis 08f41bcbf4 Native Animated - Call x.__makeNative before super.__makeNative
Summary:
This fixes a `Attempt to get native tag from node not marked as "native"` error that happens because some animated values are not converted to native before calling the base class `__makeNative`. This makes sure we call the `__makeNative` method of input nodes before calling `super.__makeNative`.

**Test plan**
Tested that it fixes the issue I encountered and that native animations still work with properly in RNTester.
Closes https://github.com/facebook/react-native/pull/14435

Differential Revision: D5236092

Pulled By: javache

fbshipit-source-id: cb02616aec05f220c65b58831ca4334b58d0383b
2017-06-14 12:53:09 -07:00
Hector Ramos eb7d3bae26 [0.46.0-rc.2] Bump version numbers 2017-06-09 13:14:16 -07:00
Adam Miskiewicz 43c06e263b Fix broken default getProjectRoots
Summary:
In <= 0.44, the default implementation of getProjectRoots() came from `local-cli/core/default.config.js`. With changes happening in the CLI and the packager over the course of the last two months, various pieces of this logic (specifically `local-cli/utils/Config.js`) were rewritten, and though default.config.js was still being imported and used in `local-cli/core/index.js`, the default `getProjectRoots()` was being overriden by the defaults specified in `local-cli/utils/Config.js`.

This PR moves the logic from default.config.js into Config.js and index.js, as appropriate. Specifically:

- The `getProjectCommands()`, `getProjectConfig()`, and `getDependencyConfig()` methods, which have traditionally not been part of the rn-cli.config.js spec, are now defined in `local-cli/core/index.js`.
- The `getProjectRoots()` method, which contained logic for properly resolving the _actual_ project root as well as resolving symlinks within that root, has been moved to `local-cli/utils/Config.js`, to match the fact that other default  rn-cli.config.js definitions live there.
Closes https://github.com/facebook/react-native/pull/14412

Differential Revision: D5216887

Pulled By: hramos

fbshipit-source-id: 7a3840ecf0ad8ea3f6d7bbd3d54e4f02950c6a32
2017-06-09 13:13:21 -07:00
Hector Ramos 522f4a5c6a Restore proper ordering of docs in the sidebar
Summary:
Quickfix: The ordering here was lost when a previous PR was merged.
Closes https://github.com/facebook/react-native/pull/14378

Differential Revision: D5203833

Pulled By: hramos

fbshipit-source-id: 9282a5a5c9aa81ae5e1f5fe6692192ac1db57c08
2017-06-07 15:34:59 -07:00
Hector Ramos c62b9f645e New Handling Touches Tutorial
Summary:
Finally, a place where `Button` is properly introduced. This is based on the old Handling Touches guide, which has been simplified (with some content moved over to the scroll views tutorial).

I've also updated the ordering of the guides into something that makes more sense to someone just getting started with React Native.
Closes https://github.com/facebook/react-native/pull/14371

Differential Revision: D5201127

Pulled By: hramos

fbshipit-source-id: 819192e2db9febb8a315f51693dae557752b6002
2017-06-07 12:18:38 -07:00
Hector Ramos a3ea9377c1 Add Components and APIs Overview Guide
Summary:
Essential components such as View, Text, and Button are easily overlooked amongst the long list of components and APIs due to a lack of categorization. The basic components are already introduced as part of the tutorial, but they may be missed by people who prefer scanning over the docs.

Built website on localhost. Preview of the website as seem on Chrome on macOS:

![screencapture-localhost-8079-react-native-docs-components-and-apis-html-1496357491473](https://cloud.githubusercontent.com/assets/165856/26704237/902d0986-46e2-11e7-9624-17db692ae11e.png)

Preview as seen on an iPhone Plus (via Chrome console):
![screen shot 2017-06-01 at 3 57 00 pm](https://cloud.githubusercontent.com/assets/165856/26704309/05c8ff7e-46e3-11e7-99ff-b7402f5265d4.png)
Closes https://github.com/facebook/react-native/pull/14265

Differential Revision: D5192597

Pulled By: hramos

fbshipit-source-id: f281a14230468458f3da674a82df263fb9f064f4
2017-06-07 12:18:31 -07:00
James Ide a98a51325e [0.46.0-rc.1] Bump version numbers 2017-06-07 12:11:26 -07:00
Christoph Pojer 335d56ec55 Remove react-native/packager folder.
Summary: This folder is not necessary any longer. All the code now lives in https://github.com/facebook/metro-bundler

Reviewed By: davidaurelio, jeanlauliac

Differential Revision: D5199196

fbshipit-source-id: 35bf0f10a9163f53426db9a76f8f853dceb69167
2017-06-07 12:10:08 -07:00
Mike Grabowski ee7e4ab1a3 [0.46.0-rc.0] Bump version numbers 2017-06-07 13:37:25 +02:00
2698 changed files with 13352 additions and 216610 deletions
+1 -9
View File
@@ -3,12 +3,4 @@
**/staticBundle.js
**/main.js
Libraries/vendor/**/*
Libraries/Renderer/*
website/node_modules
pr-inactivity-bookmarklet.js
question-bookmarklet.js
flow/
website/core/metadata.js
website/core/metadata-blog.js
website/src/react-native/docs/
website/src/react-native/blog/
packager/src/worker-farm/**/*
+25 -17
View File
@@ -1,6 +1,4 @@
{
"root": true,
"parser": "babel-eslint",
"ecmaFeatures": {
@@ -13,8 +11,6 @@
},
"plugins": [
"flowtype",
"prettier",
"react"
],
@@ -53,17 +49,33 @@
"setTimeout": false,
"window": false,
"XMLHttpRequest": false,
"pit": false
"pit": false,
// Flow global types.
"ReactComponent": false,
"ReactClass": false,
"ReactElement": false,
"ReactPropsCheckType": false,
"ReactPropsChainableTypeChecker": false,
"ReactPropTypes": false,
"SyntheticEvent": false,
"$Either": false,
"$All": false,
"$ArrayBufferView": false,
"$Tuple": false,
"$Supertype": false,
"$Subtype": false,
"$Shape": false,
"$Diff": false,
"$Keys": false,
"$Enum": false,
"$Exports": false,
"$FlowIssue": false,
"$FlowFixMe": false,
"$FixMe": false
},
"rules": {
// Flow Plugin
// The following rules are made available via `eslint-plugin-flowtype`
"flowtype/define-flow-type": 1,
"flowtype/use-flow-type": 1,
// General
"comma-dangle": 0, // disallow trailing commas in object literals
"no-cond-assign": 1, // disallow assignment in conditional expressions
"no-console": 0, // disallow use of console (off by default in the node environment)
@@ -164,10 +176,6 @@
"no-restricted-modules": 1, // restrict usage of specified node modules (off by default)
"no-sync": 0, // disallow use of synchronous methods (off by default)
// Prettier Plugin
// https://github.com/prettier/eslint-plugin-prettier
"prettier/prettier": [2, "fb", "@format"],
// Stylistic Issues
// These rules are purely matters of style and are quite subjective.
@@ -233,6 +241,6 @@
"react/prop-types": 0,
"react/react-in-jsx-scope": 1,
"react/self-closing-comp": 1,
"react/wrap-multilines": 0
"react/wrap-multilines": 0,
}
}
+3 -3
View File
@@ -38,12 +38,12 @@ suppress_type=$FlowIssue
suppress_type=$FlowFixMe
suppress_type=$FixMe
suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(4[0-9]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native_oss[a-z,_]*\\)?)\\)
suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(4[0-9]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native_oss[a-z,_]*\\)?)\\)?:? #[0-9]+
suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(4[0-7]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native_oss[a-z,_]*\\)?)\\)
suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(4[0-7]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native_oss[a-z,_]*\\)?)\\)?:? #[0-9]+
suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError
unsafe.enable_getters_and_setters=true
[version]
^0.49.1
^0.47.0
-9
View File
@@ -1,9 +0,0 @@
docs/* @hramos
blog/* @hramos
Libraries/Animated/* @janicduplessis
Libraries/NativeAnimation/* @janicduplessis
ReactAndroid/src/main/java/com/facebook/react/animated/* @janicduplessis
website/* @hramos
website/showcase.json @hramos
package.json @hramos @ericnakagawa
website/package.json @hramos @ericnakagawa
+7 -7
View File
@@ -16,20 +16,20 @@
If you answered "No":
We use GitHub Issues exclusively for tracking bugs in React Native. If you're looking for help,
check out the How to Get In Touch section of the following guide:
https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md#how-to-get-in-touch
check out the How to Get In Touch section of the following guide:
https://facebook.github.io/react-native/docs/contributing.html#how-to-get-in-touch
Now scroll below!
-->
### Have you read the Bugs section of the Contributing to React Native Guide?
### Have you read the Bugs section of the How to Contribute guide?
(Write your answer here.)
<!--
Please read through the bug reporting guidelines thoroughly:
https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md#bugs
https://facebook.github.io/react-native/docs/contributing.html#bugs
-->
### Environment
@@ -41,15 +41,15 @@
1. `react-native -v`:
2. `node -v`:
3. `npm -v`:
4. `yarn --version` (if you use Yarn):
4. `yarn --version`<!-- (if you use Yarn) -->:
Then, specify:
<!-- (What platform are you building for? Choose any from iOS, Android, AppleTV.) -->
- Target Platform:
- Target Platform:
<!-- Which operating system are you using? Specify macOS, Windows, or Linux, along with specific release versions -->
- Development Operating System:
- Development Operating System:
<!-- Include any additional relevant information. Are you using Xcode or Android Studio to build native code? Is the issue specific to a particular iOS or Android SDK? -->
- Build tools:
+29 -6
View File
@@ -1,9 +1,32 @@
<!--
Thank you for sending the PR!
Thanks for submitting a PR! Please read these instructions carefully:
If you changed any code, please provide us with clear instructions on how you verified your changes work. In other words, a test plan is *required*. Bonus points for screenshots and videos!
- [ ] Explain the **motivation** for making this change.
- [ ] Provide a **test plan** demonstrating that the code is solid.
- [ ] Match the **code formatting** of the rest of the codebase.
- [ ] Target the `master` branch, NOT a "stable" branch.
Please read the Contribution Guidelines at https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md to learn more about contributing to React Native.
## Motivation (required)
Happy contributing!
-->
What existing problem does the pull request solve?
## Test Plan (required)
A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI or updates the website. See [What is a Test Plan?][1] to learn more.
If you have added code that should be tested, add tests.
## Next Steps
Sign the [CLA][2], if you haven't already.
Small pull requests are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it.
Make sure all **tests pass** on both [Travis][3] and [Circle CI][4]. PRs that break tests are unlikely to be merged.
For more info, see the ["Pull Requests"][5] section of our "Contributing" guidelines.
[1]: https://medium.com/@martinkonicek/what-is-a-test-plan-8bfc840ec171#.y9lcuqqi9
[2]: https://code.facebook.com/cla
[3]: https://travis-ci.org/facebook/react-native
[4]: http://circleci.com/gh/facebook/react-native
[5]: https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md#pull-requests
-3
View File
@@ -57,6 +57,3 @@ node_modules
/coverage
/third-party
/website/src
/website/build
+15 -9
View File
@@ -3,20 +3,25 @@ language: objective-c
osx_image: xcode8.3
install:
- nvm install 7
- mkdir -p /Users/travis/build/facebook/.nvm
- export NVM_DIR="/Users/travis/build/facebook/.nvm"
- brew install nvm
- source $(brew --prefix nvm)/nvm.sh
# TODO npm 2 started stalling on Travis, t11852928
# Use node 6 because that is what runs on land-blocking tests
- nvm install 6
- rm -Rf "${TMPDIR}/jest_preprocess_cache"
- brew install yarn --ignore-dependencies
- yarn install
- wget https://github.com/yarnpkg/yarn/releases/download/v0.16.0/yarn-0.16.0.js
- export yarn="node $(pwd)/yarn-0.16.0.js"
- $yarn install
script:
- if [[ "$TEST_TYPE" = objc-ios ]]; then travis_retry travis_wait 30 ./scripts/objc-test-ios.sh test; fi
- if [[ "$TEST_TYPE" = objc-tvos ]]; then travis_retry travis_wait 30 ./scripts/objc-test-tvos.sh; fi
- if [[ "$TEST_TYPE" = objc-ios ]]; then travis_retry travis_wait ./scripts/objc-test-ios.sh test; fi
- if [[ "$TEST_TYPE" = objc-tvos ]]; then travis_retry travis_wait ./scripts/objc-test-tvos.sh; fi
- if [[ "$TEST_TYPE" = e2e-objc ]]; then node ./scripts/run-ci-e2e-tests.js --ios --js --retries 3; fi
- if [[ ( "$TEST_TYPE" = podspecs ) && ( "$TRAVIS_PULL_REQUEST" = "false" ) ]]; then gem install cocoapods && travis_wait 30 ./scripts/process-podspecs.sh; fi
- if [[ ( "$TEST_TYPE" = podspecs ) && ( "$TRAVIS_PULL_REQUEST" = "false" ) ]]; then gem install cocoapods && ./scripts/process-podspecs.sh; fi
cache:
- cocoapods
- yarn
matrix:
- fast_finish: true # Fail the whole build as soon as one test type fails. Should help with Travis capacity issues (very long queues).
@@ -36,6 +41,7 @@ branches:
notifications:
email:
recipients:
- mkonicek@fb.com
- douglowder@mac.com # Doug Lowder built and maintains Apple TV specific code and wants to be notified about tvOS failures.
- eloy@artsy.net # Eloy Durán maintains the podspecs test and wants to be notified about failures.
on_failure: change
-14
View File
@@ -1,14 +0,0 @@
{
// Use IntelliSense to learn about possible Node.js debug attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceRoot}/Libraries/react-native/react-native-implementation.js"
}
]
}
+80 -56
View File
@@ -1,16 +1,48 @@
# Contributing to React Native
React Native is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody on https://facebook.com. We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully this document makes the process for contributing clear and preempts some questions you may have.
<!-- generated_contributing_start -->
React Native is one of Facebook's first open source projects that is both under very active development and is also being used to ship code to everybody using Facebook's mobile apps. If you're interested in contributing to React Native, hopefully this document makes the process for contributing clear.
## Code of Conduct
Core contributors to React Native meet monthly and post their meeting notes on the [React Native blog](https://facebook.github.io/react-native/blog). You can also find ad hoc discussions in the [React Native Core Contributors](https://www.facebook.com/groups/reactnativeoss/) Facebook group.
## [Code of Conduct](https://code.facebook.com/codeofconduct)
Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) so that you can understand what actions will and will not be tolerated.
## Our Development Process
## How to contribute
There are many ways to contribute to React Native, and many of them do not involve writing any code. Here's a few ideas to get started:
* Simply start using React Native. Go through the [Getting Started](http://facebook.github.io/react-native/docs/getting-started.html) guide. Does everything work as expected? If not, we're always looking for improvements. Let us know by [opening an issue](http://facebook.github.io/react-native/docs/contributing.html#reporting-new-issues).
* Look through the [open issues](https://github.com/facebook/react-native/issues). Provide workarounds, ask for clarification, or suggest labels. Help [triage issues](http://facebook.github.io/react-native/docs/contributing.html#triaging-issues-and-pull-requests).
* If you find an issue you would like to fix, [open a pull request](http://facebook.github.io/react-native/docs/contributing.html#your-first-pull-request). Issues tagged as [`Good First Task`](https://github.com/facebook/react-native/labels/Good%20First%20Task) are a good place to get started.
* Read through the [React Native docs](http://facebook.github.io/react-native/docs). If you find anything that is confusing or can be improved, you can make edits by clicking "Improve this page" at the bottom of most docs.
* Browse [Stack Overflow](https://stackoverflow.com/questions/tagged/react-native) and answer questions. This will help you get familiarized with common pitfalls or misunderstandings, which can be useful when contributing updates to the documentation.
* Take a look at the [features requested](https://react-native.canny.io/feature-requests) by others in the community and consider opening a pull request if you see something you want to work on.
Contributions are very welcome. If you think you need help planning your contribution, please hop into [#react-native](https://discord.gg/0ZcbPKXt5bZjGY5n) and let people know you're looking for a mentor.
### Triaging issues and pull requests
One great way you can contribute to the project without writing any code is to help triage issues and pull requests as they come in.
* Ask for more information if the issue does not provide all the details required by the template.
* Suggest [labels](https://github.com/facebook/react-native/labels) that can help categorize issues.
* Flag issues that are stale or that should be closed.
* Ask for test plans and review code.
Adding labels, closing and reopening issues, and merging pull requests is, as you may expect, limited to a subset of contributors. Simply commenting on the issue or pull request can still go a long way towards helping us keep the number of outstanding issues under control.
Once you have become an active contributor in the community, you may gain access to the Facebook GitHub Bot, allowing you to perform some of these operations yourself. You can learn more about the bot in the [maintainer's guide](docs/maintainers.html#facebook-github-bot).
## Our development process
Some of the core team will be working directly on [GitHub](https://github.com/facebook/react-native). These changes will be public from the beginning. Other changesets will come via a bridge with Facebook's internal source control. This is a necessity as it allows engineers at Facebook outside of the core team to move fast and contribute from an environment they are comfortable in.
## Branch Organization
When a change made on GitHub is approved, it will first be imported into Facebook's internal source control. The change will eventually sync back to GitHub as a single commit once it has passed all internal tests.
### Branch organization
We will do our best to keep `master` in good shape, with tests passing at all times. But in order to move fast, we will make API changes that your application might not be compatible with. We will do our best to [communicate these changes](https://github.com/facebook/react-native/releases) and version appropriately so you can lock into a specific version if need be.
@@ -18,69 +50,61 @@ To see what changes are coming and provide better feedback to React Native contr
## Bugs
#### Where to Find Known Issues
We use [GitHub Issues](https://github.com/facebook/react-native/issues) for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you a are certain this is a new, unreported bug, you can submit a [bug report](http://facebook.github.io/react-native/docs/contributing.html#reporting-new-issues).
We are using [GitHub Issues](https://github.com/facebook/react-native/issues) for our public bugs. Before filing a new task, try to make sure your problem doesn't already exist.
If you have questions about using React Native, the [help page](http://facebook.github.io/react-native/support.html) list various resources that should help you get started.
Questions and feature requests are tracked elsewhere:
We also have a [place where you can request features or enhancements](https://react-native.canny.io/feature-requests). If you see anything you'd like to be implemented, vote it up and explain your use case.
- Have a question? [Ask on Stack Overflow](http://stackoverflow.com/questions/tagged/react-native).
- If you have a question regarding future plans, check out the [roadmap](https://github.com/facebook/react-native/wiki/Roadmap).
- Have a feature request that is not covered in the roadmap? [Add it here](https://react-native.canny.io/feature-requests).
## Reporting new issues
#### Reporting New Issues
When [opening a new issue](https://github.com/facebook/react-native/issues/new), always make sure to fill out the [issue template](https://raw.githubusercontent.com/facebook/react-native/master/.github/ISSUE_TEMPLATE.md). **This step is very important!** Not doing so may result in your issue getting closed. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template.
The best way to get your bug fixed is to provide a reduced test case. Please provide either a [Sketch](https://sketch.expo.io/) or a public repository with a runnable example.
* **One issue, one bug:** Please report a single bug per issue.
* **Provide a Snack:** The best way to get attention on your issue is to provide a reduced test case. You can use [Snack](https://snack.expo.io/) to demonstrate the issue.
* **Provide reproduction steps:** List all the steps necessary to reproduce the issue. Provide a Snack or upload a sample project to GitHub. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort.
* **Try out the latest version:** Verify that the issue can be reproduced locally by updating your project to use [React Native from `master`](http://facebook.github.io/react-native/versions.html). The bug may have already been fixed!
Please report a single bug per issue. Always provide reproduction steps. You can use Snack in many cases to demonstrate an issue: https://snack.expo.io/. If the bug cannot be reproduced using Snack, verify that the issue can be reproduced locally by targeting the latest release candidate. Ideally, check if the issue is present in master as well.
We're not able to provide support through GitHub Issues. If you're looking for help with your code, consider asking on [Stack Overflow](http://stackoverflow.com/questions/tagged/react-native) or reaching out to the community through [other channels](https://facebook.github.io/react-native/support.html).
Do not forget to include sample code that reproduces the issue. Only open issues for bugs affecting either the latest stable release, or the current release candidate, or master (see http://facebook.github.io/react-native/versions.html). If it is not clear from your report that the issue can be reproduced in one of these releases, your issue will be closed.
We're not able to provide support through GitHub Issues. If you're looking for help with your code, consider asking on Stack Overflow: http://stackoverflow.com/questions/tagged/react-native
#### Security Bugs
### Security bugs
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. With that in mind, please do not file public issues; go through the process outlined on that page.
## How to Get in Touch
## Pull requests
Many React Native users are active on [Stack Overflow](http://stackoverflow.com/questions/tagged/react-native).
### Your first pull request
If you want to get a general sense of what React Native folks talk about, check out the [React Native Community](https://www.facebook.com/groups/react.native.community) Facebook group.
So you have decided to contribute code back to upstream by opening a pull request. You've invested a good chunk of time, and we appreciate it. We will do our best to work with you and get the PR looked at.
There is also [an active community of React and React Native users on the Discord chat platform](https://discord.gg/0ZcbPKXt5bZjGY5n) in case you need help.
Working on your first Pull Request? You can learn how from this free video series:
The React Native team sends out periodical updates through the following channels:
[**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
* [Blog](https://facebook.github.io/react-native/blog/)
* [Twitter](https://www.twitter.com/reactnative)
We have a list of [beginner friendly issues](https://github.com/facebook/react-native/labels/Good%20First%20Task) to help you get your feet wet in the React Native codebase and familiar with our contribution process. This is a great place to get started.
Core contributors to React Native meet monthly and post their meeting notes on the React Native blog. You can also find ad hoc discussions in the [React Native Core Contributors](https://www.facebook.com/groups/reactnativeoss/) Facebook group.
### Proposing a change
## Proposing a Change
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, we have a [place to track feature requests](https://react-native.canny.io/feature-requests).
If you intend to change the public API, or make any non-trivial changes to the implementation, we recommend [filing an issue](https://github.com/facebook/react-native/issues/new). This lets us reach an agreement on your proposal before you put significant effort into it.
If you're only fixing a bug, it's fine to submit a pull request right away but we still recommend to file an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
## Pull Requests
If you send a pull request, please do it against the master branch. We maintain stable branches for stable releases separately but we don't accept pull requests to them directly. Instead, we cherry-pick non-breaking changes from master to the latest stable version.
The core team will be monitoring for pull requests. When we get one, we'll run some Facebook-specific integration tests on it first. From here, we'll need to get another person to sign off on the changes and then merge the pull request. For API changes we may need to fix internal uses, which could cause some delay. We'll do our best to provide updates and feedback throughout the process.
### Sending a pull request
Small pull requests are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it.
*Before* submitting a pull request, please make sure the following is done
**Before submitting a pull request**, please make sure the following is done:
1. Fork the repo and create your branch from `master`.
1. Fork [the repository](https://github.com/facebook/react-native) and create your branch from `master`.
2. Add the copyright notice to the top of any new files you've added.
3. Describe your **test plan** in your commit.
4. Ensure **tests pass** on Travis and Circle CI.
5. Make sure your code lints (`node linter.js <files touched>`).
6. If you haven't already, sign the CLA: https://code.facebook.com/cla
7. Squash your commits (`git rebase -i`).
One intent alongside one commit makes it clearer for people to review and easier to understand your intention.
3. Describe your [**test plan**](https://facebook.github.io/react-native/docs/contributing.html#test-plan) in your commit.
4. Ensure [**tests pass**](https://facebook.github.io/react-native/docs/contributing.html#contrinuous-integration-tests) on both Travis and Circle CI.
5. Make sure your code lints (`npm run lint`).
6. If you haven't already, [sign the CLA](https://code.facebook.com/cla).
All pull requests should be opened against the `master` branch.
> **Note:** It is not necessary to keep clicking `Merge master to your branch` on the PR page. You would want to merge master if there are conflicts or tests are failing. The Facebook-GitHub-Bot ultimately squashes all commits to a single one before merging your PR.
@@ -88,18 +112,15 @@ Small pull requests are much easier to review and more likely to get merged. Mak
A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI or updates the website.
- If you've added code that should be tested, add tests!
- If you've changed APIs, update the documentation.
- If you've updated the docs, verify the website locally and submit screenshots if applicable (see `website/README.md`)
* If you've added code that should be tested, add tests!
* If you've changed APIs, update the documentation.
* If you've updated the docs, verify the website locally and submit screenshots if applicable (see [website/README.md](https://github.com/facebook/react-native/blob/master/website/README.md))
See "What is a Test Plan?" to learn more:
https://medium.com/@martinkonicek/what-is-a-test-plan-8bfc840ec171#.y9lcuqqi9
See [What is a Test Plan?](https://medium.com/@martinkonicek/what-is-a-test-plan-8bfc840ec171#.y9lcuqqi9) to learn more.
#### Continuous integration tests
Make sure all **tests pass** on both [Travis][travis] and [Circle CI][circle]. PRs that break tests are unlikely to be merged.
You can learn more about running tests and contributing to React Native here: https://facebook.github.io/react-native/docs/testing.html
Make sure all **tests pass** on both [Travis][travis] and [Circle CI][circle]. PRs that break tests are unlikely to be merged. Learn more about [testing your changes here](https://facebook.github.io/react-native/docs/testing.html).
[travis]: https://travis-ci.org/facebook/react-native
[circle]: http://circleci.com/gh/facebook/react-native
@@ -111,10 +132,10 @@ When adding a new breaking change, follow this template in your pull request:
```
### New breaking change here
- **Who does this affect**:
- **How to migrate**:
- **Why make this breaking change**:
- **Severity (number of people affected x effort)**:
* **Who does this affect**:
* **How to migrate**:
* **Why make this breaking change**:
* **Severity (number of people affected x effort)**:
```
If your pull request is merged, a core contributor will update the [list of breaking changes](https://github.com/facebook/react-native/wiki/Breaking-Changes) which is then used to populate the release notes.
@@ -136,15 +157,17 @@ Copy and paste this to the top of your new file(s):
If you've added a new module, add a `@providesModule <moduleName>` at the end of the comment. This will allow the haste package manager to find it.
### Contributor License Agreement (CLA)
#### Contributor License Agreement (CLA)
In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, just let us know that you have completed the CLA and we can cross-check with your GitHub username.
In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, the Facebook GitHub Bot will reply with a link to the CLA form. You may also [complete your CLA here](https://code.facebook.com/cla).
Complete your CLA here: https://code.facebook.com/cla
### What happens next?
The core team will be monitoring for pull requests. Read [what to expect from maintainers](https://facebook.github.io/react-native/docs/maintainers.html#handling-pull-requests) to understand what may happen after you open a pull request.
## Style Guide
Our linter will catch most styling issues that may exist in your code. You can check the status of your code styling by simply running `node linter.js <files touched>`.
Our linter will catch most styling issues that may exist in your code. You can check the status of your code styling by simply running `npm run lint`.
However, there are still some styles that the linter cannot pick up.
@@ -194,3 +217,4 @@ However, there are still some styles that the linter cannot pick up.
## License
By contributing to React Native, you agree that your contributions will be licensed under its BSD license.
<!-- generated_contributing_end -->
+1
View File
@@ -3,6 +3,7 @@ FROM containership/android-base:latest
# set default environment variables
ENV GRADLE_OPTS="-Dorg.gradle.jvmargs=\"-Xmx512m -XX:+HeapDumpOnOutOfMemoryError\""
ENV JAVA_TOOL_OPTIONS="-Dfile.encoding=UTF8"
ENV REACT_NATIVE_MAX_WORKERS=1
# add ReactAndroid directory
ADD .buckconfig /app/.buckconfig
+1 -1
View File
@@ -1,6 +1,6 @@
FROM library/node:6.9.2
ENV YARN_VERSION=0.27.5
ENV YARN_VERSION=0.19.1
# install dependencies
RUN apt-get update && apt-get install ocaml libelf-dev -y
+3 -2
View File
@@ -17,6 +17,7 @@ AVD_UUID=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)
ANDROID_NPM_DEPS="appium@1.5.1 mocha@2.4.5 wd@0.3.11 colors@1.0.3 pretty-data2@0.40.1"
CLI_PACKAGE=$ROOT/react-native-cli/react-native-cli-*.tgz
PACKAGE=$ROOT/react-native-*.tgz
REACT_NATIVE_MAX_WORKERS=1
# solve issue with max user watches limit
echo 65536 | tee -a /proc/sys/fs/inotify/max_user_watches
@@ -230,13 +231,13 @@ function e2e_suite() {
# js tests
if [ $RUN_JS -ne 0 ]; then
# Check the packager produces a bundle (doesn't throw an error)
react-native bundle --max-workers 1 --platform android --dev true --entry-file index.android.js --bundle-output android-bundle.js
REACT_NATIVE_MAX_WORKERS=1 react-native bundle --platform android --dev true --entry-file index.android.js --bundle-output android-bundle.js
if [ $? -ne 0 ]; then
echo "Could not build android bundle"
return 1
fi
react-native bundle --max-workers 1 --platform ios --dev true --entry-file index.ios.js --bundle-output ios-bundle.js
REACT_NATIVE_MAX_WORKERS=1 react-native bundle --platform ios --dev true --entry-file index.ios.js --bundle-output ios-bundle.js
if [ $? -ne 0 ]; then
echo "Could not build iOS bundle"
return 1
@@ -1,52 +0,0 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @providesModule AccessibilityManagerTest
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const { View } = ReactNative;
const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
const {
TestModule,
AccessibilityManager,
} = ReactNative.NativeModules;
class AccessibilityManagerTest extends React.Component {
componentDidMount() {
AccessibilityManager.setAccessibilityContentSizeMultipliers({
'extraSmall': 1.0,
'small': 2.0,
'medium': 3.0,
'large': 4.0,
'extraLarge': 5.0,
'extraExtraLarge': 6.0,
'extraExtraExtraLarge': 7.0,
'accessibilityMedium': 8.0,
'accessibilityLarge': 9.0,
'accessibilityExtraLarge': 10.0,
'accessibilityExtraExtraLarge': 11.0,
'accessibilityExtraExtraExtraLarge': 12.0,
});
RCTDeviceEventEmitter.addListener('didUpdateDimensions', update => {
TestModule.markTestPassed(update.window.fontScale === 4.0);
});
}
render(): React.Element<any> {
return <View />;
}
}
AccessibilityManagerTest.displayName = 'AccessibilityManagerTest';
module.exports = AccessibilityManagerTest;
-1
View File
@@ -35,7 +35,6 @@ var TESTS = [
require('./PromiseTest'),
require('./SyncMethodTest'),
require('./WebSocketTest'),
require('./AccessibilityManagerTest'),
];
TESTS.forEach(
+2 -3
View File
@@ -392,7 +392,7 @@ class Shape extends React.Component {
render() {
var props = this.props;
var path = props.d || childrenAsString(props.children);
var d = (path instanceof Path ? path : new Path(path)).toJSON();
var d = new Path(path).toJSON();
return (
<NativeShape
fill={extractBrush(props.fill, props)}
@@ -486,8 +486,7 @@ function extractAlignment(alignment) {
class Text extends React.Component {
render() {
var props = this.props;
var path = props.path;
var textPath = path ? (path instanceof Path ? path : new Path(path)).toJSON() : null;
var textPath = props.path ? new Path(props.path).toJSON() : null;
var textFrame = extractFontAndLines(
props.font,
childrenAsString(props.children)
@@ -2825,9 +2825,9 @@ module.exports = {
*
*```javascript
* onScroll={Animated.event(
* [{nativeEvent: {contentOffset: {x: this._scrollX}}}],
* [{nativeEvent: {contentOffset: {x: this._scrollX}}}]
* {listener}, // Optional async listener
* )}
* )
* ...
* onPanResponderMove: Animated.event([
* null, // raw event arg ignored
@@ -8,6 +8,8 @@
*/
'use strict';
jest.disableAutomock();
var Animated = require('Animated');
describe('Animated tests', () => {
beforeEach(() => {
@@ -9,6 +9,7 @@
'use strict';
jest
.disableAutomock()
.setMock('Text', {})
.setMock('View', {})
.setMock('Image', {})
@@ -8,6 +8,8 @@
*/
'use strict';
jest.unmock('Easing');
var Easing = require('Easing');
describe('Easing', () => {
it('should work with linear', () => {
@@ -8,6 +8,11 @@
*/
'use strict';
jest
.unmock('Interpolation')
.unmock('Easing')
.unmock('normalizeColor');
var Interpolation = require('Interpolation');
var Easing = require('Easing');
@@ -10,6 +10,7 @@
'use strict';
jest.unmock('bezier');
var bezier = require('bezier');
var identity = function (x) { return x; };
+6 -12
View File
@@ -15,6 +15,7 @@
'use strict';
const ErrorUtils = require('ErrorUtils');
const JSTimersExecution = require('JSTimersExecution');
const Systrace = require('Systrace');
const deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
@@ -40,9 +41,6 @@ const TRACE_TAG_REACT_APPS = 1 << 17;
const DEBUG_INFO_LIMIT = 32;
// Work around an initialization order issue
let JSTimers = null;
class MessageQueue {
_lazyCallableModules: {[key: string]: void => Object};
_queue: [Array<number>, Array<number>, Array<any>, number];
@@ -153,9 +151,8 @@ class MessageQueue {
};
}
getCallableModule(name: string) {
const getValue = this._lazyCallableModules[name];
return getValue ? getValue() : null;
_getCallableModule(name: string) {
return this._lazyCallableModules[name]();
}
enqueueNativeCall(moduleID: number, methodID: number, params: Array<any>, onFail: ?Function, onSucc: ?Function) {
@@ -237,11 +234,8 @@ class MessageQueue {
}
__callImmediates() {
Systrace.beginEvent('JSTimers.callImmediates()');
if (!JSTimers) {
JSTimers = require('JSTimers');
}
JSTimers.callImmediates();
Systrace.beginEvent('JSTimersExecution.callImmediates()');
JSTimersExecution.callImmediates();
Systrace.endEvent();
}
@@ -252,7 +246,7 @@ class MessageQueue {
if (this.__spy) {
this.__spy({ type: TO_JS, module, method, args});
}
const moduleMethods = this.getCallableModule(module);
const moduleMethods = this._getCallableModule(module);
invariant(
!!moduleMethods,
'Module %s is not a registered callable module (calling %s)',
+4 -6
View File
@@ -15,8 +15,6 @@ const BatchedBridge = require('BatchedBridge');
const invariant = require('fbjs/lib/invariant');
import type {ExtendedError} from 'parseErrorStack';
type ModuleConfig = [
string, /* name */
?Object, /* constants */
@@ -115,13 +113,13 @@ function arrayContains<T>(array: Array<T>, value: T): boolean {
return array.indexOf(value) !== -1;
}
function createErrorFromErrorData(errorData: {message: string}): ExtendedError {
function createErrorFromErrorData(errorData: {message: string}): Error {
const {
message,
...extraErrorInfo
} = errorData || {};
const error : ExtendedError = new Error(message);
error.framesToPop = 1;
} = errorData;
const error = new Error(message);
(error:any).framesToPop = 1;
return Object.assign(error, extraErrorInfo);
}
@@ -9,6 +9,10 @@
*/
'use strict';
// const MessageQueueTestConfig = require('MessageQueueTestConfig');
jest.unmock('MessageQueue');
jest.unmock('defineLazyObjectProperty');
let MessageQueue;
let MessageQueueTestModule;
let queue;
@@ -80,34 +84,4 @@ describe('MessageQueue', function() {
queue.__invokeCallback(1);
expect(() => queue.__invokeCallback(0)).toThrow();
});
it('should throw when calling with unknown module', () => {
const unknownModule = 'UnknownModule', unknownMethod = 'UnknownMethod';
expect(() => queue.__callFunction(unknownModule, unknownMethod)).toThrow(
`Module ${unknownModule} is not a registered callable module (calling ${unknownMethod})`,
);
});
it('should return lazily registered module', () => {
const dummyModule = {}, name = 'modulesName';
queue.registerLazyCallableModule(name, () => dummyModule);
expect(queue.getCallableModule(name)).toEqual(dummyModule);
});
it('should not initialize lazily registered module before it was used for the first time', () => {
const dummyModule = {}, name = 'modulesName';
const factory = jest.fn(() => dummyModule);
queue.registerLazyCallableModule(name, factory);
expect(factory).not.toHaveBeenCalled();
});
it('should initialize lazily registered module only once', () => {
const dummyModule = {}, name = 'modulesName';
const factory = jest.fn(() => dummyModule);
queue.registerLazyCallableModule(name, factory);
queue.getCallableModule(name);
queue.getCallableModule(name);
expect(factory).toHaveBeenCalledTimes(1);
});
});
@@ -9,12 +9,10 @@
*/
'use strict';
jest
.enableAutomock()
.unmock('BatchedBridge')
.unmock('defineLazyObjectProperty')
.unmock('MessageQueue')
.unmock('NativeModules');
jest.unmock('BatchedBridge');
jest.unmock('defineLazyObjectProperty');
jest.unmock('MessageQueue');
jest.unmock('NativeModules');
let BatchedBridge;
let NativeModules;
+19 -14
View File
@@ -97,25 +97,25 @@ class Button extends React.Component {
} = this.props;
const buttonStyles = [styles.button];
const textStyles = [styles.text];
if (color) {
if (Platform.OS === 'ios') {
textStyles.push({color: color});
} else {
buttonStyles.push({backgroundColor: color});
}
const Touchable = Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity;
if (color && Platform.OS === 'ios') {
textStyles.push({color: color});
} else if (color) {
buttonStyles.push({backgroundColor: color});
}
const accessibilityTraits = ['button'];
if (disabled) {
buttonStyles.push(styles.buttonDisabled);
textStyles.push(styles.textDisabled);
accessibilityTraits.push('disabled');
}
invariant(
typeof title === 'string',
'The title prop of a Button must be a string',
);
const formattedTitle = Platform.OS === 'android' ? title.toUpperCase() : title;
const Touchable = Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity;
const accessibilityTraits = ['button'];
if (disabled) {
accessibilityTraits.push('disabled');
}
return (
<Touchable
accessibilityComponentType="button"
@@ -132,27 +132,32 @@ class Button extends React.Component {
}
}
// Material design blue from https://material.google.com/style/color.html#color-color-palette
let defaultBlue = '#2196F3';
if (Platform.OS === 'ios') {
// Measured default tintColor from iOS 10
defaultBlue = '#0C42FD';
}
const styles = StyleSheet.create({
button: Platform.select({
ios: {},
android: {
elevation: 4,
// Material design blue from https://material.google.com/style/color.html#color-color-palette
backgroundColor: '#2196F3',
backgroundColor: defaultBlue,
borderRadius: 2,
},
}),
text: Platform.select({
ios: {
// iOS blue from https://developer.apple.com/ios/human-interface-guidelines/visual-design/color/
color: '#007AFF',
color: defaultBlue,
textAlign: 'center',
padding: 8,
fontSize: 18,
},
android: {
color: 'white',
textAlign: 'center',
color: 'white',
padding: 8,
fontWeight: '500',
},
+1 -3
View File
@@ -100,9 +100,7 @@ let Keyboard = {
* - `keyboardDidChangeFrame`
*
* Note that if you set `android:windowSoftInputMode` to `adjustResize` or `adjustNothing`,
* only `keyboardDidShow` and `keyboardDidHide` events will be available on Android.
* `keyboardWillShow` as well as `keyboardWillHide` are generally not available on Android
* since there is no native corresponding event.
* only `keyboardDidShow` and `keyboardDidHide` events will available on Android.
*
* @param {function} callback function to be called when the event fires.
*/
@@ -22,8 +22,13 @@ const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
import type EmitterSubscription from 'EmitterSubscription';
import type {ViewLayout, ViewLayoutEvent} from 'ViewPropTypes';
type Rect = {
x: number,
y: number,
width: number,
height: number,
};
type ScreenRect = {
screenX: number,
screenY: number,
@@ -36,6 +41,11 @@ type KeyboardChangeEvent = {
duration?: number,
easing?: string,
};
type LayoutEvent = {
nativeEvent: {
layout: Rect,
}
};
const viewRef = 'VIEW';
@@ -77,7 +87,7 @@ const KeyboardAvoidingView = createReactClass({
},
subscriptions: ([]: Array<EmitterSubscription>),
frame: (null: ?ViewLayout),
frame: (null: ?Rect),
relativeKeyboardHeight(keyboardFrame: ScreenRect): number {
const frame = this.frame;
@@ -113,7 +123,7 @@ const KeyboardAvoidingView = createReactClass({
this.setState({bottom: height});
},
onLayout(event: ViewLayoutEvent) {
onLayout(event: LayoutEvent) {
this.frame = event.nativeEvent.layout;
},
@@ -1,110 +0,0 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule MaskedViewIOS
* @flow
*/
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const requireNativeComponent = require('requireNativeComponent');
const ReactPropTypes = React.PropTypes;
import type { ViewProps } from 'ViewPropTypes';
type Props = ViewProps & {
children: any,
/**
* Should be a React element to be rendered and applied as the
* mask for the child element.
*/
maskElement: React.Element<*>,
};
/**
* Renders the child view with a mask specified in the `maskElement` prop.
*
* ```
* import React from 'react';
* import { MaskedView, Text, View } from 'react-native';
*
* class MyMaskedView extends React.Component {
* render() {
* return (
* <MaskedView
* style={{ flex: 1 }}
* maskElement={
* <View style={styles.maskContainerStyle}>
* <Text style={styles.maskTextStyle}>
* Basic Mask
* </Text>
* </View>
* }
* >
* <View style={{ flex: 1, backgroundColor: 'blue' }} />
* </MaskedView>
* );
* }
* }
* ```
*
* The above example will render a view with a blue background that fills its
* parent, and then mask that view with text that says "Basic Mask".
*
* The alpha channel of the view rendered by the `maskElement` prop determines how
* much of the view's content and background shows through. Fully or partially
* opaque pixels allow the underlying content to show through but fully
* transparent pixels block that content.
*
*/
class MaskedViewIOS extends React.Component {
props: Props;
static propTypes = {
...ViewPropTypes,
maskElement: ReactPropTypes.element.isRequired,
};
_hasWarnedInvalidRenderMask = false;
render() {
const { maskElement, children, ...otherViewProps } = this.props;
if (!React.isValidElement(maskElement)) {
if (!this._hasWarnedInvalidRenderMask) {
console.warn(
'MaskedView: Invalid `maskElement` prop was passed to MaskedView. ' +
'Expected a React Element. No mask will render.'
);
this._hasWarnedInvalidRenderMask = true;
}
return <View {...otherViewProps}>{children}</View>;
}
return (
<RCTMaskedView {...otherViewProps}>
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
{maskElement}
</View>
{children}
</RCTMaskedView>
);
}
}
const RCTMaskedView = requireNativeComponent('RCTMaskedView', {
name: 'RCTMaskedView',
displayName: 'RCTMaskedView',
propTypes: {
...ViewPropTypes,
},
});
module.exports = MaskedViewIOS;
@@ -436,7 +436,7 @@ var NavigatorIOS = createReactClass({
titleTextColor: PropTypes.string,
/**
* Boolean value that indicates whether the navigation bar is
* Bboolean value that indicates whether the navigation bar is
* translucent.
*/
translucent: PropTypes.bool,
+5 -36
View File
@@ -33,9 +33,6 @@ const flattenStyle = require('flattenStyle');
const invariant = require('fbjs/lib/invariant');
const processDecelerationRate = require('processDecelerationRate');
const requireNativeComponent = require('requireNativeComponent');
const warning = require('fbjs/lib/warning');
import type {NativeMethodsMixinType} from 'ReactNativeTypes';
/**
* Component that wraps platform ScrollView while providing
@@ -259,8 +256,6 @@ const ScrollView = createReactClass({
* When true, the scroll view stops on multiples of the scroll view's size
* when scrolling. This can be used for horizontal pagination. The default
* value is false.
*
* Note: Vertical pagination is not supported on Android.
*/
pagingEnabled: PropTypes.bool,
/**
@@ -318,10 +313,8 @@ const ScrollView = createReactClass({
/**
* When set, causes the scroll view to stop at multiples of the value of
* `snapToInterval`. This can be used for paginating through children
* that have lengths smaller than the scroll view. Typically used in
* combination with `snapToAlignment` and `decelerationRate="fast"`.
* Overrides less configurable `pagingEnabled` prop.
*
* that have lengths smaller than the scroll view. Used in combination
* with `snapToAlignment`.
* @platform ios
*/
snapToInterval: PropTypes.number,
@@ -397,15 +390,6 @@ const ScrollView = createReactClass({
'always',
'never',
]),
/**
* When true, ScrollView will emit updateChildFrames data in scroll events,
* otherwise will not compute or emit child frame data. This only exists
* to support legacy issues, `onLayout` should be used instead to retrieve
* frame data.
* The default value is false.
* @platform ios
*/
DEPRECATED_sendUpdatedChildFrames: PropTypes.bool,
},
mixins: [ScrollResponder.Mixin],
@@ -601,8 +585,8 @@ const ScrollView = createReactClass({
this._scrollViewRef = ref;
},
_innerViewRef: (null: ?NativeMethodsMixinType),
_setInnerViewRef: function(ref: ?NativeMethodsMixinType) {
_innerViewRef: (null: ?View),
_setInnerViewRef: function(ref: ?View) {
this._innerViewRef = ref;
},
@@ -612,10 +596,6 @@ const ScrollView = createReactClass({
if (Platform.OS === 'ios') {
ScrollViewClass = RCTScrollView;
ScrollContentContainerViewClass = RCTScrollContentView;
warning(
!this.props.snapToInterval || !this.props.pagingEnabled,
'snapToInterval is currently ignored when pagingEnabled is true.'
);
} else if (Platform.OS === 'android') {
if (this.props.horizontal) {
ScrollViewClass = AndroidHorizontalScrollView;
@@ -689,13 +669,7 @@ const ScrollView = createReactClass({
{...contentSizeChangeProps}
ref={this._setInnerViewRef}
style={contentContainerStyle}
removeClippedSubviews={
// Subview clipping causes issues with sticky headers on Android and
// would be hard to fix properly in a performant way.
Platform.OS === 'android' && hasStickyHeaders ?
false :
this.props.removeClippedSubviews
}
removeClippedSubviews={this.props.removeClippedSubviews}
collapsable={false}>
{children}
</ScrollContentContainerViewClass>;
@@ -710,9 +684,6 @@ const ScrollView = createReactClass({
this.props.alwaysBounceVertical :
!this.props.horizontal;
const DEPRECATED_sendUpdatedChildFrames =
!!this.props.DEPRECATED_sendUpdatedChildFrames;
const baseStyle = this.props.horizontal ? styles.baseHorizontal : styles.baseVertical;
const props = {
...this.props,
@@ -741,7 +712,6 @@ const ScrollView = createReactClass({
scrollEventThrottle: hasStickyHeaders ? 1 : this.props.scrollEventThrottle,
sendMomentumEvents: (this.props.onMomentumScrollBegin || this.props.onMomentumScrollEnd) ?
true : false,
DEPRECATED_sendUpdatedChildFrames,
};
const { decelerationRate } = this.props;
@@ -838,7 +808,6 @@ if (Platform.OS === 'android') {
(ScrollView: ReactClass<any>),
nativeOnlyProps,
);
// $FlowFixMe (bvaughn) Update ComponentInterface in ViewPropTypes to include a string type (for Fiber host components) in a follow-up.
RCTScrollContentView = requireNativeComponent('RCTScrollContentView', View);
}
+35 -56
View File
@@ -63,10 +63,7 @@ type DefaultProps = {
/**
* Merges the prop stack with the default values.
*/
function mergePropsStack(
propsStack: Array<Object>,
defaultValues: Object
): Object {
function mergePropsStack(propsStack: Array<Object>, defaultValues: Object): Object {
return propsStack.reduce((prev, cur) => {
for (const prop in cur) {
if (cur[prop] != null) {
@@ -83,29 +80,20 @@ function mergePropsStack(
*/
function createStackEntry(props: any): any {
return {
backgroundColor:
props.backgroundColor != null
? {
value: props.backgroundColor,
animated: props.animated,
}
: null,
barStyle:
props.barStyle != null
? {
value: props.barStyle,
animated: props.animated,
}
: null,
backgroundColor: props.backgroundColor != null ? {
value: props.backgroundColor,
animated: props.animated,
} : null,
barStyle: props.barStyle != null ? {
value: props.barStyle,
animated: props.animated,
} : null,
translucent: props.translucent,
hidden:
props.hidden != null
? {
value: props.hidden,
animated: props.animated,
transition: props.showHideTransition,
}
: null,
hidden: props.hidden != null ? {
value: props.hidden,
animated: props.animated,
transition: props.showHideTransition,
} : null,
networkActivityIndicatorVisible: props.networkActivityIndicatorVisible,
};
}
@@ -153,7 +141,7 @@ class StatusBar extends React.Component {
props: {
hidden?: boolean,
animated?: boolean,
backgroundColor?: string,
backgroundColor?: $FlowFixMe,
translucent?: boolean,
barStyle?: 'default' | 'light-content' | 'dark-content',
networkActivityIndicatorVisible?: boolean,
@@ -227,9 +215,7 @@ class StatusBar extends React.Component {
*/
static setNetworkActivityIndicatorVisible(visible: boolean) {
if (Platform.OS !== 'ios') {
console.warn(
'`setNetworkActivityIndicatorVisible` is only available on iOS'
);
console.warn('`setNetworkActivityIndicatorVisible` is only available on iOS');
return;
}
StatusBar._defaultProps.networkActivityIndicatorVisible = visible;
@@ -290,7 +276,11 @@ class StatusBar extends React.Component {
/**
* Sets the color of the status bar text.
*/
barStyle: PropTypes.oneOf(['default', 'light-content', 'dark-content']),
barStyle: PropTypes.oneOf([
'default',
'light-content',
'dark-content',
]),
/**
* If the network activity indicator should be visible.
*
@@ -303,7 +293,10 @@ class StatusBar extends React.Component {
*
* @platform ios
*/
showHideTransition: PropTypes.oneOf(['fade', 'slide']),
showHideTransition: PropTypes.oneOf([
'fade',
'slide',
]),
};
static defaultProps = {
@@ -350,52 +343,38 @@ class StatusBar extends React.Component {
clearImmediate(StatusBar._updateImmediate);
StatusBar._updateImmediate = setImmediate(() => {
const oldProps = StatusBar._currentValues;
const mergedProps = mergePropsStack(
StatusBar._propsStack,
StatusBar._defaultProps
);
const mergedProps = mergePropsStack(StatusBar._propsStack, StatusBar._defaultProps);
// Update the props that have changed using the merged values from the props stack.
if (Platform.OS === 'ios') {
if (
!oldProps ||
oldProps.barStyle.value !== mergedProps.barStyle.value
) {
if (!oldProps || oldProps.barStyle.value !== mergedProps.barStyle.value) {
StatusBarManager.setStyle(
mergedProps.barStyle.value,
mergedProps.barStyle.animated
mergedProps.barStyle.animated,
);
}
if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
StatusBarManager.setHidden(
mergedProps.hidden.value,
mergedProps.hidden.animated ? mergedProps.hidden.transition : 'none'
mergedProps.hidden.animated ?
mergedProps.hidden.transition :
'none',
);
}
if (
!oldProps ||
oldProps.networkActivityIndicatorVisible !==
mergedProps.networkActivityIndicatorVisible
) {
if (!oldProps || oldProps.networkActivityIndicatorVisible !== mergedProps.networkActivityIndicatorVisible) {
StatusBarManager.setNetworkActivityIndicatorVisible(
mergedProps.networkActivityIndicatorVisible
);
}
} else if (Platform.OS === 'android') {
if (
!oldProps ||
oldProps.barStyle.value !== mergedProps.barStyle.value
) {
if (!oldProps || oldProps.barStyle.value !== mergedProps.barStyle.value) {
StatusBarManager.setStyle(mergedProps.barStyle.value);
}
if (
!oldProps ||
oldProps.backgroundColor.value !== mergedProps.backgroundColor.value
) {
if (!oldProps || oldProps.backgroundColor.value !== mergedProps.backgroundColor.value) {
StatusBarManager.setColor(
processColor(mergedProps.backgroundColor.value),
mergedProps.backgroundColor.animated
mergedProps.backgroundColor.animated,
);
}
if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
@@ -53,7 +53,7 @@ var TextInputState = {
},
/**
* @param {number} textFieldID id of the text field to unfocus
* @param {number} textFieldID id of the text field to focus
* Unfocuses the specified text field
* noop if it wasn't focused
*/
@@ -7,36 +7,38 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule TouchableHighlight
* @flow
* @noflow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
// Note (avik): add @flow when Flow supports spread properties in propTypes
var ColorPropType = require('ColorPropType');
var NativeMethodsMixin = require('NativeMethodsMixin');
const PropTypes = require('prop-types');
const React = require('React');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheet = require('StyleSheet');
const TimerMixin = require('react-timer-mixin');
const Touchable = require('Touchable');
const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
const View = require('View');
var React = require('React');
var ReactNativeViewAttributes = require('ReactNativeViewAttributes');
var StyleSheet = require('StyleSheet');
var TimerMixin = require('react-timer-mixin');
var Touchable = require('Touchable');
var TouchableWithoutFeedback = require('TouchableWithoutFeedback');
var View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const ensureComponentIsNative = require('ensureComponentIsNative');
const ensurePositiveDelayProps = require('ensurePositiveDelayProps');
const keyOf = require('fbjs/lib/keyOf');
const merge = require('merge');
var createReactClass = require('create-react-class');
var ensureComponentIsNative = require('ensureComponentIsNative');
var ensurePositiveDelayProps = require('ensurePositiveDelayProps');
var keyOf = require('fbjs/lib/keyOf');
var merge = require('merge');
import type {Event} from 'TouchableWithoutFeedback';
type Event = Object;
const DEFAULT_PROPS = {
var DEFAULT_PROPS = {
activeOpacity: 0.85,
underlayColor: 'black',
};
const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
var PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
/**
* A wrapper for making views respond properly to touches.
@@ -108,6 +110,7 @@ var TouchableHighlight = createReactClass({
* @platform ios
*/
tvParallaxProperties: PropTypes.object,
},
mixins: [NativeMethodsMixin, TimerMixin, Touchable.Mixin],
@@ -26,7 +26,7 @@ const {
AccessibilityTraits,
} = require('ViewAccessibility');
export type Event = Object;
type Event = Object;
const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
@@ -37,6 +37,7 @@ const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
* TouchableWithoutFeedback supports only one child.
* If you wish to have several child components, wrap them in a View.
*/
// $FlowFixMe(>=0.41.0)
const TouchableWithoutFeedback = createReactClass({
displayName: 'TouchableWithoutFeedback',
mixins: [TimerMixin, Touchable.Mixin],
@@ -89,7 +90,6 @@ const TouchableWithoutFeedback = createReactClass({
* reactivated! Move it back and forth several times while the scroll view
* is disabled. Ensure you pass in a constant to reduce memory allocations.
*/
// $FlowFixMe: Expected a React PropType instead
pressRetentionOffset: EdgeInsetsPropType,
/**
* This defines how far your touch can start away from the button. This is
@@ -99,7 +99,6 @@ const TouchableWithoutFeedback = createReactClass({
* of sibling views always takes precedence if a touch hits two overlapping
* views.
*/
// $FlowFixMe: Expected a React PropType instead
hitSlop: EdgeInsetsPropType,
},
@@ -8,6 +8,8 @@
*/
'use strict';
jest.disableAutomock();
const React = require('React');
const ReactTestRenderer = require('react-test-renderer');
const Text = require('Text');
+122 -29
View File
@@ -9,21 +9,32 @@
* @providesModule View
* @flow
*/
"use strict";
'use strict';
const NativeMethodsMixin = require("NativeMethodsMixin");
const Platform = require("Platform");
const PropTypes = require("prop-types");
const React = require("React");
const ReactNativeStyleAttributes = require("ReactNativeStyleAttributes");
const ReactNativeViewAttributes = require("ReactNativeViewAttributes");
const ViewPropTypes = require("ViewPropTypes");
const NativeMethodsMixin = require('NativeMethodsMixin');
const NativeModules = require('NativeModules');
const Platform = require('Platform');
const PropTypes = require('prop-types');
const React = require('React');
const ReactNativeFeatureFlags = require('ReactNativeFeatureFlags');
const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require("create-react-class");
const invariant = require("fbjs/lib/invariant");
const requireNativeComponent = require("requireNativeComponent");
const createReactClass = require('create-react-class');
const invariant = require('fbjs/lib/invariant');
const requireNativeComponent = require('requireNativeComponent');
const warning = require('fbjs/lib/warning');
import type { ViewProps } from "ViewPropTypes";
const {
AccessibilityComponentTypes,
AccessibilityTraits,
} = require('ViewAccessibility');
const forceTouchAvailable = (NativeModules.PlatformConstants &&
NativeModules.PlatformConstants.forceTouchAvailable) || false;
import type {ViewProps} from 'ViewPropTypes';
export type Props = ViewProps;
@@ -75,7 +86,7 @@ export type Props = ViewProps;
*/
// $FlowFixMe(>=0.41.0)
const View = createReactClass({
displayName: "View",
displayName: 'View',
// TODO: We should probably expose the mixins, viewConfig, and statics publicly. For example,
// one of the props is of type AccessibilityComponentType. That is defined as a const[] above,
// but it is not rendered by the docs, since `statics` below is not rendered. So its Possible
@@ -85,61 +96,143 @@ const View = createReactClass({
// `propTypes` should not be accessed directly on View since this wrapper only
// exists for DEV mode. However it's important for them to be declared.
// If the object passed to `createClass` specifies `propTypes`, Flow will
// create a static type from it.
// create a static type from it. This property will be over-written below with
// a warn-on-use getter though.
// TODO (bvaughn) Remove the warn-on-use comment after April 1.
propTypes: ViewPropTypes,
// ReactElementValidator will (temporarily) use this private accessor when
// detected to avoid triggering the warning message.
// TODO (bvaughn) Remove this after April 1 ReactNative RC is tagged.
statics: {
__propTypesSecretDontUseThesePlease: ViewPropTypes
},
/**
* `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
* make `this` look like an actual native component class.
*/
viewConfig: {
uiViewClassName: "RCTView",
uiViewClassName: 'RCTView',
validAttributes: ReactNativeViewAttributes.RCTView
},
contextTypes: {
isInAParentText: PropTypes.bool
isInAParentText: PropTypes.bool,
},
render: function() {
invariant(
!(this.context.isInAParentText && Platform.OS === "android"),
"Nesting of <View> within <Text> is not supported on Android."
);
!(this.context.isInAParentText && Platform.OS === 'android'),
'Nesting of <View> within <Text> is not supported on Android.');
// WARNING: This method will not be used in production mode as in that mode we
// replace wrapper component View with generated native wrapper RCTView. Avoid
// adding functionality this component that you'd want to be available in both
// dev and prod modes.
return <RCTView {...this.props} />;
}
},
});
const RCTView = requireNativeComponent("RCTView", View, {
// Warn about unsupported use of View static properties as these will no longer
// be supported with React fiber. This warning message will go away in the next
// ReactNative release. Use defineProperty() rather than createClass() statics
// because the mixin process auto-triggers the 1-time warning message.
// TODO (bvaughn) Remove this after April 1 ReactNative RC is tagged.
function mixinStatics (target) {
let warnedAboutAccessibilityTraits = false;
let warnedAboutAccessibilityComponentType = false;
let warnedAboutForceTouchAvailable = false;
let warnedAboutPropTypes = false;
// $FlowFixMe https://github.com/facebook/flow/issues/285
Object.defineProperty(target, 'AccessibilityTraits', {
get: function() {
warning(
warnedAboutAccessibilityTraits,
'View.AccessibilityTraits has been deprecated and will be ' +
'removed in a future version of ReactNative. Use ' +
'ViewAccessibility.AccessibilityTraits instead.'
);
warnedAboutAccessibilityTraits = true;
return AccessibilityTraits;
}
});
// $FlowFixMe https://github.com/facebook/flow/issues/285
Object.defineProperty(target, 'AccessibilityComponentType', {
get: function() {
warning(
warnedAboutAccessibilityComponentType,
'View.AccessibilityComponentType has been deprecated and will be ' +
'removed in a future version of ReactNative. Use ' +
'ViewAccessibility.AccessibilityComponentTypes instead.'
);
warnedAboutAccessibilityComponentType = true;
return AccessibilityComponentTypes;
}
});
// $FlowFixMe https://github.com/facebook/flow/issues/285
Object.defineProperty(target, 'forceTouchAvailable', {
get: function() {
warning(
warnedAboutForceTouchAvailable,
'View.forceTouchAvailable has been deprecated and will be removed ' +
'in a future version of ReactNative. Use ' +
'NativeModules.PlatformConstants.forceTouchAvailable instead.'
);
warnedAboutForceTouchAvailable = true;
return forceTouchAvailable;
}
});
// $FlowFixMe https://github.com/facebook/flow/issues/285
Object.defineProperty(target, 'propTypes', {
get: function() {
warning(
warnedAboutPropTypes,
'View.propTypes has been deprecated and will be removed in a future ' +
'version of ReactNative. Use ViewPropTypes instead.'
);
warnedAboutPropTypes = true;
return ViewPropTypes;
}
});
}
const RCTView = requireNativeComponent('RCTView', View, {
nativeOnly: {
nativeBackgroundAndroid: true,
nativeForegroundAndroid: true
nativeForegroundAndroid: true,
}
});
if (__DEV__) {
const UIManager = require("UIManager");
const viewConfig =
(UIManager.viewConfigs && UIManager.viewConfigs.RCTView) || {};
const UIManager = require('UIManager');
const viewConfig = UIManager.viewConfigs && UIManager.viewConfigs.RCTView || {};
for (const prop in viewConfig.nativeProps) {
const viewAny: any = View; // Appease flow
if (!viewAny.propTypes[prop] && !ReactNativeStyleAttributes[prop]) {
throw new Error(
"View is missing propType for native prop `" + prop + "`"
'View is missing propType for native prop `' + prop + '`'
);
}
}
}
// TODO (bvaughn) Remove feature flags once all static View accessors are gone.
// We temporarily wrap fiber native views with the create-class View above,
// Because external code sometimes accesses static properties of this view.
let ViewToExport = RCTView;
if (__DEV__) {
if (
__DEV__ ||
ReactNativeFeatureFlags.useFiber
) {
mixinStatics(View);
ViewToExport = View;
} else {
// TODO (bvaughn) Remove this mixin once all static View accessors are gone.
mixinStatics((RCTView : any));
}
// No one should depend on the DEV-mode createClass View wrapper.
module.exports = ((ViewToExport: any): typeof RCTView);
// TODO (bvaughn) Temporarily mask Flow warnings for View property accesses.
// We're wrapping the string type (Fiber) for now to avoid any actual problems.
module.exports = ((ViewToExport : any) : typeof View);
+2 -14
View File
@@ -36,19 +36,6 @@ import type {TVViewProps} from 'TVViewPropTypes';
const stylePropType = StyleSheetPropType(ViewStylePropTypes);
export type ViewLayout = {
x: number,
y: number,
width: number,
height: number,
}
export type ViewLayoutEvent = {
nativeEvent: {
layout: ViewLayout,
}
}
// There's no easy way to create a different type if(Platform.isTVOS):
// so we must include TVViewProps
export type ViewProps = {
@@ -63,7 +50,6 @@ export type ViewProps = {
onMagicTap?: Function,
testID?: string,
nativeID?: string,
onLayout?: (event: ViewLayoutEvent) => void,
onResponderGrant?: Function,
onResponderMove?: Function,
onResponderReject?: Function,
@@ -232,6 +218,8 @@ module.exports = {
* Used to locate this view from native classes.
*
* > This disables the 'layout-only view removal' optimization for this view!
*
* @platform android
*/
nativeID: PropTypes.string,
@@ -75,7 +75,6 @@ class ViewPagerAndroid extends React.Component {
onPageScrollStateChanged?: Function,
onPageSelected?: Function,
pageMargin?: number,
peekEnabled?: boolean,
keyboardDismissMode?: 'none' | 'on-drag',
scrollEnabled?: boolean,
};
@@ -138,12 +137,6 @@ class ViewPagerAndroid extends React.Component {
* The default value is true.
*/
scrollEnabled: PropTypes.bool,
/**
* Whether enable showing peekFraction or not. If this is true, the preview of
* last and next page will show in current screen. Defaults to false.
*/
peekEnabled: PropTypes.bool,
};
componentDidMount() {
@@ -367,10 +367,6 @@ class WebView extends React.Component {
]),
};
static defaultProps = {
scalesPageToFit: true,
};
state = {
viewState: WebViewState.IDLE,
lastErrorEvent: (null: ?ErrorEvent),
@@ -9,6 +9,8 @@
'use strict';
jest.disableAutomock();
var parseErrorStack = require('parseErrorStack');
function getFakeError() {
+5 -7
View File
@@ -18,22 +18,20 @@ export type StackFrame = {
methodName: string,
};
export type ExtendedError = Error & {
framesToPop?: number,
};
var stacktraceParser = require('stacktrace-parser');
function parseErrorStack(e: ExtendedError): Array<StackFrame> {
function parseErrorStack(e: Error): Array<StackFrame> {
if (!e || !e.stack) {
return [];
}
const stacktraceParser = require('stacktrace-parser');
const stack = Array.isArray(e.stack) ? e.stack : stacktraceParser.parse(e.stack);
var stack = Array.isArray(e.stack) ? e.stack : stacktraceParser.parse(e.stack);
let framesToPop = typeof e.framesToPop === 'number' ? e.framesToPop : 0;
var framesToPop = typeof e.framesToPop === 'number' ? e.framesToPop : 0;
while (framesToPop--) {
stack.shift();
}
return stack;
}
+2 -4
View File
@@ -11,13 +11,11 @@
*/
'use strict';
import type {ExtendedError} from 'parseErrorStack';
/**
* Handles the developer-visible aspect of errors and exceptions
*/
let exceptionID = 0;
function reportException(e: ExtendedError, isFatal: bool) {
function reportException(e: Error, isFatal: bool) {
const {ExceptionsManager} = require('NativeModules');
if (ExceptionsManager) {
const parseErrorStack = require('parseErrorStack');
@@ -86,7 +84,7 @@ function reactConsoleErrorHandler() {
// (Note: Logic duplicated in polyfills/console.js.)
return;
}
const error : ExtendedError = new Error('console.error: ' + str);
const error : any = new Error('console.error: ' + str);
error.framesToPop = 1;
reportException(error, /* isFatal */ false);
}
+58 -52
View File
@@ -13,6 +13,7 @@
/* eslint-disable strict */
/* globals window: true */
/**
* Sets up global variables typical in most JavaScript environments.
*
@@ -95,21 +96,28 @@ if (!global.process.env.NODE_ENV) {
global.process.env.NODE_ENV = __DEV__ ? 'development' : 'production';
}
// Setup the Systrace profiling hooks if necessary
if (global.__RCTProfileIsProfiling) {
const Systrace = require('Systrace');
Systrace.setEnabled(true);
}
if (__DEV__ && global.performance === undefined) {
const Systrace = require('Systrace');
global.performance = Systrace.getUserTimingPolyfill();
}
// Set up profile
const Systrace = require('Systrace');
Systrace.setEnabled(global.__RCTProfileIsProfiling || false);
// Set up console
const ExceptionsManager = require('ExceptionsManager');
ExceptionsManager.installConsoleErrorReporter();
// TODO: Move these around to solve the cycle in a cleaner way
const BatchedBridge = require('BatchedBridge');
BatchedBridge.registerLazyCallableModule('Systrace', () => require('Systrace'));
BatchedBridge.registerLazyCallableModule('JSTimersExecution', () => require('JSTimersExecution'));
BatchedBridge.registerLazyCallableModule('HeapCapture', () => require('HeapCapture'));
BatchedBridge.registerLazyCallableModule('SamplingProfiler', () => require('SamplingProfiler'));
BatchedBridge.registerLazyCallableModule('RCTLog', () => require('RCTLog'));
if (__DEV__) {
if (!global.__RCTProfileIsProfiling) {
BatchedBridge.registerCallableModule('HMRClient', require('HMRClient'));
}
}
// Set up error handler
if (!global.__fbDisableExceptionsManager) {
const handleError = (e, isFatal) => {
@@ -127,26 +135,6 @@ if (!global.__fbDisableExceptionsManager) {
ErrorUtils.setGlobalHandler(handleError);
}
// Set up collections
// We can't make these lazy because `Map` checks for `global.Map` (which wouldc
// not exist if it were lazily defined).
defineProperty(global, 'Map', () => require('Map'), true);
defineProperty(global, 'Set', () => require('Set'), true);
// Set up Promise
// The native Promise implementation throws the following error:
// ERROR: Event loop not supported.
defineProperty(global, 'Promise', () => require('Promise'));
// Set up regenerator.
defineProperty(global, 'regeneratorRuntime', () => {
// The require just sets up the global, so make sure when we first
// invoke it the global does not exist
delete global.regeneratorRuntime;
require('regenerator-runtime/runtime');
return global.regeneratorRuntime;
});
// Set up timers
const defineLazyTimer = name => {
defineProperty(global, name, () => require('JSTimers')[name]);
@@ -162,6 +150,29 @@ defineLazyTimer('cancelAnimationFrame');
defineLazyTimer('requestIdleCallback');
defineLazyTimer('cancelIdleCallback');
// Set up alert
if (!global.alert) {
global.alert = function(text) {
// Require Alert on demand. Requiring it too early can lead to issues
// with things like Platform not being fully initialized.
require('Alert').alert('Alert', '' + text);
};
}
// Set up Promise
// The native Promise implementation throws the following error:
// ERROR: Event loop not supported.
defineProperty(global, 'Promise', () => require('Promise'));
// Set up regenerator.
defineProperty(global, 'regeneratorRuntime', () => {
// The require just sets up the global, so make sure when we first
// invoke it the global does not exist
delete global.regeneratorRuntime;
require('regenerator-runtime/runtime');
return global.regeneratorRuntime;
});
// Set up XHR
// The native XMLHttpRequest in Chrome dev tools is CORS aware and won't
// let you fetch anything from the internet
@@ -174,15 +185,6 @@ defineProperty(global, 'Request', () => require('fetch').Request);
defineProperty(global, 'Response', () => require('fetch').Response);
defineProperty(global, 'WebSocket', () => require('WebSocket'));
// Set up alert
if (!global.alert) {
global.alert = function(text) {
// Require Alert on demand. Requiring it too early can lead to issues
// with things like Platform not being fully initialized.
require('Alert').alert('Alert', '' + text);
};
}
// Set up Geolocation
let navigator = global.navigator;
if (navigator === undefined) {
@@ -193,31 +195,35 @@ if (navigator === undefined) {
defineProperty(navigator, 'product', () => 'ReactNative', true);
defineProperty(navigator, 'geolocation', () => require('Geolocation'));
// Just to make sure the JS gets packaged up. Wait until the JS environment has
// been initialized before requiring them.
const BatchedBridge = require('BatchedBridge');
BatchedBridge.registerLazyCallableModule('Systrace', () => require('Systrace'));
BatchedBridge.registerLazyCallableModule('JSTimers', () => require('JSTimers'));
BatchedBridge.registerLazyCallableModule('HeapCapture', () => require('HeapCapture'));
BatchedBridge.registerLazyCallableModule('SamplingProfiler', () => require('SamplingProfiler'));
BatchedBridge.registerLazyCallableModule('RCTLog', () => require('RCTLog'));
BatchedBridge.registerLazyCallableModule('RCTDeviceEventEmitter', () => require('RCTDeviceEventEmitter'));
BatchedBridge.registerLazyCallableModule('RCTNativeAppEventEmitter', () => require('RCTNativeAppEventEmitter'));
BatchedBridge.registerLazyCallableModule('PerformanceLogger', () => require('PerformanceLogger'));
// Set up collections
// We can't make these lazy because `Map` checks for `global.Map` (which wouldc
// not exist if it were lazily defined).
defineProperty(global, 'Map', () => require('Map'), true);
defineProperty(global, 'Set', () => require('Set'), true);
// Set up devtools
if (__DEV__) {
if (!global.__RCTProfileIsProfiling) {
BatchedBridge.registerCallableModule('HMRClient', require('HMRClient'));
// not when debugging in chrome
// TODO(t12832058) This check is broken
if (!window.document) {
require('setupDevtools');
}
require('RCTDebugComponentOwnership');
// In order to use Cmd+P to record/dump perf data, we need to make sure
// this module is available in the bundle
require('RCTRenderingPerf');
// Set up inspector
const JSInspector = require('JSInspector');
JSInspector.registerAgent(require('NetworkAgent'));
}
}
// Just to make sure the JS gets packaged up. Wait until the JS environment has
// been initialized before requiring them.
BatchedBridge.registerLazyCallableModule('RCTDeviceEventEmitter', () => require('RCTDeviceEventEmitter'));
BatchedBridge.registerLazyCallableModule('RCTNativeAppEventEmitter', () => require('RCTNativeAppEventEmitter'));
BatchedBridge.registerLazyCallableModule('PerformanceLogger', () => require('PerformanceLogger'));
+84 -351
View File
@@ -7,39 +7,64 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule JSTimers
* @format
* @flow
*/
'use strict';
// Note that the module JSTimers is split into two in order to solve a cycle
// in dependencies. NativeModules > BatchedBridge > MessageQueue > JSTimersExecution
const JSTimersExecution = require('JSTimersExecution');
const Platform = require('Platform');
const Systrace = require('Systrace');
const invariant = require('fbjs/lib/invariant');
const performanceNow = require('fbjs/lib/performanceNow');
const warning = require('fbjs/lib/warning');
const {Timing} = require('NativeModules');
const performanceNow = require('fbjs/lib/performanceNow');
import type {ExtendedError} from 'parseErrorStack';
import type {JSTimerType} from 'JSTimersExecution';
/**
* JS implementation of timer functions. Must be completely driven by an
* external clock signal, all that's stored here is timerID, timer type, and
* callback.
*/
// Returns a free index if one is available, and the next consecutive index otherwise.
function _getFreeIndex(): number {
let freeIndex = JSTimersExecution.timerIDs.indexOf(null);
if (freeIndex === -1) {
freeIndex = JSTimersExecution.timerIDs.length;
}
return freeIndex;
}
export type JSTimerType =
| 'setTimeout'
| 'setInterval'
| 'requestAnimationFrame'
| 'setImmediate'
| 'requestIdleCallback';
function _allocateCallback(func: Function, type: JSTimerType): number {
const id = JSTimersExecution.GUID++;
const freeIndex = _getFreeIndex();
JSTimersExecution.timerIDs[freeIndex] = id;
JSTimersExecution.callbacks[freeIndex] = func;
JSTimersExecution.types[freeIndex] = type;
if (__DEV__) {
const parseErrorStack = require('parseErrorStack');
const e = (new Error() : any);
e.framesToPop = 1;
const stack = parseErrorStack(e);
if (stack) {
JSTimersExecution.identifiers[freeIndex] = stack.shift();
}
}
return id;
}
// These timing contants should be kept in sync with the ones in native ios and
// android `RCTTiming` module.
const FRAME_DURATION = 1000 / 60;
const IDLE_CALLBACK_FRAME_DEADLINE = 1;
function _freeCallback(timerID: number) {
// JSTimersExecution.timerIDs contains nulls after timers have been removed;
// ignore nulls upfront so indexOf doesn't find them
if (timerID == null) {
return;
}
const index = JSTimersExecution.timerIDs.indexOf(timerID);
// See corresponding comment in `callTimers` for reasoning behind this
if (index !== -1) {
JSTimersExecution._clearIndex(index);
const type = JSTimersExecution.types[index];
if (type !== 'setImmediate' && type !== 'requestIdleCallback') {
Timing.deleteTimer(timerID);
}
}
}
const MAX_TIMER_DURATION_MS = 60 * 1000;
const IS_ANDROID = Platform.OS === 'android';
@@ -49,152 +74,6 @@ const ANDROID_LONG_TIMER_MESSAGE =
'module awake, and timers can only be called when the app is in the foreground. ' +
'See https://github.com/facebook/react-native/issues/12981 for more info.';
// Parallel arrays
const callbacks: Array<?Function> = [];
const types: Array<?JSTimerType> = [];
const timerIDs: Array<?number> = [];
let immediates: Array<number> = [];
let requestIdleCallbacks: Array<number> = [];
const requestIdleCallbackTimeouts: {[number]: number} = {};
const identifiers: Array<null | {methodName: string}> = [];
let GUID = 1;
let errors: ?Array<Error> = null;
let hasEmittedTimeDriftWarning = false;
// Returns a free index if one is available, and the next consecutive index otherwise.
function _getFreeIndex(): number {
let freeIndex = timerIDs.indexOf(null);
if (freeIndex === -1) {
freeIndex = timerIDs.length;
}
return freeIndex;
}
function _allocateCallback(func: Function, type: JSTimerType): number {
const id = GUID++;
const freeIndex = _getFreeIndex();
timerIDs[freeIndex] = id;
callbacks[freeIndex] = func;
types[freeIndex] = type;
if (__DEV__) {
const parseErrorStack = require('parseErrorStack');
const error: ExtendedError = new Error();
error.framesToPop = 1;
const stack = parseErrorStack(error);
if (stack) {
identifiers[freeIndex] = stack.shift();
}
}
return id;
}
/**
* Calls the callback associated with the ID. Also unregister that callback
* if it was a one time timer (setTimeout), and not unregister it if it was
* recurring (setInterval).
*/
function _callTimer(timerID: number, frameTime: number, didTimeout: ?boolean) {
warning(
timerID <= GUID,
'Tried to call timer with ID %s but no such timer exists.',
timerID,
);
// timerIndex of -1 means that no timer with that ID exists. There are
// two situations when this happens, when a garbage timer ID was given
// and when a previously existing timer was deleted before this callback
// fired. In both cases we want to ignore the timer id, but in the former
// case we warn as well.
const timerIndex = timerIDs.indexOf(timerID);
if (timerIndex === -1) {
return;
}
const type = types[timerIndex];
const callback = callbacks[timerIndex];
if (!callback || !type) {
console.error('No callback found for timerID ' + timerID);
return;
}
if (__DEV__) {
const identifier = identifiers[timerIndex] || {};
Systrace.beginEvent('Systrace.callTimer: ' + identifier.methodName);
}
// Clear the metadata
if (
type === 'setTimeout' ||
type === 'setImmediate' ||
type === 'requestAnimationFrame' ||
type === 'requestIdleCallback'
) {
_clearIndex(timerIndex);
}
try {
if (
type === 'setTimeout' ||
type === 'setInterval' ||
type === 'setImmediate'
) {
callback();
} else if (type === 'requestAnimationFrame') {
callback(performanceNow());
} else if (type === 'requestIdleCallback') {
callback({
timeRemaining: function() {
// TODO: Optimisation: allow running for longer than one frame if
// there are no pending JS calls on the bridge from native. This
// would require a way to check the bridge queue synchronously.
return Math.max(0, FRAME_DURATION - (performanceNow() - frameTime));
},
didTimeout: !!didTimeout,
});
} else {
console.error('Tried to call a callback with invalid type: ' + type);
}
} catch (e) {
// Don't rethrow so that we can run all timers.
if (!errors) {
errors = [e];
} else {
errors.push(e);
}
}
if (__DEV__) {
Systrace.endEvent();
}
}
function _clearIndex(i: number) {
timerIDs[i] = null;
callbacks[i] = null;
types[i] = null;
identifiers[i] = null;
}
function _freeCallback(timerID: number) {
// timerIDs contains nulls after timers have been removed;
// ignore nulls upfront so indexOf doesn't find them
if (timerID == null) {
return;
}
const index = timerIDs.indexOf(timerID);
// See corresponding comment in `callTimers` for reasoning behind this
if (index !== -1) {
_clearIndex(index);
const type = types[index];
if (type !== 'setImmediate' && type !== 'requestIdleCallback') {
Timing.deleteTimer(timerID);
}
}
}
/**
* JS implementation of timer functions. Must be completely driven by an
* external clock signal, all that's stored here is timerID, timer type, and
@@ -205,24 +84,13 @@ const JSTimers = {
* @param {function} func Callback to be invoked after `duration` ms.
* @param {number} duration Number of milliseconds.
*/
setTimeout: function(
func: Function,
duration: number,
...args?: any
): number {
setTimeout: function(func: Function, duration: number, ...args?: any): number {
if (__DEV__ && IS_ANDROID && duration > MAX_TIMER_DURATION_MS) {
console.warn(
ANDROID_LONG_TIMER_MESSAGE +
'\n' +
'(Saw setTimeout with duration ' +
duration +
'ms)',
);
ANDROID_LONG_TIMER_MESSAGE + '\n' + '(Saw setTimeout with duration ' +
duration + 'ms)');
}
const id = _allocateCallback(
() => func.apply(undefined, args),
'setTimeout',
);
const id = _allocateCallback(() => func.apply(undefined, args), 'setTimeout');
Timing.createTimer(id, duration || 0, Date.now(), /* recurring */ false);
return id;
},
@@ -231,24 +99,13 @@ const JSTimers = {
* @param {function} func Callback to be invoked every `duration` ms.
* @param {number} duration Number of milliseconds.
*/
setInterval: function(
func: Function,
duration: number,
...args?: any
): number {
setInterval: function(func: Function, duration: number, ...args?: any): number {
if (__DEV__ && IS_ANDROID && duration > MAX_TIMER_DURATION_MS) {
console.warn(
ANDROID_LONG_TIMER_MESSAGE +
'\n' +
'(Saw setInterval with duration ' +
duration +
'ms)',
);
ANDROID_LONG_TIMER_MESSAGE + '\n' + '(Saw setInterval with duration ' +
duration + 'ms)');
}
const id = _allocateCallback(
() => func.apply(undefined, args),
'setInterval',
);
const id = _allocateCallback(() => func.apply(undefined, args), 'setInterval');
Timing.createTimer(id, duration || 0, Date.now(), /* recurring */ true);
return id;
},
@@ -258,18 +115,15 @@ const JSTimers = {
* current JavaScript execution loop.
*/
setImmediate: function(func: Function, ...args?: any) {
const id = _allocateCallback(
() => func.apply(undefined, args),
'setImmediate',
);
immediates.push(id);
const id = _allocateCallback(() => func.apply(undefined, args), 'setImmediate');
JSTimersExecution.immediates.push(id);
return id;
},
/**
* @param {function} func Callback to be invoked every frame.
*/
requestAnimationFrame: function(func: Function) {
requestAnimationFrame: function(func : Function) {
const id = _allocateCallback(func, 'requestAnimationFrame');
Timing.createTimer(id, 1, Date.now(), /* recurring */ false);
return id;
@@ -280,58 +134,58 @@ const JSTimers = {
* with time remaining in frame.
* @param {?object} options
*/
requestIdleCallback: function(func: Function, options: ?Object) {
if (requestIdleCallbacks.length === 0) {
requestIdleCallback: function(func : Function, options : ?Object) {
if (JSTimersExecution.requestIdleCallbacks.length === 0) {
Timing.setSendIdleEvents(true);
}
const timeout = options && options.timeout;
const id = _allocateCallback(
timeout != null
? deadline => {
const timeoutId = requestIdleCallbackTimeouts[id];
if (timeoutId) {
JSTimers.clearTimeout(timeoutId);
requestIdleCallbackTimeouts[id];
}
return func(deadline);
timeout != null ?
deadline => {
const timeoutId = JSTimersExecution.requestIdleCallbackTimeouts.get(id);
if (timeoutId) {
JSTimers.clearTimeout(timeoutId);
JSTimersExecution.requestIdleCallbackTimeouts.delete(id);
}
: func,
'requestIdleCallback',
return func(deadline);
} :
func,
'requestIdleCallback'
);
requestIdleCallbacks.push(id);
JSTimersExecution.requestIdleCallbacks.push(id);
if (timeout != null) {
const timeoutId = JSTimers.setTimeout(() => {
const index = requestIdleCallbacks.indexOf(id);
const index = JSTimersExecution.requestIdleCallbacks.indexOf(id);
if (index > -1) {
requestIdleCallbacks.splice(index, 1);
_callTimer(id, performanceNow(), true);
JSTimersExecution.requestIdleCallbacks.splice(index, 1);
JSTimersExecution.callTimer(id, performanceNow(), true);
}
delete requestIdleCallbackTimeouts[id];
if (requestIdleCallbacks.length === 0) {
JSTimersExecution.requestIdleCallbackTimeouts.delete(id);
if (JSTimersExecution.requestIdleCallbacks.length === 0) {
Timing.setSendIdleEvents(false);
}
}, timeout);
requestIdleCallbackTimeouts[id] = timeoutId;
JSTimersExecution.requestIdleCallbackTimeouts.set(id, timeoutId);
}
return id;
},
cancelIdleCallback: function(timerID: number) {
_freeCallback(timerID);
const index = requestIdleCallbacks.indexOf(timerID);
const index = JSTimersExecution.requestIdleCallbacks.indexOf(timerID);
if (index !== -1) {
requestIdleCallbacks.splice(index, 1);
JSTimersExecution.requestIdleCallbacks.splice(index, 1);
}
const timeoutId = requestIdleCallbackTimeouts[timerID];
const timeoutId = JSTimersExecution.requestIdleCallbackTimeouts.get(timerID);
if (timeoutId) {
JSTimers.clearTimeout(timeoutId);
delete requestIdleCallbackTimeouts[timerID];
JSTimersExecution.requestIdleCallbackTimeouts.delete(timerID);
}
if (requestIdleCallbacks.length === 0) {
if (JSTimersExecution.requestIdleCallbacks.length === 0) {
Timing.setSendIdleEvents(false);
}
},
@@ -346,136 +200,15 @@ const JSTimers = {
clearImmediate: function(timerID: number) {
_freeCallback(timerID);
const index = immediates.indexOf(timerID);
const index = JSTimersExecution.immediates.indexOf(timerID);
if (index !== -1) {
immediates.splice(index, 1);
JSTimersExecution.immediates.splice(index, 1);
}
},
cancelAnimationFrame: function(timerID: number) {
_freeCallback(timerID);
},
/**
* This is called from the native side. We are passed an array of timerIDs,
* and
*/
callTimers: function(timersToCall: Array<number>) {
invariant(
timersToCall.length !== 0,
'Cannot call `callTimers` with an empty list of IDs.',
);
// $FlowFixMe: optionals do not allow assignment from null
errors = null;
for (let i = 0; i < timersToCall.length; i++) {
_callTimer(timersToCall[i], 0);
}
if (errors) {
const errorCount = errors.length;
if (errorCount > 1) {
// Throw all the other errors in a setTimeout, which will throw each
// error one at a time
for (let ii = 1; ii < errorCount; ii++) {
JSTimers.setTimeout(
(error => {
throw error;
}).bind(null, errors[ii]),
0,
);
}
}
throw errors[0];
}
},
callIdleCallbacks: function(frameTime: number) {
if (
FRAME_DURATION - (performanceNow() - frameTime) <
IDLE_CALLBACK_FRAME_DEADLINE
) {
return;
}
// $FlowFixMe: optionals do not allow assignment from null
errors = null;
if (requestIdleCallbacks.length > 0) {
const passIdleCallbacks = requestIdleCallbacks.slice();
requestIdleCallbacks = [];
for (let i = 0; i < passIdleCallbacks.length; ++i) {
_callTimer(passIdleCallbacks[i], frameTime);
}
}
if (requestIdleCallbacks.length === 0) {
Timing.setSendIdleEvents(false);
}
if (errors) {
errors.forEach(error =>
JSTimers.setTimeout(() => {
throw error;
}, 0),
);
}
},
/**
* Performs a single pass over the enqueued immediates. Returns whether
* more immediates are queued up (can be used as a condition a while loop).
*/
callImmediatesPass() {
if (__DEV__) {
Systrace.beginEvent('callImmediatesPass()');
}
// The main reason to extract a single pass is so that we can track
// in the system trace
if (immediates.length > 0) {
const passImmediates = immediates.slice();
immediates = [];
// Use for loop rather than forEach as per @vjeux's advice
// https://github.com/facebook/react-native/commit/c8fd9f7588ad02d2293cac7224715f4af7b0f352#commitcomment-14570051
for (let i = 0; i < passImmediates.length; ++i) {
_callTimer(passImmediates[i], 0);
}
}
if (__DEV__) {
Systrace.endEvent();
}
return immediates.length > 0;
},
/**
* This is called after we execute any command we receive from native but
* before we hand control back to native.
*/
callImmediates() {
errors = null;
while (JSTimers.callImmediatesPass()) {}
if (errors) {
errors.forEach(error =>
JSTimers.setTimeout(() => {
throw error;
}, 0),
);
}
},
/**
* Called from native (in development) when environment times are out-of-sync.
*/
emitTimeDriftWarning(warningMessage: string) {
if (hasEmittedTimeDriftWarning) {
return;
}
hasEmittedTimeDriftWarning = true;
console.warn(warningMessage);
},
};
module.exports = JSTimers;
+246
View File
@@ -0,0 +1,246 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule JSTimersExecution
* @flow
*/
'use strict';
const Systrace = require('Systrace');
const invariant = require('fbjs/lib/invariant');
const performanceNow = require('fbjs/lib/performanceNow');
const warning = require('fbjs/lib/warning');
// These timing contants should be kept in sync with the ones in native ios and
// android `RCTTiming` module.
const FRAME_DURATION = 1000 / 60;
const IDLE_CALLBACK_FRAME_DEADLINE = 1;
let hasEmittedTimeDriftWarning = false;
export type JSTimerType =
'setTimeout' |
'setInterval' |
'requestAnimationFrame' |
'setImmediate' |
'requestIdleCallback';
/**
* JS implementation of timer functions. Must be completely driven by an
* external clock signal, all that's stored here is timerID, timer type, and
* callback.
*/
const JSTimersExecution = {
GUID: 1,
// Parallel arrays
callbacks: ([] : Array<?Function>),
types: ([] : Array<?JSTimerType>),
timerIDs: ([] : Array<?number>),
immediates: [],
requestIdleCallbacks: [],
requestIdleCallbackTimeouts: (new Map() : Map<number, number>),
identifiers: ([] : Array<null | {methodName: string}>),
errors: (null : ?Array<Error>),
/**
* Calls the callback associated with the ID. Also unregister that callback
* if it was a one time timer (setTimeout), and not unregister it if it was
* recurring (setInterval).
*/
callTimer(timerID: number, frameTime: number, didTimeout: ?boolean) {
warning(
timerID <= JSTimersExecution.GUID,
'Tried to call timer with ID %s but no such timer exists.',
timerID
);
// timerIndex of -1 means that no timer with that ID exists. There are
// two situations when this happens, when a garbage timer ID was given
// and when a previously existing timer was deleted before this callback
// fired. In both cases we want to ignore the timer id, but in the former
// case we warn as well.
const timerIndex = JSTimersExecution.timerIDs.indexOf(timerID);
if (timerIndex === -1) {
return;
}
const type = JSTimersExecution.types[timerIndex];
const callback = JSTimersExecution.callbacks[timerIndex];
if (!callback || !type) {
console.error('No callback found for timerID ' + timerID);
return;
}
if (__DEV__) {
const identifier = JSTimersExecution.identifiers[timerIndex] || {};
Systrace.beginEvent('Systrace.callTimer: ' + identifier.methodName);
}
// Clear the metadata
if (type === 'setTimeout' || type === 'setImmediate' ||
type === 'requestAnimationFrame' || type === 'requestIdleCallback') {
JSTimersExecution._clearIndex(timerIndex);
}
try {
if (type === 'setTimeout' || type === 'setInterval' ||
type === 'setImmediate') {
callback();
} else if (type === 'requestAnimationFrame') {
callback(performanceNow());
} else if (type === 'requestIdleCallback') {
callback({
timeRemaining: function() {
// TODO: Optimisation: allow running for longer than one frame if
// there are no pending JS calls on the bridge from native. This
// would require a way to check the bridge queue synchronously.
return Math.max(0, FRAME_DURATION - (performanceNow() - frameTime));
},
didTimeout: !!didTimeout,
});
} else {
console.error('Tried to call a callback with invalid type: ' + type);
}
} catch (e) {
// Don't rethrow so that we can run all timers.
if (!JSTimersExecution.errors) {
JSTimersExecution.errors = [e];
} else {
JSTimersExecution.errors.push(e);
}
}
if (__DEV__) {
Systrace.endEvent();
}
},
/**
* This is called from the native side. We are passed an array of timerIDs,
* and
*/
callTimers(timerIDs: [number]) {
invariant(
timerIDs.length !== 0,
'Cannot call `callTimers` with an empty list of IDs.'
);
JSTimersExecution.errors = null;
for (let i = 0; i < timerIDs.length; i++) {
JSTimersExecution.callTimer(timerIDs[i], 0);
}
const errors = JSTimersExecution.errors;
if (errors) {
const errorCount = errors.length;
if (errorCount > 1) {
// Throw all the other errors in a setTimeout, which will throw each
// error one at a time
for (let ii = 1; ii < errorCount; ii++) {
require('JSTimers').setTimeout(
((error) => { throw error; }).bind(null, errors[ii]),
0
);
}
}
throw errors[0];
}
},
callIdleCallbacks: function(frameTime: number) {
if (FRAME_DURATION - (performanceNow() - frameTime) < IDLE_CALLBACK_FRAME_DEADLINE) {
return;
}
JSTimersExecution.errors = null;
if (JSTimersExecution.requestIdleCallbacks.length > 0) {
const passIdleCallbacks = JSTimersExecution.requestIdleCallbacks.slice();
JSTimersExecution.requestIdleCallbacks = [];
for (let i = 0; i < passIdleCallbacks.length; ++i) {
JSTimersExecution.callTimer(passIdleCallbacks[i], frameTime);
}
}
if (JSTimersExecution.requestIdleCallbacks.length === 0) {
const { Timing } = require('NativeModules');
Timing.setSendIdleEvents(false);
}
if (JSTimersExecution.errors) {
JSTimersExecution.errors.forEach((error) =>
require('JSTimers').setTimeout(() => { throw error; }, 0)
);
}
},
/**
* Performs a single pass over the enqueued immediates. Returns whether
* more immediates are queued up (can be used as a condition a while loop).
*/
callImmediatesPass() {
if (__DEV__) {
Systrace.beginEvent('JSTimersExecution.callImmediatesPass()');
}
// The main reason to extract a single pass is so that we can track
// in the system trace
if (JSTimersExecution.immediates.length > 0) {
const passImmediates = JSTimersExecution.immediates.slice();
JSTimersExecution.immediates = [];
// Use for loop rather than forEach as per @vjeux's advice
// https://github.com/facebook/react-native/commit/c8fd9f7588ad02d2293cac7224715f4af7b0f352#commitcomment-14570051
for (let i = 0; i < passImmediates.length; ++i) {
JSTimersExecution.callTimer(passImmediates[i], 0);
}
}
if (__DEV__) {
Systrace.endEvent();
}
return JSTimersExecution.immediates.length > 0;
},
/**
* This is called after we execute any command we receive from native but
* before we hand control back to native.
*/
callImmediates() {
JSTimersExecution.errors = null;
while (JSTimersExecution.callImmediatesPass()) {}
if (JSTimersExecution.errors) {
JSTimersExecution.errors.forEach((error) =>
require('JSTimers').setTimeout(() => { throw error; }, 0)
);
}
},
/**
* Called from native (in development) when environment times are out-of-sync.
*/
emitTimeDriftWarning(warningMessage: string) {
if (hasEmittedTimeDriftWarning) {
return;
}
hasEmittedTimeDriftWarning = true;
console.warn(warningMessage);
},
_clearIndex(i: number) {
JSTimersExecution.timerIDs[i] = null;
JSTimersExecution.callbacks[i] = null;
JSTimersExecution.types[i] = null;
JSTimersExecution.identifiers[i] = null;
},
};
module.exports = JSTimersExecution;
@@ -0,0 +1,41 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* Utility class to provide the component owner hierarchy to native code for
* debugging purposes.
*
* @providesModule RCTDebugComponentOwnership
* @flow
*/
'use strict';
var BatchedBridge = require('BatchedBridge');
var RCTDebugComponentOwnership = {
/**
* Asynchronously returns the owner hierarchy as an array of strings. Request id is
* passed along to the native module so that the native module can identify the
* particular call instance.
*
* Example returned owner hierarchy: ['RootView', 'Dialog', 'TitleView', 'Text']
*/
getOwnerHierarchy: function(requestID: number, tag: number) {
// Consider cleaning up these unused modules in a separate diff.
throw new Error(
'This seems to be unused. Will disable until it is needed again.'
);
},
};
BatchedBridge.registerCallableModule(
'RCTDebugComponentOwnership',
RCTDebugComponentOwnership
);
module.exports = RCTDebugComponentOwnership;
@@ -12,11 +12,12 @@
'use strict';
const Image = require('Image');
const PropTypes = require('prop-types');
const React = require('React');
const PropTypes = require('prop-types');
const Text = require('Text');
const TouchableHighlight = require('TouchableHighlight');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
import type {ImageSource} from 'ImageSource';
@@ -30,12 +31,12 @@ class SwipeableQuickActionButton extends React.Component {
props: {
accessibilityLabel?: string,
imageSource: ImageSource | number,
imageStyle?: ?ViewPropTypes.style,
imageStyle?: ?View.propTypes.style,
onPress?: Function,
style?: ?ViewPropTypes.style,
style?: ?View.propTypes.style,
testID?: string,
text?: ?(string | Object | Array<string | Object>),
textStyle?: ?ViewPropTypes.style,
textStyle?: ?View.propTypes.style,
};
static propTypes = {
@@ -72,8 +72,6 @@ const SwipeableRow = createReactClass({
propTypes: {
children: PropTypes.any,
isOpen: PropTypes.bool,
preventSwipeLeft: PropTypes.bool,
preventSwipeRight: PropTypes.bool,
maxSwipeDistance: PropTypes.number.isRequired,
onOpen: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
@@ -110,8 +108,6 @@ const SwipeableRow = createReactClass({
getDefaultProps(): Object {
return {
isOpen: false,
preventSwipeLeft: false,
preventSwipeRight: false,
maxSwipeDistance: 0,
onOpen: emptyFunction,
onClose: emptyFunction,
@@ -196,11 +192,6 @@ const SwipeableRow = createReactClass({
);
},
close(): void {
this.props.onClose();
this._animateToClosedPosition();
},
_onSwipeableViewLayout(event: Object): void {
this.setState({
isSwipeableViewRendered: true,
@@ -279,7 +270,6 @@ const SwipeableRow = createReactClass({
{
duration,
toValue,
useNativeDriver: true,
},
).start(() => {
this._previousLeft = toValue;
@@ -339,12 +329,6 @@ const SwipeableRow = createReactClass({
// Ignore swipes due to user's finger moving slightly when tapping
_isValidSwipe(gestureState: Object): boolean {
if (this.props.preventSwipeLeft && gestureState.dx < 0) {
return false;
}
if (this.props.preventSwipeRight && gestureState.dx > 0) {
return false;
}
return Math.abs(gestureState.dx) > HORIZONTAL_SWIPE_DISTANCE_THRESHOLD;
},
+1 -3
View File
@@ -27,8 +27,6 @@ const infoLog = require('infoLog');
const invariant = require('fbjs/lib/invariant');
const nullthrows = require('fbjs/lib/nullthrows');
import type {NativeMethodsMixinType} from 'ReactNativeTypes';
const DEBUG = false;
/**
@@ -615,7 +613,7 @@ type CellProps = {
};
class CellRenderer extends React.Component {
props: CellProps;
_containerRef: NativeMethodsMixinType;
_containerRef: View;
_offscreenRenderDone = false;
_timeout = 0;
_lastLayout: ?Object = null;
+1 -1
View File
@@ -175,7 +175,7 @@ var Geolocation = {
for (var ii = 0; ii < subscriptions.length; ii++) {
var sub = subscriptions[ii];
if (sub) {
warning(false, 'Called stopObserving with existing subscriptions.');
warning('Called stopObserving with existing subscriptions.');
sub[0].remove();
// array element refinements not yet enabled in Flow
var sub1 = sub[1]; sub1 && sub1.remove();
+7 -13
View File
@@ -35,10 +35,8 @@ const ImageViewManager = NativeModules.ImageViewManager;
* including network images, static resources, temporary local images, and
* images from local disk, such as the camera roll.
*
* This example shows fetching and displaying an image from local storage
* as well as one from network and even from data provided in the `'data:'` uri scheme.
*
* > Note that for network and data images, you will need to manually specify the dimensions of your image!
* This example shows both fetching and displaying an image from local
* storage as well as one from network.
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
@@ -55,10 +53,6 @@ const ImageViewManager = NativeModules.ImageViewManager;
* style={{width: 50, height: 50}}
* source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
* />
* <Image
* style={{width: 66, height: 58}}
* source={{uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg=='}}
* />
* </View>
* );
* }
@@ -110,17 +104,17 @@ const ImageViewManager = NativeModules.ImageViewManager;
* ```
* dependencies {
* // If your app supports Android versions before Ice Cream Sandwich (API level 14)
* compile 'com.facebook.fresco:animated-base-support:1.3.0'
* compile 'com.facebook.fresco:animated-base-support:1.0.1'
*
* // For animated GIF support
* compile 'com.facebook.fresco:animated-gif:1.3.0'
* compile 'com.facebook.fresco:animated-gif:1.0.1'
*
* // For WebP support, including animated WebP
* compile 'com.facebook.fresco:animated-webp:1.3.0'
* compile 'com.facebook.fresco:webpsupport:1.3.0'
* compile 'com.facebook.fresco:animated-webp:1.0.1'
* compile 'com.facebook.fresco:webpsupport:1.0.1'
*
* // For WebP support, without animations
* compile 'com.facebook.fresco:webpsupport:1.3.0'
* compile 'com.facebook.fresco:webpsupport:1.0.1'
* }
* ```
*
+6 -31
View File
@@ -14,13 +14,8 @@
const Image = require('Image');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ensureComponentIsNative = require('ensureComponentIsNative');
import type {NativeMethodsMixinType} from 'ReactNativeTypes';
/**
* Very simple drop-in replacement for <Image> which supports nesting views.
*
@@ -46,40 +41,20 @@ import type {NativeMethodsMixinType} from 'ReactNativeTypes';
* ```
*/
class ImageBackground extends React.Component {
setNativeProps(props: Object) {
// Work-around flow
const viewRef = this._viewRef;
if (viewRef) {
ensureComponentIsNative(viewRef);
viewRef.setNativeProps(props);
}
}
_viewRef: ?NativeMethodsMixinType = null;
_captureRef = ref => {
this._viewRef = ref;
};
render() {
const {children, style, imageStyle, imageRef, ...props} = this.props;
return (
<View style={style} ref={this._captureRef}>
<View style={style}>
<Image
{...props}
style={[
StyleSheet.absoluteFill,
{
// Temporary Workaround:
// Current (imperfect yet) implementation of <Image> overwrites width and height styles
// (which is not quite correct), and these styles conflict with explicitly set styles
// of <ImageBackground> and with our internal layout model here.
// So, we have to proxy/reapply these styles explicitly for actual <Image> component.
// This workaround should be removed after implementing proper support of
// intrinsic content size of the <Image>.
width: style.width,
height: style.height,
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
},
imageStyle,
]}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -12,7 +12,7 @@
'use strict';
// This is a stub for flow to make it understand require('./icon.png')
// See metro-bundler/src/Bundler/index.js
// See packager/src/Bundler/index.js
var AssetRegistry = require('AssetRegistry');
@@ -8,6 +8,12 @@
*/
'use strict';
jest
.unmock('AssetRegistry')
.unmock('AssetSourceResolver')
.unmock('../resolveAssetSource')
.unmock('../../../local-cli/bundle/assetPathUtils');
var AssetRegistry = require('AssetRegistry');
var Platform = require('Platform');
var NativeModules = require('NativeModules');
+3 -2
View File
@@ -35,10 +35,10 @@ class BoxInspector extends React.Component {
<BoxContainer title="padding" box={padding}>
<View>
<Text style={styles.innerText}>
({(frame.left || 0).toFixed(1)}, {(frame.top || 0).toFixed(1)})
({frame.left}, {frame.top})
</Text>
<Text style={styles.innerText}>
{(frame.width || 0).toFixed(1)} &times; {(frame.height || 0).toFixed(1)}
{frame.width} &times; {frame.height}
</Text>
</View>
</BoxContainer>
@@ -110,3 +110,4 @@ var styles = StyleSheet.create({
});
module.exports = BoxInspector;
+1 -1
View File
@@ -26,7 +26,7 @@ const UIManager = require('UIManager');
const View = require('View');
const emptyObject = require('fbjs/lib/emptyObject');
const invariant = require('fbjs/lib/invariant');
const invariant = require('invariant');
export type ReactRenderer = {
getInspectorDataForViewTag: (viewTag: number) => Object,
@@ -11,6 +11,7 @@
'use strict';
jest
.disableAutomock()
.mock('ErrorUtils')
.mock('BatchedBridge');
@@ -11,6 +11,7 @@
'use strict';
jest
.disableAutomock()
.mock('ErrorUtils')
.mock('BatchedBridge');
@@ -163,7 +164,6 @@ describe('promise tasks', () => {
}
beforeEach(() => {
jest.resetModules();
jest.useFakeTimers();
InteractionManager = require('InteractionManager');
BatchedBridge = require('BatchedBridge');
sequenceId = 0;
@@ -256,9 +256,7 @@ describe('promise tasks', () => {
expectToBeCalledOnce(task2);
});
const bigAsyncTest = (resolve) => {
jest.useRealTimers();
const bigAsyncTest = () => {
const task1 = createSequenceTask(1);
const task2 = jest.fn(() => {
expect(++sequenceId).toBe(2);
@@ -284,25 +282,27 @@ describe('promise tasks', () => {
InteractionManager.runAfterInteractions({gen: task2, name: 'gen2'});
InteractionManager.runAfterInteractions(task6);
setTimeout(() => {
expectToBeCalledOnce(task1);
expectToBeCalledOnce(task2);
expectToBeCalledOnce(task3);
expectToBeCalledOnce(task4);
expectToBeCalledOnce(task5);
expectToBeCalledOnce(task6);
jest.runAllTimers();
// runAllTimers doesn't actually run all timers with nested timer functions
// inside Promises, so we have to call it extra times.
jest.runAllTimers();
jest.runAllTimers();
resolve();
}, 100);
expectToBeCalledOnce(task1);
expectToBeCalledOnce(task2);
expectToBeCalledOnce(task3);
expectToBeCalledOnce(task4);
expectToBeCalledOnce(task5);
expectToBeCalledOnce(task6);
};
it('resolves async tasks recusively before other queued tasks', () => {
return new Promise(bigAsyncTest);
bigAsyncTest();
});
it('should also work with a deadline', () => {
InteractionManager.setDeadline(100);
BatchedBridge.getEventLoopRunningTime.mockReturnValue(200);
return new Promise(bigAsyncTest);
bigAsyncTest();
});
});
@@ -9,7 +9,7 @@
*/
'use strict';
jest.enableAutomock().unmock('InteractionMixin');
jest.unmock('InteractionMixin');
describe('InteractionMixin', () => {
var InteractionManager;
@@ -10,7 +10,7 @@
'use strict';
const Promise = require('promise');
jest.unmock('TaskQueue');
function expectToBeCalledOnce(fn) {
expect(fn.mock.calls.length).toBe(1);
+13 -26
View File
@@ -8,7 +8,6 @@
*
* @providesModule FillRateHelper
* @flow
* @format
*/
/* eslint-disable no-console-disallow */
@@ -57,15 +56,17 @@ class FillRateHelper {
_mostlyBlankStartTime = (null: ?number);
_samplesStartTime = (null: ?number);
static addListener(callback: FillRateInfo => void): {remove: () => void} {
static addListener(
callback: (FillRateInfo) => void
): {remove: () => void} {
warning(
_sampleRate !== null,
'Call `FillRateHelper.setSampleRate` before `addListener`.',
'Call `FillRateHelper.setSampleRate` before `addListener`.'
);
_listeners.push(callback);
return {
remove: () => {
_listeners = _listeners.filter(listener => callback !== listener);
_listeners = _listeners.filter((listener) => callback !== listener);
},
};
}
@@ -97,8 +98,7 @@ class FillRateHelper {
}
const start = this._samplesStartTime; // const for flow
if (start == null) {
DEBUG &&
console.debug('FillRateHelper: bail on deactivate with no start time');
DEBUG && console.debug('FillRateHelper: bail on deactivate with no start time');
return;
}
if (this._info.sample_count < _minSampleCount) {
@@ -115,13 +115,10 @@ class FillRateHelper {
const derived = {
avg_blankness: this._info.pixels_blank / this._info.pixels_sampled,
avg_speed: this._info.pixels_scrolled / (total_time_spent / 1000),
avg_speed_when_any_blank:
this._info.any_blank_speed_sum / this._info.any_blank_count,
any_blank_per_min:
this._info.any_blank_count / (total_time_spent / 1000 / 60),
avg_speed_when_any_blank: this._info.any_blank_speed_sum / this._info.any_blank_count,
any_blank_per_min: this._info.any_blank_count / (total_time_spent / 1000 / 60),
any_blank_time_frac: this._info.any_blank_ms / total_time_spent,
mostly_blank_per_min:
this._info.mostly_blank_count / (total_time_spent / 1000 / 60),
mostly_blank_per_min: this._info.mostly_blank_count / (total_time_spent / 1000 / 60),
mostly_blank_time_frac: this._info.mostly_blank_ms / total_time_spent,
};
for (const key in derived) {
@@ -129,7 +126,7 @@ class FillRateHelper {
}
console.debug('FillRateHelper deactivateAndFlush: ', {derived, info});
}
_listeners.forEach(listener => listener(info));
_listeners.forEach((listener) => listener(info));
this._resetData();
}
@@ -150,11 +147,7 @@ class FillRateHelper {
visibleLength: number,
},
): number {
if (
!this._enabled ||
props.getItemCount(props.data) === 0 ||
this._samplesStartTime == null
) {
if (!this._enabled || props.getItemCount(props.data) === 0 || this._samplesStartTime == null) {
return 0;
}
const {dOffset, offset, velocity, visibleLength} = scrollMetrics;
@@ -187,10 +180,7 @@ class FillRateHelper {
// Only count blankTop if we aren't rendering the first item, otherwise we will count the header
// as blank.
if (firstFrame && first > 0) {
blankTop = Math.min(
visibleLength,
Math.max(0, firstFrame.offset - offset),
);
blankTop = Math.min(visibleLength, Math.max(0, firstFrame.offset - offset));
}
let blankBottom = 0;
let last = state.last;
@@ -203,10 +193,7 @@ class FillRateHelper {
// footer as blank.
if (lastFrame && last < props.getItemCount(props.data) - 1) {
const bottomEdge = lastFrame.offset + lastFrame.length;
blankBottom = Math.min(
visibleLength,
Math.max(0, offset + visibleLength - bottomEdge),
);
blankBottom = Math.min(visibleLength, Math.max(0, offset + visibleLength - bottomEdge));
}
const pixels_blank = Math.round(blankTop + blankBottom);
const blankness = pixels_blank / visibleLength;
+23 -80
View File
@@ -8,7 +8,6 @@
*
* @providesModule FlatList
* @flow
* @format
*/
'use strict';
@@ -38,7 +37,7 @@ type RequiredProps<ItemT> = {
* onShowUnderlay={separators.highlight}
* onHideUnderlay={separators.unhighlight}>
* <View style={{backgroundColor: 'white'}}>
* <Text>{item.title}</Text>
* <Text>{item.title}}</Text>
* </View>
* </TouchableHighlight>
* )}
@@ -110,10 +109,8 @@ type OptionalProps<ItemT> = {
* Remember to include separator length (height or width) in your offset calculation if you
* specify `ItemSeparatorComponent`.
*/
getItemLayout?: (
data: ?Array<ItemT>,
index: number,
) => {length: number, offset: number, index: number},
getItemLayout?: (data: ?Array<ItemT>, index: number) =>
{length: number, offset: number, index: number},
/**
* If true, renders items next to each other horizontally instead of stacked vertically.
*/
@@ -131,10 +128,6 @@ type OptionalProps<ItemT> = {
* `getItemLayout` to be implemented.
*/
initialScrollIndex?: ?number,
/**
* Reverses the direction of scroll. Uses scale transforms of -1.
*/
inverted?: ?boolean,
/**
* Used to extract a unique key for a given item at the specified index. Key is used for caching
* and as the react key to track item re-ordering. The default extractor checks `item.key`, then
@@ -170,11 +163,6 @@ type OptionalProps<ItemT> = {
viewableItems: Array<ViewToken>,
changed: Array<ViewToken>,
}) => void,
/**
* Set this when offset is needed for the loading indicator to show correctly.
* @platform android
*/
progressViewOffset?: number,
legacyImplementation?: ?boolean,
/**
* Set this true while waiting for new data from a refresh.
@@ -191,9 +179,7 @@ type OptionalProps<ItemT> = {
*/
viewabilityConfig?: ViewabilityConfig,
};
type Props<ItemT> = RequiredProps<ItemT> &
OptionalProps<ItemT> &
VirtualizedListProps;
type Props<ItemT> = RequiredProps<ItemT> & OptionalProps<ItemT> & VirtualizedListProps;
const defaultProps = {
...VirtualizedList.defaultProps,
@@ -287,7 +273,7 @@ type DefaultProps = typeof defaultProps;
* }
*
* This is a convenience wrapper around [`<VirtualizedList>`](docs/virtualizedlist.html),
* and thus inherits its props (as well as those of `ScrollView`) that aren't explicitly listed
* and thus inherits it's props (as well as those of `ScrollView`) that aren't explicitly listed
* here, along with the following caveats:
*
* - Internal state is not preserved when content scrolls out of the render window. Make sure all
@@ -304,11 +290,7 @@ type DefaultProps = typeof defaultProps;
* Alternatively, you can provide a custom `keyExtractor` prop.
*
*/
class FlatList<ItemT> extends React.PureComponent<
DefaultProps,
Props<ItemT>,
void,
> {
class FlatList<ItemT> extends React.PureComponent<DefaultProps, Props<ItemT>, void> {
static defaultProps: DefaultProps = defaultProps;
props: Props<ItemT>;
/**
@@ -327,10 +309,7 @@ class FlatList<ItemT> extends React.PureComponent<
* `getItemLayout` prop.
*/
scrollToIndex(params: {
animated?: ?boolean,
index: number,
viewOffset?: number,
viewPosition?: number,
animated?: ?boolean, index: number, viewOffset?: number, viewPosition?: number,
}) {
this._listRef.scrollToIndex(params);
}
@@ -341,17 +320,13 @@ class FlatList<ItemT> extends React.PureComponent<
* Note: cannot scroll to locations outside the render window without specifying the
* `getItemLayout` prop.
*/
scrollToItem(params: {
animated?: ?boolean,
item: ItemT,
viewPosition?: number,
}) {
scrollToItem(params: {animated?: ?boolean, item: ItemT, viewPosition?: number}) {
this._listRef.scrollToItem(params);
}
/**
* Scroll to a specific content pixel offset in the list.
*
*
* Check out [scrollToOffset](docs/virtualizedlist.html#scrolltooffset) of VirtualizedList
*/
scrollToOffset(params: {animated?: ?boolean, offset: number}) {
@@ -391,12 +366,6 @@ class FlatList<ItemT> extends React.PureComponent<
}
}
setNativeProps(props: Object) {
if (this._listRef) {
this._listRef.setNativeProps(props);
}
}
componentWillMount() {
this._checkProps(this.props);
}
@@ -405,7 +374,7 @@ class FlatList<ItemT> extends React.PureComponent<
invariant(
nextProps.numColumns === this.props.numColumns,
'Changing numColumns on the fly is not supported. Change the key prop on FlatList when ' +
'changing the number of columns to force a fresh render of the component.',
'changing the number of columns to force a fresh render of the component.'
);
this._checkProps(nextProps);
}
@@ -413,9 +382,7 @@ class FlatList<ItemT> extends React.PureComponent<
_hasWarnedLegacy = false;
_listRef: VirtualizedList;
_captureRef = ref => {
this._listRef = ref;
};
_captureRef = (ref) => { this._listRef = ref; };
_checkProps(props: Props<ItemT>) {
const {
@@ -426,29 +393,20 @@ class FlatList<ItemT> extends React.PureComponent<
numColumns,
columnWrapperStyle,
} = props;
invariant(
!getItem && !getItemCount,
'FlatList does not support custom data formats.',
);
invariant(!getItem && !getItemCount, 'FlatList does not support custom data formats.');
if (numColumns > 1) {
invariant(!horizontal, 'numColumns does not support horizontal.');
} else {
invariant(
!columnWrapperStyle,
'columnWrapperStyle not supported for single column lists',
);
invariant(!columnWrapperStyle, 'columnWrapperStyle not supported for single column lists');
}
if (legacyImplementation) {
invariant(
numColumns === 1,
'Legacy list does not support multiple columns.',
);
invariant(numColumns === 1, 'Legacy list does not support multiple columns.');
// Warning: may not have full feature parity and is meant more for debugging and performance
// comparison.
if (!this._hasWarnedLegacy) {
console.warn(
'FlatList: Using legacyImplementation - some features not supported and performance ' +
'may suffer',
'may suffer'
);
this._hasWarnedLegacy = true;
}
@@ -479,12 +437,10 @@ class FlatList<ItemT> extends React.PureComponent<
invariant(
Array.isArray(items),
'FlatList: Encountered internal consistency error, expected each item to consist of an ' +
'array with 1-%s columns; instead, received a single item.',
'array with 1-%s columns; instead, received a single item.',
numColumns,
);
return items
.map((it, kk) => keyExtractor(it, index * numColumns + kk))
.join(':');
return items.map((it, kk) => keyExtractor(it, index * numColumns + kk)).join(':');
} else {
return keyExtractor(items, index);
}
@@ -499,7 +455,7 @@ class FlatList<ItemT> extends React.PureComponent<
});
}
_onViewableItemsChanged = info => {
_onViewableItemsChanged = (info) => {
const {numColumns, onViewableItemsChanged} = this.props;
if (!onViewableItemsChanged) {
return;
@@ -507,10 +463,8 @@ class FlatList<ItemT> extends React.PureComponent<
if (numColumns > 1) {
const changed = [];
const viewableItems = [];
info.viewableItems.forEach(v =>
this._pushMultiColumnViewable(viewableItems, v),
);
info.changed.forEach(v => this._pushMultiColumnViewable(changed, v));
info.viewableItems.forEach((v) => this._pushMultiColumnViewable(viewableItems, v));
info.changed.forEach((v) => this._pushMultiColumnViewable(changed, v));
onViewableItemsChanged({viewableItems, changed});
} else {
onViewableItemsChanged(info);
@@ -521,10 +475,7 @@ class FlatList<ItemT> extends React.PureComponent<
const {renderItem, numColumns, columnWrapperStyle} = this.props;
if (numColumns > 1) {
const {item, index} = info;
invariant(
Array.isArray(item),
'Expected array of items with numColumns > 1',
);
invariant(Array.isArray(item), 'Expected array of items with numColumns > 1');
return (
<View style={[{flexDirection: 'row'}, columnWrapperStyle]}>
{item.map((it, kk) => {
@@ -544,13 +495,7 @@ class FlatList<ItemT> extends React.PureComponent<
render() {
if (this.props.legacyImplementation) {
return (
<MetroListView
{...this.props}
items={this.props.data}
ref={this._captureRef}
/>
);
return <MetroListView {...this.props} items={this.props.data} ref={this._captureRef} />;
} else {
return (
<VirtualizedList
@@ -560,9 +505,7 @@ class FlatList<ItemT> extends React.PureComponent<
getItemCount={this._getItemCount}
keyExtractor={this._keyExtractor}
ref={this._captureRef}
onViewableItemsChanged={
this.props.onViewableItemsChanged && this._onViewableItemsChanged
}
onViewableItemsChanged={this.props.onViewableItemsChanged && this._onViewableItemsChanged}
/>
);
}
+86 -139
View File
@@ -8,7 +8,6 @@
*
* @providesModule ListView
* @flow
* @format
*/
'use strict';
@@ -35,13 +34,8 @@ var DEFAULT_SCROLL_RENDER_AHEAD = 1000;
var DEFAULT_END_REACHED_THRESHOLD = 1000;
var DEFAULT_SCROLL_CALLBACK_THROTTLE = 50;
/**
* DEPRECATED - use one of the new list components, such as [`FlatList`](docs/flatlist.html)
* or [`SectionList`](docs/sectionlist.html) for bounded memory use, fewer bugs,
* better performance, an easier to use API, and more features. Check out this
* [blog post](https://facebook.github.io/react-native/blog/2017/03/13/better-list-views.html)
* for more details.
*
* ListView - A core component designed for efficient display of vertically
* scrolling lists of changing data. The minimal API is to create a
* [`ListView.DataSource`](docs/listviewdatasource.html), populate it with a simple
@@ -241,9 +235,7 @@ var ListView = createReactClass({
getMetrics: function() {
return {
contentLength: this.scrollProperties.contentLength,
totalRows: this.props.enableEmptySections
? this.props.dataSource.getRowAndSectionCount()
: this.props.dataSource.getRowCount(),
totalRows: (this.props.enableEmptySections ? this.props.dataSource.getRowAndSectionCount() : this.props.dataSource.getRowCount()),
renderedRows: this.state.curRenderedRowsCount,
visibleRows: Object.keys(this._visibleRows).length,
};
@@ -289,14 +281,14 @@ var ListView = createReactClass({
*
* See `ScrollView#scrollToEnd`.
*/
scrollToEnd: function(options?: ?{animated?: ?boolean}) {
scrollToEnd: function(options?: ?{ animated?: ?boolean }) {
if (this._scrollComponent) {
if (this._scrollComponent.scrollToEnd) {
this._scrollComponent.scrollToEnd(options);
} else {
console.warn(
'The scroll component used by the ListView does not support ' +
'scrollToEnd. Check the renderScrollComponent prop of your ListView.',
'scrollToEnd. Check the renderScrollComponent prop of your ListView.'
);
}
}
@@ -338,7 +330,7 @@ var ListView = createReactClass({
getInitialState: function() {
return {
curRenderedRowsCount: this.props.initialListSize,
highlightedRow: ({}: Object),
highlightedRow: ({} : Object),
};
},
@@ -351,7 +343,7 @@ var ListView = createReactClass({
this.scrollProperties = {
visibleLength: null,
contentLength: null,
offset: 0,
offset: 0
};
this._childFrames = [];
this._visibleRows = {};
@@ -368,24 +360,20 @@ var ListView = createReactClass({
},
componentWillReceiveProps: function(nextProps: Object) {
if (
this.props.dataSource !== nextProps.dataSource ||
this.props.initialListSize !== nextProps.initialListSize
) {
this.setState(
(state, props) => {
this._prevRenderedRowsCount = 0;
return {
curRenderedRowsCount: Math.min(
Math.max(state.curRenderedRowsCount, props.initialListSize),
props.enableEmptySections
? props.dataSource.getRowAndSectionCount()
: props.dataSource.getRowCount(),
if (this.props.dataSource !== nextProps.dataSource ||
this.props.initialListSize !== nextProps.initialListSize) {
this.setState((state, props) => {
this._prevRenderedRowsCount = 0;
return {
curRenderedRowsCount: Math.min(
Math.max(
state.curRenderedRowsCount,
props.initialListSize
),
};
},
() => this._renderMoreRowsIfNeeded(),
);
props.enableEmptySections ? props.dataSource.getRowAndSectionCount() : props.dataSource.getRowCount()
),
};
}, () => this._renderMoreRowsIfNeeded());
}
},
@@ -419,32 +407,26 @@ var ListView = createReactClass({
if (rowIDs.length === 0) {
if (this.props.enableEmptySections === undefined) {
var warning = require('fbjs/lib/warning');
warning(
false,
'In next release empty section headers will be rendered.' +
" In this release you can use 'enableEmptySections' flag to render empty section headers.",
);
warning(false, 'In next release empty section headers will be rendered.'
+ ' In this release you can use \'enableEmptySections\' flag to render empty section headers.');
continue;
} else {
var invariant = require('fbjs/lib/invariant');
invariant(
this.props.enableEmptySections,
"In next release 'enableEmptySections' flag will be deprecated, empty section headers will always be rendered." +
' If empty section headers are not desirable their indices should be excluded from sectionIDs object.' +
" In this release 'enableEmptySections' may only have value 'true' to allow empty section headers rendering.",
);
'In next release \'enableEmptySections\' flag will be deprecated, empty section headers will always be rendered.'
+ ' If empty section headers are not desirable their indices should be excluded from sectionIDs object.'
+ ' In this release \'enableEmptySections\' may only have value \'true\' to allow empty section headers rendering.');
}
}
if (renderSectionHeader) {
const element = renderSectionHeader(
dataSource.getSectionHeaderData(sectionIdx),
sectionID,
sectionID
);
if (element) {
bodyComponents.push(
React.cloneElement(element, {key: 's_' + sectionID}),
);
bodyComponents.push(React.cloneElement(element, {key: 's_' + sectionID}));
if (this.props.stickySectionHeadersEnabled) {
stickySectionHeaderIndices.push(totalIndex);
}
@@ -455,10 +437,9 @@ var ListView = createReactClass({
for (var rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) {
var rowID = rowIDs[rowIdx];
var comboID = sectionID + '_' + rowID;
var shouldUpdateRow =
rowCount >= this._prevRenderedRowsCount &&
var shouldUpdateRow = rowCount >= this._prevRenderedRowsCount &&
dataSource.rowShouldUpdate(sectionIdx, rowIdx);
var row = (
var row =
<StaticRenderer
key={'r_' + comboID}
shouldUpdate={!!shouldUpdateRow}
@@ -467,31 +448,29 @@ var ListView = createReactClass({
dataSource.getRowData(sectionIdx, rowIdx),
sectionID,
rowID,
this._onRowHighlighted,
this._onRowHighlighted
)}
/>
);
/>;
bodyComponents.push(row);
totalIndex++;
if (
this.props.renderSeparator &&
(rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1)
) {
if (this.props.renderSeparator &&
(rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1)) {
var adjacentRowHighlighted =
this.state.highlightedRow.sectionID === sectionID &&
(this.state.highlightedRow.rowID === rowID ||
this.state.highlightedRow.rowID === rowIDs[rowIdx + 1]);
this.state.highlightedRow.sectionID === sectionID && (
this.state.highlightedRow.rowID === rowID ||
this.state.highlightedRow.rowID === rowIDs[rowIdx + 1]
);
var separator = this.props.renderSeparator(
sectionID,
rowID,
adjacentRowHighlighted,
adjacentRowHighlighted
);
if (separator) {
bodyComponents.push(
<View key={'s_' + comboID}>
{separator}
</View>,
</View>
);
totalIndex++;
}
@@ -505,7 +484,10 @@ var ListView = createReactClass({
}
}
var {renderScrollComponent, ...props} = this.props;
var {
renderScrollComponent,
...props
} = this.props;
if (!props.scrollEventThrottle) {
props.scrollEventThrottle = DEFAULT_SCROLL_CALLBACK_THROTTLE;
}
@@ -514,9 +496,7 @@ var ListView = createReactClass({
}
Object.assign(props, {
onScroll: this._onScroll,
stickyHeaderIndices: this.props.stickyHeaderIndices.concat(
stickySectionHeaderIndices,
),
stickyHeaderIndices: this.props.stickyHeaderIndices.concat(stickySectionHeaderIndices),
// Do not pass these events downstream to ScrollView since they will be
// registered in ListView's own ScrollResponder.Mixin
@@ -526,19 +506,11 @@ var ListView = createReactClass({
onKeyboardDidHide: undefined,
});
return cloneReferencedElement(
renderScrollComponent(props),
{
ref: this._setScrollComponentRef,
onContentSizeChange: this._onContentSizeChange,
onLayout: this._onLayout,
DEPRECATED_sendUpdatedChildFrames:
typeof props.onChangeVisibleRows !== undefined,
},
header,
bodyComponents,
footer,
);
return cloneReferencedElement(renderScrollComponent(props), {
ref: this._setScrollComponentRef,
onContentSizeChange: this._onContentSizeChange,
onLayout: this._onLayout,
}, header, bodyComponents, footer);
},
/**
@@ -553,8 +525,7 @@ var ListView = createReactClass({
// RCTScrollViewManager.calculateChildFrames is not available on
// every platform
RCTScrollViewManager &&
RCTScrollViewManager.calculateChildFrames &&
RCTScrollViewManager && RCTScrollViewManager.calculateChildFrames &&
RCTScrollViewManager.calculateChildFrames(
ReactNative.findNodeHandle(scrollComponent),
this._updateVisibleRows,
@@ -572,8 +543,7 @@ var ListView = createReactClass({
this._updateVisibleRows();
this._renderMoreRowsIfNeeded();
}
this.props.onContentSizeChange &&
this.props.onContentSizeChange(width, height);
this.props.onContentSizeChange && this.props.onContentSizeChange(width, height);
},
_onLayout: function(event: Object) {
@@ -588,16 +558,10 @@ var ListView = createReactClass({
},
_maybeCallOnEndReached: function(event?: Object) {
if (
this.props.onEndReached &&
this.scrollProperties.contentLength !== this._sentEndForContentLength &&
this._getDistanceFromEnd(this.scrollProperties) <
this.props.onEndReachedThreshold &&
this.state.curRenderedRowsCount ===
(this.props.enableEmptySections
? this.props.dataSource.getRowAndSectionCount()
: this.props.dataSource.getRowCount())
) {
if (this.props.onEndReached &&
this.scrollProperties.contentLength !== this._sentEndForContentLength &&
this._getDistanceFromEnd(this.scrollProperties) < this.props.onEndReachedThreshold &&
this.state.curRenderedRowsCount === (this.props.enableEmptySections ? this.props.dataSource.getRowAndSectionCount() : this.props.dataSource.getRowCount())) {
this._sentEndForContentLength = this.scrollProperties.contentLength;
this.props.onEndReached(event);
return true;
@@ -606,14 +570,9 @@ var ListView = createReactClass({
},
_renderMoreRowsIfNeeded: function() {
if (
this.scrollProperties.contentLength === null ||
if (this.scrollProperties.contentLength === null ||
this.scrollProperties.visibleLength === null ||
this.state.curRenderedRowsCount ===
(this.props.enableEmptySections
? this.props.dataSource.getRowAndSectionCount()
: this.props.dataSource.getRowCount())
) {
this.state.curRenderedRowsCount === (this.props.enableEmptySections ? this.props.dataSource.getRowAndSectionCount() : this.props.dataSource.getRowCount())) {
this._maybeCallOnEndReached();
return;
}
@@ -625,32 +584,23 @@ var ListView = createReactClass({
},
_pageInNewRows: function() {
this.setState(
(state, props) => {
var rowsToRender = Math.min(
state.curRenderedRowsCount + props.pageSize,
props.enableEmptySections
? props.dataSource.getRowAndSectionCount()
: props.dataSource.getRowCount(),
);
this._prevRenderedRowsCount = state.curRenderedRowsCount;
return {
curRenderedRowsCount: rowsToRender,
};
},
() => {
this._measureAndUpdateScrollProps();
this._prevRenderedRowsCount = this.state.curRenderedRowsCount;
},
);
this.setState((state, props) => {
var rowsToRender = Math.min(
state.curRenderedRowsCount + props.pageSize,
(props.enableEmptySections ? props.dataSource.getRowAndSectionCount() : props.dataSource.getRowCount())
);
this._prevRenderedRowsCount = state.curRenderedRowsCount;
return {
curRenderedRowsCount: rowsToRender
};
}, () => {
this._measureAndUpdateScrollProps();
this._prevRenderedRowsCount = this.state.curRenderedRowsCount;
});
},
_getDistanceFromEnd: function(scrollProperties: Object) {
return (
scrollProperties.contentLength -
scrollProperties.visibleLength -
scrollProperties.offset
);
return scrollProperties.contentLength - scrollProperties.visibleLength - scrollProperties.offset;
},
_updateVisibleRows: function(updatedFrames?: Array<Object>) {
@@ -658,7 +608,7 @@ var ListView = createReactClass({
return; // No need to compute visible rows if there is no callback
}
if (updatedFrames) {
updatedFrames.forEach(newFrame => {
updatedFrames.forEach((newFrame) => {
this._childFrames[newFrame.index] = merge(newFrame);
});
}
@@ -689,10 +639,8 @@ var ListView = createReactClass({
var rowID = rowIDs[rowIdx];
var frame = this._childFrames[totalIndex];
totalIndex++;
if (
this.props.renderSeparator &&
(rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1)
) {
if (this.props.renderSeparator &&
(rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1)){
totalIndex++;
}
if (!frame) {
@@ -701,7 +649,7 @@ var ListView = createReactClass({
var rowVisible = visibleSection[rowID];
var min = isVertical ? frame.y : frame.x;
var max = min + (isVertical ? frame.height : frame.width);
if ((!min && !max) || min === max) {
if ((!min && !max) || (min === max)) {
break;
}
if (min > visibleMax || max < visibleMin) {
@@ -728,28 +676,27 @@ var ListView = createReactClass({
delete this._visibleRows[sectionID];
}
}
visibilityChanged &&
this.props.onChangeVisibleRows(this._visibleRows, changedRows);
visibilityChanged && this.props.onChangeVisibleRows(this._visibleRows, changedRows);
},
_onScroll: function(e: Object) {
var isVertical = !this.props.horizontal;
this.scrollProperties.visibleLength =
e.nativeEvent.layoutMeasurement[isVertical ? 'height' : 'width'];
this.scrollProperties.contentLength =
e.nativeEvent.contentSize[isVertical ? 'height' : 'width'];
this.scrollProperties.offset =
e.nativeEvent.contentOffset[isVertical ? 'y' : 'x'];
this.scrollProperties.visibleLength = e.nativeEvent.layoutMeasurement[
isVertical ? 'height' : 'width'
];
this.scrollProperties.contentLength = e.nativeEvent.contentSize[
isVertical ? 'height' : 'width'
];
this.scrollProperties.offset = e.nativeEvent.contentOffset[
isVertical ? 'y' : 'x'
];
this._updateVisibleRows(e.nativeEvent.updatedChildFrames);
if (!this._maybeCallOnEndReached(e)) {
this._renderMoreRowsIfNeeded();
}
if (
this.props.onEndReached &&
this._getDistanceFromEnd(this.scrollProperties) >
this.props.onEndReachedThreshold
) {
if (this.props.onEndReached &&
this._getDistanceFromEnd(this.scrollProperties) > this.props.onEndReachedThreshold) {
// Scrolled out of the end zone, so it should be able to trigger again.
this._sentEndForContentLength = null;
}
+36 -47
View File
@@ -8,7 +8,6 @@
*
* @providesModule ListViewDataSource
* @flow
* @format
*/
'use strict';
@@ -19,26 +18,26 @@ var warning = require('fbjs/lib/warning');
function defaultGetRowData(
dataBlob: any,
sectionID: number | string,
rowID: number | string,
rowID: number | string
): any {
return dataBlob[sectionID][rowID];
}
function defaultGetSectionHeaderData(
dataBlob: any,
sectionID: number | string,
sectionID: number | string
): any {
return dataBlob[sectionID];
}
type differType = (data1: any, data2: any) => boolean;
type differType = (data1: any, data2: any) => bool;
type ParamType = {
rowHasChanged: differType,
getRowData?: ?typeof defaultGetRowData,
sectionHeaderHasChanged?: ?differType,
getSectionHeaderData?: ?typeof defaultGetSectionHeaderData,
};
}
/**
* Provides efficient data processing and access to the
@@ -75,6 +74,7 @@ type ParamType = {
*/
class ListViewDataSource {
/**
* You can provide custom extraction and `hasChanged` functions for section
* headers and rows. If absent, data will be extracted with the
@@ -103,7 +103,7 @@ class ListViewDataSource {
constructor(params: ParamType) {
invariant(
params && typeof params.rowHasChanged === 'function',
'Must provide a rowHasChanged function.',
'Must provide a rowHasChanged function.'
);
this._rowHasChanged = params.rowHasChanged;
this._getRowData = params.getRowData || defaultGetRowData;
@@ -138,10 +138,10 @@ class ListViewDataSource {
* handle merging of old and new data separately and then pass that into
* this function as the `dataBlob`.
*/
cloneWithRows(
dataBlob: $ReadOnlyArray<any> | {+[key: string]: any},
rowIdentities: ?$ReadOnlyArray<string>,
): ListViewDataSource {
cloneWithRows(
dataBlob: $ReadOnlyArray<any> | {+[key: string]: any},
rowIdentities: ?$ReadOnlyArray<string>
): ListViewDataSource {
var rowIds = rowIdentities ? [[...rowIdentities]] : null;
if (!this._sectionHeaderHasChanged) {
this._sectionHeaderHasChanged = () => false;
@@ -161,19 +161,17 @@ class ListViewDataSource {
* Note: this returns a new object!
*/
cloneWithRowsAndSections(
dataBlob: any,
sectionIdentities: ?Array<string>,
rowIdentities: ?Array<Array<string>>,
dataBlob: any,
sectionIdentities: ?Array<string>,
rowIdentities: ?Array<Array<string>>
): ListViewDataSource {
invariant(
typeof this._sectionHeaderHasChanged === 'function',
'Must provide a sectionHeaderHasChanged function with section data.',
'Must provide a sectionHeaderHasChanged function with section data.'
);
invariant(
!sectionIdentities ||
!rowIdentities ||
sectionIdentities.length === rowIdentities.length,
'row and section ids lengths must be the same',
!sectionIdentities || !rowIdentities || sectionIdentities.length === rowIdentities.length,
'row and section ids lengths must be the same'
);
var newSource = new ListViewDataSource({
@@ -192,7 +190,7 @@ class ListViewDataSource {
newSource.rowIdentities = rowIdentities;
} else {
newSource.rowIdentities = [];
newSource.sectionIdentities.forEach(sectionID => {
newSource.sectionIdentities.forEach((sectionID) => {
newSource.rowIdentities.push(Object.keys(dataBlob[sectionID]));
});
}
@@ -201,7 +199,7 @@ class ListViewDataSource {
newSource._calculateDirtyArrays(
this._dataBlob,
this.sectionIdentities,
this.rowIdentities,
this.rowIdentities
);
return newSource;
@@ -212,18 +210,16 @@ class ListViewDataSource {
}
getRowAndSectionCount(): number {
return this._cachedRowCount + this.sectionIdentities.length;
return (this._cachedRowCount + this.sectionIdentities.length);
}
/**
* Returns if the row is dirtied and needs to be rerendered
*/
rowShouldUpdate(sectionIndex: number, rowIndex: number): boolean {
rowShouldUpdate(sectionIndex: number, rowIndex: number): bool {
var needsUpdate = this._dirtyRows[sectionIndex][rowIndex];
warning(
needsUpdate !== undefined,
'missing dirtyBit for section, row: ' + sectionIndex + ', ' + rowIndex,
);
warning(needsUpdate !== undefined,
'missing dirtyBit for section, row: ' + sectionIndex + ', ' + rowIndex);
return needsUpdate;
}
@@ -235,7 +231,7 @@ class ListViewDataSource {
var rowID = this.rowIdentities[sectionIndex][rowIndex];
warning(
sectionID !== undefined && rowID !== undefined,
'rendering invalid section, row: ' + sectionIndex + ', ' + rowIndex,
'rendering invalid section, row: ' + sectionIndex + ', ' + rowIndex
);
return this._getRowData(this._dataBlob, sectionID, rowID);
}
@@ -286,12 +282,10 @@ class ListViewDataSource {
/**
* Returns if the section header is dirtied and needs to be rerendered
*/
sectionHeaderShouldUpdate(sectionIndex: number): boolean {
sectionHeaderShouldUpdate(sectionIndex: number): bool {
var needsUpdate = this._dirtySections[sectionIndex];
warning(
needsUpdate !== undefined,
'missing dirtyBit for section: ' + sectionIndex,
);
warning(needsUpdate !== undefined,
'missing dirtyBit for section: ' + sectionIndex);
return needsUpdate;
}
@@ -303,10 +297,8 @@ class ListViewDataSource {
return null;
}
var sectionID = this.sectionIdentities[sectionIndex];
warning(
sectionID !== undefined,
'renderSection called on invalid section: ' + sectionIndex,
);
warning(sectionID !== undefined,
'renderSection called on invalid section: ' + sectionIndex);
return this._getSectionHeaderData(this._dataBlob, sectionID);
}
@@ -320,8 +312,8 @@ class ListViewDataSource {
_sectionHeaderHasChanged: ?differType;
_dataBlob: any;
_dirtyRows: Array<Array<boolean>>;
_dirtySections: Array<boolean>;
_dirtyRows: Array<Array<bool>>;
_dirtySections: Array<bool>;
_cachedRowCount: number;
// These two 'protected' variables are accessed by ListView to iterate over
@@ -332,7 +324,7 @@ class ListViewDataSource {
_calculateDirtyArrays(
prevDataBlob: any,
prevSectionIDs: Array<string>,
prevRowIDs: Array<Array<string>>,
prevRowIDs: Array<Array<string>>
): void {
// construct a hashmap of the existing (old) id arrays
var prevSectionsHash = keyedDictionaryFromArray(prevSectionIDs);
@@ -341,7 +333,7 @@ class ListViewDataSource {
var sectionID = prevSectionIDs[ii];
warning(
!prevRowsHash[sectionID],
'SectionID appears more than once: ' + sectionID,
'SectionID appears more than once: ' + sectionID
);
prevRowsHash[sectionID] = keyedDictionaryFromArray(prevRowIDs[ii]);
}
@@ -359,17 +351,13 @@ class ListViewDataSource {
if (!dirty && sectionHeaderHasChanged) {
dirty = sectionHeaderHasChanged(
this._getSectionHeaderData(prevDataBlob, sectionID),
this._getSectionHeaderData(this._dataBlob, sectionID),
this._getSectionHeaderData(this._dataBlob, sectionID)
);
}
this._dirtySections.push(!!dirty);
this._dirtyRows[sIndex] = [];
for (
var rIndex = 0;
rIndex < this.rowIdentities[sIndex].length;
rIndex++
) {
for (var rIndex = 0; rIndex < this.rowIdentities[sIndex].length; rIndex++) {
var rowID = this.rowIdentities[sIndex][rIndex];
// dirty if the section is new, row is new or _rowHasChanged is true
dirty =
@@ -377,7 +365,7 @@ class ListViewDataSource {
!prevRowsHash[sectionID][rowID] ||
this._rowHasChanged(
this._getRowData(prevDataBlob, sectionID, rowID),
this._getRowData(this._dataBlob, sectionID, rowID),
this._getRowData(this._dataBlob, sectionID, rowID)
);
this._dirtyRows[sIndex].push(!!dirty);
}
@@ -407,4 +395,5 @@ function keyedDictionaryFromArray(arr) {
return result;
}
module.exports = ListViewDataSource;
@@ -7,7 +7,6 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@@ -19,8 +18,8 @@ const StaticRenderer = require('StaticRenderer');
class ListViewMock extends React.Component {
static latestRef: ?ListViewMock;
static defaultProps = {
renderScrollComponent: props => <ScrollView {...props} />,
};
renderScrollComponent: (props) => <ScrollView {...props} />,
}
componentDidMount() {
ListViewMock.latestRef = this;
}
@@ -42,9 +41,9 @@ class ListViewMock extends React.Component {
null,
dataSource.getRowData(sectionIdx, rowIdx),
sectionID,
rowID,
rowID
)}
/>,
/>
);
}
}
+19 -37
View File
@@ -8,7 +8,6 @@
*
* @providesModule MetroListView
* @flow
* @format
*/
'use strict';
@@ -63,18 +62,10 @@ class MetroListView extends React.Component {
scrollToEnd(params?: ?{animated?: ?boolean}) {
throw new Error('scrollToEnd not supported in legacy ListView.');
}
scrollToIndex(params: {
animated?: ?boolean,
index: number,
viewPosition?: number,
}) {
scrollToIndex(params: {animated?: ?boolean, index: number, viewPosition?: number}) {
throw new Error('scrollToIndex not supported in legacy ListView.');
}
scrollToItem(params: {
animated?: ?boolean,
item: Item,
viewPosition?: number,
}) {
scrollToItem(params: {animated?: ?boolean, item: Item, viewPosition?: number}) {
throw new Error('scrollToItem not supported in legacy ListView.');
}
scrollToLocation(params: {
@@ -89,17 +80,12 @@ class MetroListView extends React.Component {
scrollToOffset(params: {animated?: ?boolean, offset: number}) {
const {animated, offset} = params;
this._listRef.scrollTo(
this.props.horizontal ? {x: offset, animated} : {y: offset, animated},
this.props.horizontal ? {x: offset, animated} : {y: offset, animated}
);
}
getListRef() {
return this._listRef;
}
setNativeProps(props: Object) {
if (this._listRef) {
this._listRef.setNativeProps(props);
}
}
static defaultProps: DefaultProps = {
keyExtractor: (item, index) => item.key || String(index),
renderScrollComponent: (props: Props) => {
@@ -120,17 +106,19 @@ class MetroListView extends React.Component {
}
},
};
state = this._computeState(this.props, {
ds: new ListView.DataSource({
rowHasChanged: (itemA, itemB) => true,
sectionHeaderHasChanged: () => true,
getSectionHeaderData: (dataBlob, sectionID) =>
this.state.sectionHeaderData[sectionID],
}),
sectionHeaderData: {},
});
state = this._computeState(
this.props,
{
ds: new ListView.DataSource({
rowHasChanged: (itemA, itemB) => true,
sectionHeaderHasChanged: () => true,
getSectionHeaderData: (dataBlob, sectionID) => this.state.sectionHeaderData[sectionID],
}),
sectionHeaderData: {},
},
);
componentWillReceiveProps(newProps: Props) {
this.setState(state => this._computeState(newProps, state));
this.setState((state) => this._computeState(newProps, state));
}
render() {
return (
@@ -146,9 +134,7 @@ class MetroListView extends React.Component {
);
}
_listRef: ListView;
_captureRef = ref => {
this._listRef = ref;
};
_captureRef = (ref) => { this._listRef = ref; };
_computeState(props: Props, state) {
const sectionHeaderData = {};
if (props.sections) {
@@ -177,14 +163,10 @@ class MetroListView extends React.Component {
};
_renderSectionHeader = (section, sectionID) => {
const {renderSectionHeader} = this.props;
invariant(
renderSectionHeader,
'Must provide renderSectionHeader with sections prop',
);
invariant(renderSectionHeader, 'Must provide renderSectionHeader with sections prop');
return renderSectionHeader({section});
};
_renderSeparator = (sID, rID) =>
<this.props.SeparatorComponent key={sID + rID} />;
}
_renderSeparator = (sID, rID) => <this.props.SeparatorComponent key={sID + rID} />;
}
module.exports = MetroListView;
+11 -22
View File
@@ -8,7 +8,6 @@
*
* @providesModule SectionList
* @flow
* @format
*/
'use strict';
@@ -122,16 +121,12 @@ type OptionalProps<SectionT: SectionBase<any>> = {
* to improve perceived performance of scroll-to-top actions.
*/
initialNumToRender: number,
/**
* Reverses the direction of scroll. Uses scale transforms of -1.
*/
inverted?: ?boolean,
/**
* Used to extract a unique key for a given item at the specified index. Key is used for caching
* and as the react key to track item re-ordering. The default extractor checks item.key, then
* falls back to using the index, like react does. Note that this sets keys for each item, but
* each overall section still needs its own key.
* falls back to using the index, like react does.
*/
keyExtractor: (item: Item, index: number) => string,
/**
* Called once when the scroll position gets within `onEndReachedThreshold` of the rendered
@@ -186,9 +181,9 @@ type OptionalProps<SectionT: SectionBase<any>> = {
legacyImplementation?: ?boolean,
};
type Props<SectionT> = RequiredProps<SectionT> &
OptionalProps<SectionT> &
VirtualizedSectionListProps<SectionT>;
type Props<SectionT> = RequiredProps<SectionT>
& OptionalProps<SectionT>
& VirtualizedSectionListProps<SectionT>;
const defaultProps = {
...VirtualizedSectionList.defaultProps,
@@ -235,7 +230,7 @@ type DefaultProps = typeof defaultProps;
* />
*
* This is a convenience wrapper around [`<VirtualizedList>`](docs/virtualizedlist.html),
* and thus inherits its props (as well as those of `ScrollView`) that aren't explicitly listed
* and thus inherits it's props (as well as those of `ScrollView`) that aren't explicitly listed
* here, along with the following caveats:
*
* - Internal state is not preserved when content scrolls out of the render window. Make sure all
@@ -252,11 +247,9 @@ type DefaultProps = typeof defaultProps;
* Alternatively, you can provide a custom `keyExtractor` prop.
*
*/
class SectionList<SectionT: SectionBase<any>> extends React.PureComponent<
DefaultProps,
Props<SectionT>,
void,
> {
class SectionList<SectionT: SectionBase<any>>
extends React.PureComponent<DefaultProps, Props<SectionT>, void>
{
props: Props<SectionT>;
static defaultProps: DefaultProps = defaultProps;
@@ -318,16 +311,12 @@ class SectionList<SectionT: SectionBase<any>> extends React.PureComponent<
}
render() {
const List = this.props.legacyImplementation
? MetroListView
: VirtualizedSectionList;
const List = this.props.legacyImplementation ? MetroListView : VirtualizedSectionList;
return <List {...this.props} ref={this._captureRef} />;
}
_wrapperListRef: MetroListView | VirtualizedSectionList<any>;
_captureRef = ref => {
this._wrapperListRef = ref;
};
_captureRef = (ref) => { this._wrapperListRef = ref; };
}
module.exports = SectionList;
+41 -79
View File
@@ -8,19 +8,12 @@
*
* @providesModule ViewabilityHelper
* @flow
* @format
*/
'use strict';
const invariant = require('fbjs/lib/invariant');
export type ViewToken = {
item: any,
key: string,
index: ?number,
isViewable: boolean,
section?: any,
};
export type ViewToken = {item: any, key: string, index: ?number, isViewable: boolean, section?: any};
export type ViewabilityConfig = {|
/**
@@ -71,9 +64,7 @@ class ViewabilityHelper {
_viewableIndices: Array<number> = [];
_viewableItems: Map<string, ViewToken> = new Map();
constructor(
config: ViewabilityConfig = {viewAreaCoveragePercentThreshold: 0},
) {
constructor(config: ViewabilityConfig = {viewAreaCoveragePercentThreshold: 0}) {
this._config = config;
}
@@ -94,19 +85,14 @@ class ViewabilityHelper {
getFrameMetrics: (index: number) => ?{length: number, offset: number},
renderRange?: {first: number, last: number}, // Optional optimization to reduce the scan size
): Array<number> {
const {
itemVisiblePercentThreshold,
viewAreaCoveragePercentThreshold,
} = this._config;
const {itemVisiblePercentThreshold, viewAreaCoveragePercentThreshold} = this._config;
const viewAreaMode = viewAreaCoveragePercentThreshold != null;
const viewablePercentThreshold = viewAreaMode
? viewAreaCoveragePercentThreshold
: itemVisiblePercentThreshold;
const viewablePercentThreshold = viewAreaMode ?
viewAreaCoveragePercentThreshold :
itemVisiblePercentThreshold;
invariant(
viewablePercentThreshold != null &&
itemVisiblePercentThreshold !=
null !==
(viewAreaCoveragePercentThreshold != null),
(itemVisiblePercentThreshold != null) !== (viewAreaCoveragePercentThreshold != null),
'Must set exactly one of itemVisiblePercentThreshold or viewAreaCoveragePercentThreshold',
);
const viewableIndices = [];
@@ -117,7 +103,7 @@ class ViewabilityHelper {
const {first, last} = renderRange || {first: 0, last: itemCount - 1};
invariant(
last < itemCount,
'Invalid render range ' + JSON.stringify({renderRange, itemCount}),
'Invalid render range ' + JSON.stringify({renderRange, itemCount})
);
for (let idx = first; idx <= last; idx++) {
const metrics = getFrameMetrics(idx);
@@ -126,18 +112,16 @@ class ViewabilityHelper {
}
const top = metrics.offset - scrollOffset;
const bottom = top + metrics.length;
if (top < viewportHeight && bottom > 0) {
if ((top < viewportHeight) && (bottom > 0)) {
firstVisible = idx;
if (
_isViewable(
viewAreaMode,
viewablePercentThreshold,
top,
bottom,
viewportHeight,
metrics.length,
)
) {
if (_isViewable(
viewAreaMode,
viewablePercentThreshold,
top,
bottom,
viewportHeight,
metrics.length,
)) {
viewableIndices.push(idx);
}
} else if (firstVisible >= 0) {
@@ -157,10 +141,7 @@ class ViewabilityHelper {
viewportHeight: number,
getFrameMetrics: (index: number) => ?{length: number, offset: number},
createViewToken: (index: number, isViewable: boolean) => ViewToken,
onViewableItemsChanged: ({
viewableItems: Array<ViewToken>,
changed: Array<ViewToken>,
}) => void,
onViewableItemsChanged: ({viewableItems: Array<ViewToken>, changed: Array<ViewToken>}) => void,
renderRange?: {first: number, last: number}, // Optional optimization to reduce the scan size
): void {
const updateTime = Date.now();
@@ -168,9 +149,7 @@ class ViewabilityHelper {
// Only count updates after the first item is rendered and has a frame.
this._lastUpdateTime = updateTime;
}
const updateElapsed = this._lastUpdateTime
? updateTime - this._lastUpdateTime
: 0;
const updateElapsed = this._lastUpdateTime ? updateTime - this._lastUpdateTime : 0;
if (this._config.waitForInteraction && !this._hasInteracted) {
return;
}
@@ -184,35 +163,25 @@ class ViewabilityHelper {
renderRange,
);
}
if (
this._viewableIndices.length === viewableIndices.length &&
this._viewableIndices.every((v, ii) => v === viewableIndices[ii])
) {
if (this._viewableIndices.length === viewableIndices.length &&
this._viewableIndices.every((v, ii) => v === viewableIndices[ii])) {
// We might get a lot of scroll events where visibility doesn't change and we don't want to do
// extra work in those cases.
return;
}
this._viewableIndices = viewableIndices;
this._lastUpdateTime = updateTime;
if (
this._config.minimumViewTime &&
updateElapsed < this._config.minimumViewTime
) {
const handle = setTimeout(() => {
this._timers.delete(handle);
this._onUpdateSync(
viewableIndices,
onViewableItemsChanged,
createViewToken,
);
}, this._config.minimumViewTime);
if (this._config.minimumViewTime && updateElapsed < this._config.minimumViewTime) {
const handle = setTimeout(
() => {
this._timers.delete(handle);
this._onUpdateSync(viewableIndices, onViewableItemsChanged, createViewToken);
},
this._config.minimumViewTime,
);
this._timers.add(handle);
} else {
this._onUpdateSync(
viewableIndices,
onViewableItemsChanged,
createViewToken,
);
this._onUpdateSync(viewableIndices, onViewableItemsChanged, createViewToken);
}
}
@@ -223,21 +192,17 @@ class ViewabilityHelper {
this._hasInteracted = true;
}
_onUpdateSync(
viewableIndicesToCheck,
onViewableItemsChanged,
createViewToken,
) {
_onUpdateSync(viewableIndicesToCheck, onViewableItemsChanged, createViewToken) {
// Filter out indices that have gone out of view since this call was scheduled.
viewableIndicesToCheck = viewableIndicesToCheck.filter(ii =>
this._viewableIndices.includes(ii),
viewableIndicesToCheck = viewableIndicesToCheck.filter(
(ii) => this._viewableIndices.includes(ii)
);
const prevItems = this._viewableItems;
const nextItems = new Map(
viewableIndicesToCheck.map(ii => {
const viewable = createViewToken(ii, true);
return [viewable.key, viewable];
}),
})
);
const changed = [];
@@ -253,14 +218,12 @@ class ViewabilityHelper {
}
if (changed.length > 0) {
this._viewableItems = nextItems;
onViewableItemsChanged({
viewableItems: Array.from(nextItems.values()),
changed,
});
onViewableItemsChanged({viewableItems: Array.from(nextItems.values()), changed});
}
}
}
function _isViewable(
viewAreaMode: boolean,
viewablePercentThreshold: number,
@@ -268,13 +231,12 @@ function _isViewable(
bottom: number,
viewportHeight: number,
itemLength: number,
): boolean {
): bool {
if (_isEntirelyVisible(top, bottom, viewportHeight)) {
return true;
} else {
const pixels = _getPixelsVisible(top, bottom, viewportHeight);
const percent =
100 * (viewAreaMode ? pixels / viewportHeight : pixels / itemLength);
const percent = 100 * (viewAreaMode ? pixels / viewportHeight : pixels / itemLength);
return percent >= viewablePercentThreshold;
}
}
@@ -282,7 +244,7 @@ function _isViewable(
function _getPixelsVisible(
top: number,
bottom: number,
viewportHeight: number,
viewportHeight: number
): number {
const visibleHeight = Math.min(bottom, viewportHeight) - Math.max(top, 0);
return Math.max(0, visibleHeight);
@@ -291,8 +253,8 @@ function _getPixelsVisible(
function _isEntirelyVisible(
top: number,
bottom: number,
viewportHeight: number,
): boolean {
viewportHeight: number
): bool {
return top >= 0 && bottom <= viewportHeight && bottom > top;
}
+23 -61
View File
@@ -8,7 +8,6 @@
*
* @providesModule VirtualizeUtils
* @flow
* @format
*/
'use strict';
@@ -34,8 +33,7 @@ function elementsThatOverlapOffsets(
if (kk === offsets.length - 1) {
invariant(
out.length === offsets.length,
'bad offsets input, should be in increasing order ' +
JSON.stringify(offsets),
'bad offsets input, should be in increasing order ' + JSON.stringify(offsets)
);
return out;
}
@@ -55,15 +53,11 @@ function newRangeCount(
prev: {first: number, last: number},
next: {first: number, last: number},
): number {
return (
next.last -
next.first +
1 -
return (next.last - next.first + 1) -
Math.max(
0,
1 + Math.min(next.last, prev.last) - Math.max(next.first, prev.first),
)
);
1 + Math.min(next.last, prev.last) - Math.max(next.first, prev.first)
);
}
/**
@@ -81,12 +75,7 @@ function computeWindowedRenderLimits(
},
prev: {first: number, last: number},
getFrameMetricsApprox: (index: number) => {length: number, offset: number},
scrollMetrics: {
dt: number,
offset: number,
velocity: number,
visibleLength: number,
},
scrollMetrics: {dt: number, offset: number, velocity: number, visibleLength: number},
): {first: number, last: number} {
const {data, getItemCount, maxToRenderPerBatch, windowSize} = props;
const itemCount = getItemCount(data);
@@ -105,13 +94,9 @@ function computeWindowedRenderLimits(
// Considering velocity seems to introduce more churn than it's worth.
const leadFactor = 0.5; // Math.max(0, Math.min(1, velocity / 25 + 0.5));
const fillPreference =
velocity > 1 ? 'after' : velocity < -1 ? 'before' : 'none';
const fillPreference = velocity > 1 ? 'after' : (velocity < -1 ? 'before' : 'none');
const overscanBegin = Math.max(
0,
visibleBegin - (1 - leadFactor) * overscanLength,
);
const overscanBegin = Math.max(0, visibleBegin - (1 - leadFactor) * overscanLength);
const overscanEnd = Math.max(0, visibleEnd + leadFactor * overscanLength);
// Find the indices that correspond to the items at the render boundaries we're targetting.
@@ -122,11 +107,8 @@ function computeWindowedRenderLimits(
);
overscanFirst = overscanFirst == null ? 0 : overscanFirst;
first = first == null ? Math.max(0, overscanFirst) : first;
overscanLast = overscanLast == null ? itemCount - 1 : overscanLast;
last =
last == null
? Math.min(overscanLast, first + maxToRenderPerBatch - 1)
: last;
overscanLast = overscanLast == null ? (itemCount - 1) : overscanLast;
last = last == null ? Math.min(overscanLast, first + maxToRenderPerBatch - 1) : last;
const visible = {first, last};
// We want to limit the number of new cells we're rendering per batch so that we can fill the
@@ -142,11 +124,9 @@ function computeWindowedRenderLimits(
}
const maxNewCells = newCellCount >= maxToRenderPerBatch;
const firstWillAddMore = first <= prev.first || first > prev.last;
const firstShouldIncrement =
first > overscanFirst && (!maxNewCells || !firstWillAddMore);
const firstShouldIncrement = first > overscanFirst && (!maxNewCells || !firstWillAddMore);
const lastWillAddMore = last >= prev.last || last < prev.first;
const lastShouldIncrement =
last < overscanLast && (!maxNewCells || !lastWillAddMore);
const lastShouldIncrement = last < overscanLast && (!maxNewCells || !lastWillAddMore);
if (maxNewCells && !firstShouldIncrement && !lastShouldIncrement) {
// We only want to stop if we've hit maxNewCells AND we cannot increment first or last
// without rendering new items. This let's us preserve as many already rendered items as
@@ -154,47 +134,29 @@ function computeWindowedRenderLimits(
// possible.
break;
}
if (
firstShouldIncrement &&
!(fillPreference === 'after' && lastShouldIncrement && lastWillAddMore)
) {
if (firstShouldIncrement &&
!(fillPreference === 'after' && lastShouldIncrement && lastWillAddMore)) {
if (firstWillAddMore) {
newCellCount++;
}
first--;
}
if (
lastShouldIncrement &&
!(fillPreference === 'before' && firstShouldIncrement && firstWillAddMore)
) {
if (lastShouldIncrement &&
!(fillPreference === 'before' && firstShouldIncrement && firstWillAddMore)) {
if (lastWillAddMore) {
newCellCount++;
}
last++;
}
}
if (
!(
last >= first &&
first >= 0 &&
last < itemCount &&
first >= overscanFirst &&
last <= overscanLast &&
first <= visible.first &&
last >= visible.last
)
) {
throw new Error(
'Bad window calculation ' +
JSON.stringify({
first,
last,
itemCount,
overscanFirst,
overscanLast,
visible,
}),
);
if (!(
last >= first &&
first >= 0 && last < itemCount &&
first >= overscanFirst && last <= overscanLast &&
first <= visible.first && last >= visible.last
)) {
throw new Error('Bad window calculation ' +
JSON.stringify({first, last, itemCount, overscanFirst, overscanLast, visible}));
}
return {first, last};
}
File diff suppressed because it is too large Load Diff
+40 -83
View File
@@ -8,7 +8,6 @@
*
* @providesModule VirtualizedSectionList
* @flow
* @format
*/
'use strict';
@@ -109,23 +108,19 @@ type OptionalProps<SectionT: SectionBase> = {
* Called when the viewability of rows changes, as defined by the
* `viewabilityConfig` prop.
*/
onViewableItemsChanged?: ?({
viewableItems: Array<ViewToken>,
changed: Array<ViewToken>,
}) => void,
onViewableItemsChanged?: ?({viewableItems: Array<ViewToken>, changed: Array<ViewToken>}) => void,
/**
* Set this true while waiting for new data from a refresh.
*/
refreshing?: ?boolean,
};
export type Props<SectionT> = RequiredProps<SectionT> &
export type Props<SectionT> =
RequiredProps<SectionT> &
OptionalProps<SectionT> &
VirtualizedListProps;
type DefaultProps = typeof VirtualizedList.defaultProps & {
data: $ReadOnlyArray<Item>,
};
type DefaultProps = (typeof VirtualizedList.defaultProps) & {data: $ReadOnlyArray<Item>};
type State = {childProps: VirtualizedListProps};
/**
@@ -133,11 +128,9 @@ type State = {childProps: VirtualizedListProps};
* hood. The only operation that might not scale well is concatting the data arrays of all the
* sections when new props are received, which should be plenty fast for up to ~10,000 items.
*/
class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
DefaultProps,
Props<SectionT>,
State,
> {
class VirtualizedSectionList<SectionT: SectionBase>
extends React.PureComponent<DefaultProps, Props<SectionT>, State>
{
props: Props<SectionT>;
state: State;
@@ -148,10 +141,7 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
};
scrollToLocation(params: {
animated?: ?boolean,
itemIndex: number,
sectionIndex: number,
viewPosition?: number,
animated?: ?boolean, itemIndex: number, sectionIndex: number, viewPosition?: number
}) {
let index = params.itemIndex + 1;
for (let ii = 0; ii < params.sectionIndex; ii++) {
@@ -239,22 +229,16 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
};
};
_onViewableItemsChanged = ({
viewableItems,
changed,
}: {
viewableItems: Array<ViewToken>,
changed: Array<ViewToken>,
}) => {
_onViewableItemsChanged = (
{viewableItems, changed}: {viewableItems: Array<ViewToken>, changed: Array<ViewToken>}
) => {
if (this.props.onViewableItemsChanged) {
this.props.onViewableItemsChanged({
viewableItems: viewableItems
.map(this._convertViewable, this)
.filter(Boolean),
viewableItems: viewableItems.map(this._convertViewable, this).filter(Boolean),
changed: changed.map(this._convertViewable, this).filter(Boolean),
});
}
};
}
_renderItem = ({item, index}: {item: Item, index: number}) => {
const info = this._subExtractor(index);
@@ -278,8 +262,9 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
return (
<ItemWithSeparator
SeparatorComponent={SeparatorComponent}
LeadingSeparatorComponent={
infoIndex === 0 ? this.props.SectionSeparatorComponent : undefined
LeadingSeparatorComponent={infoIndex === 0
? this.props.SectionSeparatorComponent
: undefined
}
cellKey={info.key}
index={infoIndex}
@@ -288,9 +273,7 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
leadingSection={info.leadingSection}
onUpdateSeparator={this._onUpdateSeparator}
prevCellKey={(this._subExtractor(index - 1) || {}).key}
ref={ref => {
this._cellRefs[info.key] = ref;
}}
ref={(ref) => {this._cellRefs[info.key] = ref;}}
renderItem={renderItem}
section={info.section}
trailingItem={info.trailingItem}
@@ -327,10 +310,13 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
_computeState(props: Props<SectionT>): State {
const offset = props.ListHeaderComponent ? 1 : 0;
const stickyHeaderIndices = [];
const itemCount = props.sections.reduce((v, section) => {
stickyHeaderIndices.push(v + offset);
return v + section.data.length + 2; // Add two for the section header and footer.
}, 0);
const itemCount = props.sections.reduce(
(v, section) => {
stickyHeaderIndices.push(v + offset);
return v + section.data.length + 2; // Add two for the section header and footer.
},
0
);
return {
childProps: {
@@ -341,12 +327,9 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
getItemCount: () => itemCount,
getItem,
keyExtractor: this._keyExtractor,
onViewableItemsChanged: props.onViewableItemsChanged
? this._onViewableItemsChanged
: undefined,
stickyHeaderIndices: props.stickySectionHeadersEnabled
? stickyHeaderIndices
: undefined,
onViewableItemsChanged:
props.onViewableItemsChanged ? this._onViewableItemsChanged : undefined,
stickyHeaderIndices: props.stickySectionHeadersEnabled ? stickyHeaderIndices : undefined,
},
};
}
@@ -361,16 +344,12 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
}
render() {
return (
<VirtualizedList {...this.state.childProps} ref={this._captureRef} />
);
return <VirtualizedList {...this.state.childProps} ref={this._captureRef} />;
}
_cellRefs = {};
_listRef: VirtualizedList;
_captureRef = ref => {
this._listRef = ref;
};
_captureRef = (ref) => { this._listRef = ref; };
}
class ItemWithSeparator extends React.Component {
@@ -411,62 +390,40 @@ class ItemWithSeparator extends React.Component {
_separators = {
highlight: () => {
['leading', 'trailing'].forEach(s =>
this._separators.updateProps(s, {highlighted: true}),
);
['leading', 'trailing'].forEach(s => this._separators.updateProps(s, {highlighted: true}));
},
unhighlight: () => {
['leading', 'trailing'].forEach(s =>
this._separators.updateProps(s, {highlighted: false}),
);
['leading', 'trailing'].forEach(s => this._separators.updateProps(s, {highlighted: false}));
},
updateProps: (select: 'leading' | 'trailing', newProps: Object) => {
const {LeadingSeparatorComponent, cellKey, prevCellKey} = this.props;
if (select === 'leading' && LeadingSeparatorComponent) {
this.setState(state => ({
leadingSeparatorProps: {...state.leadingSeparatorProps, ...newProps},
leadingSeparatorProps: {...state.leadingSeparatorProps, ...newProps}
}));
} else {
this.props.onUpdateSeparator(
(select === 'leading' && prevCellKey) || cellKey,
newProps,
);
this.props.onUpdateSeparator((select === 'leading' && prevCellKey) || cellKey, newProps);
}
},
};
updateSeparatorProps(newProps: Object) {
this.setState(state => ({
separatorProps: {...state.separatorProps, ...newProps},
}));
this.setState(state => ({separatorProps: {...state.separatorProps, ...newProps}}));
}
render() {
const {
LeadingSeparatorComponent,
SeparatorComponent,
item,
index,
section,
} = this.props;
const {LeadingSeparatorComponent, SeparatorComponent, item, index, section} = this.props;
const element = this.props.renderItem({
item,
index,
section,
separators: this._separators,
});
const leadingSeparator =
LeadingSeparatorComponent &&
const leadingSeparator = LeadingSeparatorComponent &&
<LeadingSeparatorComponent {...this.state.leadingSeparatorProps} />;
const separator =
SeparatorComponent &&
<SeparatorComponent {...this.state.separatorProps} />;
return leadingSeparator || separator
? <View>
{leadingSeparator}
{element}
{separator}
</View>
const separator = SeparatorComponent && <SeparatorComponent {...this.state.separatorProps} />;
return (leadingSeparator || separator)
? <View>{leadingSeparator}{element}{separator}</View>
: element;
}
}
@@ -486,7 +443,7 @@ function getItem(sections: ?$ReadOnlyArray<Item>, index: number): ?Item {
// If we are in the bounds of the list's data then return the item.
return sections[ii].data[itemIdx];
} else {
itemIdx -= sections[ii].data.length + 2; // Add two for the header and footer
itemIdx -= (sections[ii].data.length + 2); // Add two for the header and footer
}
}
return null;
@@ -7,7 +7,6 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@@ -21,82 +20,60 @@ function renderMyListItem(info: {item: {title: string}, index: number}) {
module.exports = {
testEverythingIsFine() {
const data = [
{
title: 'Title Text',
key: 1,
},
];
const data = [{
title: 'Title Text',
key: 1,
}];
return <FlatList renderItem={renderMyListItem} data={data} />;
},
testBadDataWithTypicalItem() {
const data = [
{
// $FlowExpectedError - bad title type 6, should be string
title: 6,
key: 1,
},
];
// $FlowExpectedError - bad title type 6, should be string
const data = [{
title: 6,
key: 1,
}];
return <FlatList renderItem={renderMyListItem} data={data} />;
},
testMissingFieldWithTypicalItem() {
const data = [
{
key: 1,
},
];
const data = [{
key: 1,
}];
// $FlowExpectedError - missing title
return <FlatList renderItem={renderMyListItem} data={data} />;
},
testGoodDataWithBadCustomRenderItemFunction() {
const data = [
{
widget: 6,
key: 1,
},
];
const data = [{
widget: 6,
key: 1,
}];
return (
<FlatList
renderItem={info =>
<span>
{
// $FlowExpectedError - bad widgetCount type 6, should be Object
info.item.widget.missingProp
}
</span>}
renderItem={(info) =>
// $FlowExpectedError - bad widgetCount type 6, should be Object
<span>{info.item.widget.missingProp}</span>
}
data={data}
/>
);
},
testBadRenderItemFunction() {
const data = [
{
title: 'foo',
key: 1,
},
];
const data = [{
title: 'foo',
key: 1,
}];
return [
// $FlowExpectedError - title should be inside `item`
<FlatList renderItem={(info: {title: string}) => <span />} data={data} />,
<FlatList
// $FlowExpectedError - bad index type string, should be number
renderItem={(info: {item: any, index: string}) => <span />}
data={data}
/>,
<FlatList
// $FlowExpectedError - bad title type number, should be string
renderItem={(info: {item: {title: number}}) => <span />}
data={data}
/>,
<FlatList renderItem={(info: {title: string}) => <span /> } data={data} />,
// $FlowExpectedError - bad index type string, should be number
<FlatList renderItem={(info: {item: any, index: string}) => <span /> } data={data} />,
// $FlowExpectedError - bad title type number, should be string
<FlatList renderItem={(info: {item: {title: number}}) => <span /> } data={data} />,
// EverythingIsFine
<FlatList
renderItem={(info: {item: {title: string}}) => <span />}
data={data}
/>,
<FlatList renderItem={(info: {item: {title: string}}) => <span /> } data={data} />,
];
},
@@ -7,7 +7,6 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@@ -19,66 +18,40 @@ function renderMyListItem(info: {item: {title: string}, index: number}) {
return <span />;
}
const renderMyHeader = ({section}: {section: {fooNumber: number} & Object}) =>
<span />;
const renderMyHeader = ({section}: {section: {fooNumber: number} & Object}) => <span />;
module.exports = {
testGoodDataWithGoodItem() {
const sections = [
{
key: 'a',
data: [
{
title: 'foo',
key: 1,
},
],
},
];
const sections = [{
key: 'a', data: [{
title: 'foo',
key: 1,
}],
}];
return <SectionList renderItem={renderMyListItem} sections={sections} />;
},
testBadRenderItemFunction() {
const sections = [
{
key: 'a',
data: [
{
title: 'foo',
key: 1,
},
],
},
];
const sections = [{
key: 'a', data: [{
title: 'foo',
key: 1,
}],
}];
return [
// $FlowExpectedError - title should be inside `item`
<SectionList
renderItem={(info: {title: string}) => <span />}
sections={sections}
/>,
<SectionList
// $FlowExpectedError - bad index type string, should be number
renderItem={(info: {index: string}) => <span />}
sections={sections}
/>,
<SectionList renderItem={(info: {title: string}) => <span /> } sections={sections} />,
// $FlowExpectedError - bad index type string, should be number
<SectionList renderItem={(info: {index: string}) => <span /> } sections={sections} />,
// EverythingIsFine
<SectionList
renderItem={(info: {item: {title: string}}) => <span />}
sections={sections}
/>,
<SectionList renderItem={(info: {item: {title: string}}) => <span /> } sections={sections} />,
];
},
testBadInheritedDefaultProp(): React.Element<*> {
const sections = [];
return (
<SectionList
renderItem={renderMyListItem}
sections={sections}
// $FlowExpectedError - bad windowSize type "big"
windowSize="big"
/>
);
// $FlowExpectedError - bad windowSize type "big"
return <SectionList renderItem={renderMyListItem} sections={sections} windowSize="big" />;
},
testMissingData(): React.Element<*> {
@@ -87,35 +60,24 @@ module.exports = {
},
testBadSectionsShape(): React.Element<*> {
const sections = [
{
key: 'a',
items: [
{
title: 'foo',
key: 1,
},
],
},
];
const sections = [{
key: 'a', items: [{
title: 'foo',
key: 1,
}],
}];
// $FlowExpectedError - section missing `data` field
return <SectionList renderItem={renderMyListItem} sections={sections} />;
},
testBadSectionsMetadata(): React.Element<*> {
const sections = [
{
key: 'a',
// $FlowExpectedError - section has bad meta data `fooNumber` field of type string
fooNumber: 'string',
data: [
{
title: 'foo',
key: 1,
},
],
},
];
// $FlowExpectedError - section has bad meta data `fooNumber` field of type string
const sections = [{
key: 'a', fooNumber: 'string', data: [{
title: 'foo',
key: 1,
}],
}];
return (
<SectionList
renderSectionHeader={renderMyHeader}
@@ -6,22 +6,16 @@
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @format
*/
'use strict';
jest.unmock('FillRateHelper');
const FillRateHelper = require('FillRateHelper');
let rowFramesGlobal;
const dataGlobal = [
{key: 'header'},
{key: 'a'},
{key: 'b'},
{key: 'c'},
{key: 'd'},
{key: 'footer'},
];
const dataGlobal =
[{key: 'header'}, {key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}, {key: 'footer'}];
function getFrameMetrics(index: number) {
const frame = rowFramesGlobal[dataGlobal[index].key];
return {length: frame.height, offset: frame.y, inLayout: frame.inLayout};
@@ -32,7 +26,7 @@ function computeResult({helper, props, state, scroll}): number {
return helper.computeBlankness(
{
data: dataGlobal,
getItemCount: data2 => data2.length,
getItemCount: (data2) => data2.length,
initialNumToRender: 10,
...(props || {}),
},
@@ -99,8 +93,8 @@ describe('computeBlankness', function() {
it('can handle multiple listeners and unsubscribe', function() {
const listeners = [jest.fn(), jest.fn(), jest.fn()];
const subscriptions = listeners.map(listener =>
FillRateHelper.addListener(listener),
const subscriptions = listeners.map(
(listener) => FillRateHelper.addListener(listener)
);
subscriptions[1].remove();
const helper = new FillRateHelper(getFrameMetrics);
+9 -6
View File
@@ -6,11 +6,11 @@
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @format
*/
'use strict';
jest.disableAutomock();
const React = require('React');
const ReactTestRenderer = require('react-test-renderer');
@@ -22,13 +22,16 @@ describe('FlatList', () => {
<FlatList
data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]}
renderItem={({item}) => <item value={item.key} />}
/>,
/>
);
expect(component).toMatchSnapshot();
});
it('renders empty list', () => {
const component = ReactTestRenderer.create(
<FlatList data={[]} renderItem={({item}) => <item value={item.key} />} />,
<FlatList
data={[]}
renderItem={({item}) => <item value={item.key} />}
/>
);
expect(component).toMatchSnapshot();
});
@@ -37,7 +40,7 @@ describe('FlatList', () => {
<FlatList
data={undefined}
renderItem={({item}) => <item value={item.key} />}
/>,
/>
);
expect(component).toMatchSnapshot();
});
@@ -55,7 +58,7 @@ describe('FlatList', () => {
refreshing={false}
onRefresh={jest.fn()}
renderItem={({item}) => <item value={item.id} />}
/>,
/>
);
expect(component).toMatchSnapshot();
});
+24 -29
View File
@@ -6,11 +6,11 @@
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @format
*/
'use strict';
jest.disableAutomock();
const React = require('React');
const ReactTestRenderer = require('react-test-renderer');
@@ -22,7 +22,7 @@ describe('SectionList', () => {
<SectionList
sections={[]}
renderItem={({item}) => <item v={item.key} />}
/>,
/>
);
expect(component).toMatchSnapshot();
});
@@ -32,7 +32,7 @@ describe('SectionList', () => {
sections={[{key: 's1', data: [{key: 'i1'}, {key: 'i2'}]}]}
renderItem={({item}) => <item v={item.key} />}
renderSectionHeader={() => null}
/>,
/>
);
expect(component).toMatchSnapshot();
});
@@ -40,20 +40,17 @@ describe('SectionList', () => {
const component = ReactTestRenderer.create(
<SectionList
initialNumToRender={Infinity}
ItemSeparatorComponent={props =>
<defaultItemSeparator v={propStr(props)} />}
ListEmptyComponent={props => <empty v={propStr(props)} />}
ListFooterComponent={props => <footer v={propStr(props)} />}
ListHeaderComponent={props => <header v={propStr(props)} />}
SectionSeparatorComponent={props =>
<sectionSeparator v={propStr(props)} />}
ItemSeparatorComponent={(props) => <defaultItemSeparator v={propStr(props)} />}
ListEmptyComponent={(props) => <empty v={propStr(props)} />}
ListFooterComponent={(props) => <footer v={propStr(props)} />}
ListHeaderComponent={(props) => <header v={propStr(props)} />}
SectionSeparatorComponent={(props) => <sectionSeparator v={propStr(props)} />}
sections={[
{
renderItem: props => <itemForSection1 v={propStr(props)} />,
renderItem: (props) => <itemForSection1 v={propStr(props)} />,
key: 's1',
keyExtractor: (item, index) => item.id,
ItemSeparatorComponent: props =>
<itemSeparatorForSection1 v={propStr(props)} />,
ItemSeparatorComponent: (props) => <itemSeparatorForSection1 v={propStr(props)} />,
data: [{id: 'i1s1'}, {id: 'i2s1'}],
},
{
@@ -67,10 +64,10 @@ describe('SectionList', () => {
]}
refreshing={false}
onRefresh={jest.fn()}
renderItem={props => <defaultItem v={propStr(props)} />}
renderSectionHeader={props => <sectionHeader v={propStr(props)} />}
renderSectionFooter={props => <sectionFooter v={propStr(props)} />}
/>,
renderItem={(props) => <defaultItem v={propStr(props)} />}
renderSectionHeader={(props) => <sectionHeader v={propStr(props)} />}
renderSectionFooter={(props) => <sectionFooter v={propStr(props)} />}
/>
);
expect(component).toMatchSnapshot();
});
@@ -79,9 +76,9 @@ describe('SectionList', () => {
<SectionList
sections={[{key: 's1', data: []}]}
renderItem={({item}) => <item v={item.key} />}
renderSectionHeader={props => <sectionHeader v={propStr(props)} />}
renderSectionFooter={props => <sectionFooter v={propStr(props)} />}
/>,
renderSectionHeader={(props) => <sectionHeader v={propStr(props)} />}
renderSectionFooter={(props) => <sectionFooter v={propStr(props)} />}
/>
);
expect(component).toMatchSnapshot();
});
@@ -90,18 +87,16 @@ describe('SectionList', () => {
<SectionList
sections={[{key: 's1', data: []}]}
renderItem={({item}) => <item v={item.key} />}
renderSectionFooter={props => <sectionFooter v={propStr(props)} />}
/>,
renderSectionFooter={(props) => <sectionFooter v={propStr(props)} />}
/>
);
expect(component).toMatchSnapshot();
});
});
function propStr(props) {
return Object.keys(props)
.map(k => {
const propObj = props[k] || {};
return `${k}:${propObj.key || propObj.id || props[k]}`;
})
.join(',');
return Object.keys(props).map(k => {
const propObj = props[k] || {};
return `${k}:${propObj.key || propObj.id || props[k]}`;
}).join(',');
}
@@ -6,11 +6,11 @@
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @format
*/
'use strict';
jest.unmock('ViewabilityHelper');
const ViewabilityHelper = require('ViewabilityHelper');
let rowFrames;
@@ -25,9 +25,7 @@ function createViewToken(index: number, isViewable: boolean) {
describe('computeViewableItems', function() {
it('returns all 4 entirely visible rows as viewable', function() {
const helper = new ViewabilityHelper({
viewAreaCoveragePercentThreshold: 50,
});
const helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 50});
rowFrames = {
a: {y: 0, height: 50},
b: {y: 50, height: 50},
@@ -35,337 +33,327 @@ describe('computeViewableItems', function() {
d: {y: 150, height: 50},
};
data = [{key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}];
expect(
helper.computeViewableItems(data.length, 0, 200, getFrameMetrics),
).toEqual([0, 1, 2, 3]);
expect(helper.computeViewableItems(data.length, 0, 200, getFrameMetrics))
.toEqual([0, 1, 2, 3]);
});
it('returns top 2 rows as viewable (1. entirely visible and 2. majority)', function() {
const helper = new ViewabilityHelper({
viewAreaCoveragePercentThreshold: 50,
});
rowFrames = {
a: {y: 0, height: 50},
b: {y: 50, height: 150},
c: {y: 200, height: 50},
d: {y: 250, height: 50},
};
data = [{key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}];
expect(
helper.computeViewableItems(data.length, 0, 200, getFrameMetrics),
).toEqual([0, 1]);
it(
'returns top 2 rows as viewable (1. entirely visible and 2. majority)',
function() {
const helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 50});
rowFrames = {
a: {y: 0, height: 50},
b: {y: 50, height: 150},
c: {y: 200, height: 50},
d: {y: 250, height: 50},
};
data = [{key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}];
expect(helper.computeViewableItems(data.length, 0, 200, getFrameMetrics))
.toEqual([0, 1]);
});
it('returns only 2nd row as viewable (majority)', function() {
const helper = new ViewabilityHelper({
viewAreaCoveragePercentThreshold: 50,
});
rowFrames = {
a: {y: 0, height: 50},
b: {y: 50, height: 150},
c: {y: 200, height: 50},
d: {y: 250, height: 50},
};
data = [{key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}];
expect(
helper.computeViewableItems(data.length, 25, 200, getFrameMetrics),
).toEqual([1]);
it(
'returns only 2nd row as viewable (majority)',
function() {
const helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 50});
rowFrames = {
a: {y: 0, height: 50},
b: {y: 50, height: 150},
c: {y: 200, height: 50},
d: {y: 250, height: 50},
};
data = [{key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}];
expect(helper.computeViewableItems(data.length, 25, 200, getFrameMetrics))
.toEqual([1]);
});
it('handles empty input', function() {
const helper = new ViewabilityHelper({
viewAreaCoveragePercentThreshold: 50,
});
rowFrames = {};
data = [];
expect(
helper.computeViewableItems(data.length, 0, 200, getFrameMetrics),
).toEqual([]);
it(
'handles empty input',
function() {
const helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 50});
rowFrames = {};
data = [];
expect(helper.computeViewableItems(data.length, 0, 200, getFrameMetrics))
.toEqual([]);
});
it('handles different view area coverage percent thresholds', function() {
rowFrames = {
a: {y: 0, height: 50},
b: {y: 50, height: 150},
c: {y: 200, height: 500},
d: {y: 700, height: 50},
};
data = [{key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}];
it(
'handles different view area coverage percent thresholds',
function() {
rowFrames = {
a: {y: 0, height: 50},
b: {y: 50, height: 150},
c: {y: 200, height: 500},
d: {y: 700, height: 50},
};
data = [{key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}];
let helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 0});
expect(
helper.computeViewableItems(data.length, 0, 50, getFrameMetrics),
).toEqual([0]);
expect(
helper.computeViewableItems(data.length, 1, 50, getFrameMetrics),
).toEqual([0, 1]);
expect(
helper.computeViewableItems(data.length, 199, 50, getFrameMetrics),
).toEqual([1, 2]);
expect(
helper.computeViewableItems(data.length, 250, 50, getFrameMetrics),
).toEqual([2]);
let helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 0});
expect(helper.computeViewableItems(data.length, 0, 50, getFrameMetrics))
.toEqual([0]);
expect(helper.computeViewableItems(data.length, 1, 50, getFrameMetrics))
.toEqual([0, 1]);
expect(helper.computeViewableItems(data.length, 199, 50, getFrameMetrics))
.toEqual([1, 2]);
expect(helper.computeViewableItems(data.length, 250, 50, getFrameMetrics))
.toEqual([2]);
helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 100});
expect(
helper.computeViewableItems(data.length, 0, 200, getFrameMetrics),
).toEqual([0, 1]);
expect(
helper.computeViewableItems(data.length, 1, 200, getFrameMetrics),
).toEqual([1]);
expect(
helper.computeViewableItems(data.length, 400, 200, getFrameMetrics),
).toEqual([2]);
expect(
helper.computeViewableItems(data.length, 600, 200, getFrameMetrics),
).toEqual([3]);
helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 100});
expect(helper.computeViewableItems(data.length, 0, 200, getFrameMetrics))
.toEqual([0, 1]);
expect(helper.computeViewableItems(data.length, 1, 200, getFrameMetrics))
.toEqual([1]);
expect(helper.computeViewableItems(data.length, 400, 200, getFrameMetrics))
.toEqual([2]);
expect(helper.computeViewableItems(data.length, 600, 200, getFrameMetrics))
.toEqual([3]);
helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 10});
expect(
helper.computeViewableItems(data.length, 30, 200, getFrameMetrics),
).toEqual([0, 1, 2]);
expect(
helper.computeViewableItems(data.length, 31, 200, getFrameMetrics),
).toEqual([1, 2]);
helper = new ViewabilityHelper({viewAreaCoveragePercentThreshold: 10});
expect(helper.computeViewableItems(data.length, 30, 200, getFrameMetrics))
.toEqual([0, 1, 2]);
expect(helper.computeViewableItems(data.length, 31, 200, getFrameMetrics))
.toEqual([1, 2]);
});
it('handles different item visible percent thresholds', function() {
rowFrames = {
a: {y: 0, height: 50},
b: {y: 50, height: 150},
c: {y: 200, height: 50},
d: {y: 250, height: 50},
};
data = [{key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}];
let helper = new ViewabilityHelper({itemVisiblePercentThreshold: 0});
expect(
helper.computeViewableItems(data.length, 0, 50, getFrameMetrics),
).toEqual([0]);
expect(
helper.computeViewableItems(data.length, 1, 50, getFrameMetrics),
).toEqual([0, 1]);
it(
'handles different item visible percent thresholds',
function() {
rowFrames = {
a: {y: 0, height: 50},
b: {y: 50, height: 150},
c: {y: 200, height: 50},
d: {y: 250, height: 50},
};
data = [{key: 'a'}, {key: 'b'}, {key: 'c'}, {key: 'd'}];
let helper = new ViewabilityHelper({itemVisiblePercentThreshold: 0});
expect(helper.computeViewableItems(data.length, 0, 50, getFrameMetrics))
.toEqual([0]);
expect(helper.computeViewableItems(data.length, 1, 50, getFrameMetrics))
.toEqual([0, 1]);
helper = new ViewabilityHelper({itemVisiblePercentThreshold: 100});
expect(
helper.computeViewableItems(data.length, 0, 250, getFrameMetrics),
).toEqual([0, 1, 2]);
expect(
helper.computeViewableItems(data.length, 1, 250, getFrameMetrics),
).toEqual([1, 2]);
helper = new ViewabilityHelper({itemVisiblePercentThreshold: 100});
expect(helper.computeViewableItems(data.length, 0, 250, getFrameMetrics))
.toEqual([0, 1, 2]);
expect(helper.computeViewableItems(data.length, 1, 250, getFrameMetrics))
.toEqual([1, 2]);
helper = new ViewabilityHelper({itemVisiblePercentThreshold: 10});
expect(
helper.computeViewableItems(data.length, 184, 20, getFrameMetrics),
).toEqual([1]);
expect(
helper.computeViewableItems(data.length, 185, 20, getFrameMetrics),
).toEqual([1, 2]);
expect(
helper.computeViewableItems(data.length, 186, 20, getFrameMetrics),
).toEqual([2]);
helper = new ViewabilityHelper({itemVisiblePercentThreshold: 10});
expect(helper.computeViewableItems(data.length, 184, 20, getFrameMetrics))
.toEqual([1]);
expect(helper.computeViewableItems(data.length, 185, 20, getFrameMetrics))
.toEqual([1, 2]);
expect(helper.computeViewableItems(data.length, 186, 20, getFrameMetrics))
.toEqual([2]);
});
});
describe('onUpdate', function() {
it('returns 1 visible row as viewable then scrolls away', function() {
const helper = new ViewabilityHelper();
rowFrames = {
a: {y: 0, height: 50},
};
data = [{key: 'a'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'a'}],
viewableItems: [{isViewable: true, key: 'a'}],
});
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(1); // nothing changed!
helper.onUpdate(
data.length,
100,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(2);
expect(onViewableItemsChanged.mock.calls[1][0]).toEqual({
changed: [{isViewable: false, key: 'a'}],
viewableItems: [],
});
});
it(
'returns 1 visible row as viewable then scrolls away',
function() {
const helper = new ViewabilityHelper();
rowFrames = {
a: {y: 0, height: 50},
};
data = [{key: 'a'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'a'}],
viewableItems: [{isViewable: true, key: 'a'}],
});
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(1); // nothing changed!
helper.onUpdate(
data.length,
100,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(2);
expect(onViewableItemsChanged.mock.calls[1][0]).toEqual({
changed: [{isViewable: false, key: 'a'}],
viewableItems: [],
});
},
);
it('returns 1st visible row then 1st and 2nd then just 2nd', function() {
const helper = new ViewabilityHelper();
rowFrames = {
a: {y: 0, height: 200},
b: {y: 200, height: 200},
};
data = [{key: 'a'}, {key: 'b'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'a'}],
viewableItems: [{isViewable: true, key: 'a'}],
});
helper.onUpdate(
data.length,
100,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(2);
// Both visible with 100px overlap each
expect(onViewableItemsChanged.mock.calls[1][0]).toEqual({
changed: [{isViewable: true, key: 'b'}],
viewableItems: [
{isViewable: true, key: 'a'},
{isViewable: true, key: 'b'},
],
});
helper.onUpdate(
data.length,
200,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(3);
expect(onViewableItemsChanged.mock.calls[2][0]).toEqual({
changed: [{isViewable: false, key: 'a'}],
viewableItems: [{isViewable: true, key: 'b'}],
});
});
it(
'returns 1st visible row then 1st and 2nd then just 2nd',
function() {
const helper = new ViewabilityHelper();
rowFrames = {
a: {y: 0, height: 200},
b: {y: 200, height: 200},
};
data = [{key: 'a'}, {key: 'b'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'a'}],
viewableItems: [{isViewable: true, key: 'a'}],
});
helper.onUpdate(
data.length,
100,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(2);
// Both visible with 100px overlap each
expect(onViewableItemsChanged.mock.calls[1][0]).toEqual({
changed: [{isViewable: true, key: 'b'}],
viewableItems: [{isViewable: true, key: 'a'}, {isViewable: true, key: 'b'}],
});
helper.onUpdate(
data.length,
200,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(3);
expect(onViewableItemsChanged.mock.calls[2][0]).toEqual({
changed: [{isViewable: false, key: 'a'}],
viewableItems: [{isViewable: true, key: 'b'}],
});
},
);
it('minimumViewTime delays callback', function() {
const helper = new ViewabilityHelper({
minimumViewTime: 350,
viewAreaCoveragePercentThreshold: 0,
});
rowFrames = {
a: {y: 0, height: 200},
b: {y: 200, height: 200},
};
data = [{key: 'a'}, {key: 'b'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged).not.toBeCalled();
it(
'minimumViewTime delays callback',
function() {
const helper = new ViewabilityHelper({minimumViewTime: 350, viewAreaCoveragePercentThreshold: 0});
rowFrames = {
a: {y: 0, height: 200},
b: {y: 200, height: 200},
};
data = [{key: 'a'}, {key: 'b'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged).not.toBeCalled();
jest.runAllTimers();
jest.runAllTimers();
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'a'}],
viewableItems: [{isViewable: true, key: 'a'}],
});
});
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'a'}],
viewableItems: [{isViewable: true, key: 'a'}],
});
}
);
it('minimumViewTime skips briefly visible items', function() {
const helper = new ViewabilityHelper({
minimumViewTime: 350,
viewAreaCoveragePercentThreshold: 0,
});
rowFrames = {
a: {y: 0, height: 250},
b: {y: 250, height: 200},
};
data = [{key: 'a'}, {key: 'b'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
helper.onUpdate(
data.length,
300, // scroll past item 'a'
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
it(
'minimumViewTime skips briefly visible items',
function() {
const helper = new ViewabilityHelper({minimumViewTime: 350, viewAreaCoveragePercentThreshold: 0});
rowFrames = {
a: {y: 0, height: 250},
b: {y: 250, height: 200},
};
data = [{key: 'a'}, {key: 'b'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
helper.onUpdate(
data.length,
300, // scroll past item 'a'
200,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
jest.runAllTimers();
jest.runAllTimers();
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'b'}],
viewableItems: [{isViewable: true, key: 'b'}],
});
});
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'b'}],
viewableItems: [{isViewable: true, key: 'b'}],
});
}
);
it('waitForInteraction blocks callback until interaction', function() {
const helper = new ViewabilityHelper({
waitForInteraction: true,
viewAreaCoveragePercentThreshold: 0,
});
rowFrames = {
a: {y: 0, height: 200},
b: {y: 200, height: 200},
};
data = [{key: 'a'}, {key: 'b'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
100,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged).not.toBeCalled();
it(
'waitForInteraction blocks callback until interaction',
function() {
const helper = new ViewabilityHelper({
waitForInteraction: true,
viewAreaCoveragePercentThreshold: 0,
});
rowFrames = {
a: {y: 0, height: 200},
b: {y: 200, height: 200},
};
data = [{key: 'a'}, {key: 'b'}];
const onViewableItemsChanged = jest.fn();
helper.onUpdate(
data.length,
0,
100,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged).not.toBeCalled();
helper.recordInteraction();
helper.recordInteraction();
helper.onUpdate(
data.length,
20,
100,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'a'}],
viewableItems: [{isViewable: true, key: 'a'}],
});
}
);
helper.onUpdate(
data.length,
20,
100,
getFrameMetrics,
createViewToken,
onViewableItemsChanged,
);
expect(onViewableItemsChanged.mock.calls.length).toBe(1);
expect(onViewableItemsChanged.mock.calls[0][0]).toEqual({
changed: [{isViewable: true, key: 'a'}],
viewableItems: [{isViewable: true, key: 'a'}],
});
});
});
@@ -6,12 +6,12 @@
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @format
*/
'use strict';
const {elementsThatOverlapOffsets, newRangeCount} = require('VirtualizeUtils');
jest.unmock('VirtualizeUtils');
const { elementsThatOverlapOffsets, newRangeCount } = require('VirtualizeUtils');
describe('newRangeCount', function() {
it('handles subset', function() {
@@ -46,15 +46,10 @@ describe('elementsThatOverlapOffsets', function() {
function getFrameMetrics(index: number) {
return {
length: 100,
offset: 100 * index,
offset: (100 * index),
};
}
expect(elementsThatOverlapOffsets(offsets, 100, getFrameMetrics)).toEqual([
0,
2,
3,
4,
]);
expect(elementsThatOverlapOffsets(offsets, 100, getFrameMetrics)).toEqual([0, 2, 3, 4]);
});
it('handles variable length', function() {
const offsets = [150, 250, 900];
@@ -65,9 +60,7 @@ describe('elementsThatOverlapOffsets', function() {
{offset: 850, length: 100},
{offset: 950, length: 150},
];
expect(
elementsThatOverlapOffsets(offsets, frames.length, ii => frames[ii]),
).toEqual([1, 1, 3]);
expect(elementsThatOverlapOffsets(offsets, frames.length, (ii) => frames[ii])).toEqual([1,1,3]);
});
it('handles out of bounds', function() {
const offsets = [150, 900];
@@ -76,8 +69,6 @@ describe('elementsThatOverlapOffsets', function() {
{offset: 50, length: 150},
{offset: 250, length: 100},
];
expect(
elementsThatOverlapOffsets(offsets, frames.length, ii => frames[ii]),
).toEqual([1]);
expect(elementsThatOverlapOffsets(offsets, frames.length, (ii) => frames[ii])).toEqual([1]);
});
});
@@ -6,25 +6,26 @@
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @format
*/
'use strict';
jest.disableAutomock();
const React = require('React');
const ReactTestRenderer = require('react-test-renderer');
const VirtualizedList = require('VirtualizedList');
describe('VirtualizedList', () => {
it('renders simple list', () => {
const component = ReactTestRenderer.create(
<VirtualizedList
data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]}
renderItem={({item}) => <item value={item.key} />}
getItem={(data, index) => data[index]}
getItemCount={data => data.length}
/>,
getItemCount={(data) => data.length}
/>
);
expect(component).toMatchSnapshot();
});
@@ -35,8 +36,8 @@ describe('VirtualizedList', () => {
data={[]}
renderItem={({item}) => <item value={item.key} />}
getItem={(data, index) => data[index]}
getItemCount={data => data.length}
/>,
getItemCount={(data) => data.length}
/>
);
expect(component).toMatchSnapshot();
});
@@ -47,8 +48,8 @@ describe('VirtualizedList', () => {
data={undefined}
renderItem={({item}) => <item value={item.key} />}
getItem={(data, index) => data[index]}
getItemCount={data => 0}
/>,
getItemCount={(data) => 0}
/>
);
expect(component).toMatchSnapshot();
});
@@ -61,9 +62,9 @@ describe('VirtualizedList', () => {
ListFooterComponent={() => <footer />}
ListHeaderComponent={() => <header />}
getItem={(data, index) => data[index]}
getItemCount={data => data.length}
getItemCount={(data) => data.length}
renderItem={({item}) => <item value={item.key} />}
/>,
/>
);
expect(component).toMatchSnapshot();
});
@@ -74,9 +75,9 @@ describe('VirtualizedList', () => {
data={[{key: 'hello'}]}
ListEmptyComponent={() => <empty />}
getItem={(data, index) => data[index]}
getItemCount={data => data.length}
getItemCount={(data) => data.length}
renderItem={({item}) => <item value={item.key} />}
/>,
/>
);
expect(component).toMatchSnapshot();
});
@@ -90,14 +91,13 @@ describe('VirtualizedList', () => {
ListHeaderComponent={() => <header />}
data={new Array(5).fill().map((_, ii) => ({id: String(ii)}))}
getItem={(data, index) => data[index]}
getItemCount={data => data.length}
getItemLayout={({index}) => ({length: 50, offset: index * 50})}
inverted={true}
getItemCount={(data) => data.length}
keyExtractor={(item, index) => item.id}
onRefresh={jest.fn()}
getItemLayout={({index}) => ({length: 50, offset: index * 50})}
refreshing={false}
onRefresh={jest.fn()}
renderItem={({item}) => <item value={item.id} />}
/>,
/>
);
expect(component).toMatchSnapshot();
});
@@ -109,7 +109,7 @@ describe('VirtualizedList', () => {
getItem={(data, index) => data.get('id_' + index)}
getItemCount={(data: Map) => data.size}
renderItem={({item}) => <item value={item.key} />}
/>,
/>
);
expect(component).toMatchSnapshot();
});
@@ -118,15 +118,15 @@ describe('VirtualizedList', () => {
const infos = [];
const component = ReactTestRenderer.create(
<VirtualizedList
ItemSeparatorComponent={props => <separator {...props} />}
ItemSeparatorComponent={(props) => <separator {...props} />}
data={[{key: 'i0'}, {key: 'i1'}, {key: 'i2'}]}
renderItem={info => {
renderItem={(info) => {
infos.push(info);
return <item title={info.item.key} />;
}}
getItem={(data, index) => data[index]}
getItemCount={data => data.length}
/>,
getItemCount={(data) => data.length}
/>
);
expect(component).toMatchSnapshot();
infos[1].separators.highlight();
@@ -135,28 +135,4 @@ describe('VirtualizedList', () => {
expect(component).toMatchSnapshot();
infos[1].separators.unhighlight();
});
it('handles nested lists', () => {
const component = ReactTestRenderer.create(
<VirtualizedList
data={[{key: 'outer0'}, {key: 'outer1'}]}
renderItem={outerInfo =>
<VirtualizedList
data={[
{key: outerInfo.item.key + ':inner0'},
{key: outerInfo.item.key + ':inner1'},
]}
horizontal={outerInfo.item.key === 'outer1'}
renderItem={innerInfo => {
return <item title={innerInfo.item.key} />;
}}
getItem={(data, index) => data[index]}
getItemCount={data => data.length}
/>}
getItem={(data, index) => data[index]}
getItemCount={data => data.length}
/>,
);
expect(component).toMatchSnapshot();
});
});
@@ -46,12 +46,12 @@ exports[`FlatList renders all the bells and whistles 1`] = `
refreshControl={
<RefreshControlMock
onRefresh={[Function]}
progressViewOffset={undefined}
refreshing={false}
/>
}
refreshing={false}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -61,13 +61,11 @@ exports[`FlatList renders all the bells and whistles 1`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<header />
</View>
<View
onLayout={undefined}
style={null}
>
<View
style={
@@ -90,7 +88,6 @@ exports[`FlatList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={undefined}
style={null}
>
<View
style={
@@ -113,7 +110,6 @@ exports[`FlatList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={undefined}
style={null}
>
<View
style={
@@ -132,7 +128,6 @@ exports[`FlatList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<footer />
</View>
@@ -160,6 +155,7 @@ exports[`FlatList renders empty list 1`] = `
onScrollEndDrag={[Function]}
onViewableItemsChanged={undefined}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -189,6 +185,7 @@ exports[`FlatList renders null list 1`] = `
onScrollEndDrag={[Function]}
onViewableItemsChanged={undefined}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -230,6 +227,7 @@ exports[`FlatList renders simple list 1`] = `
onScrollEndDrag={[Function]}
onViewableItemsChanged={undefined}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -238,7 +236,6 @@ exports[`FlatList renders simple list 1`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<item
value="i1"
@@ -246,7 +243,6 @@ exports[`FlatList renders simple list 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
value="i2"
@@ -254,7 +250,6 @@ exports[`FlatList renders simple list 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
value="i3"
@@ -34,6 +34,7 @@ exports[`SectionList rendering empty section headers is fine 1`] = `
onScrollEndDrag={[Function]}
onViewableItemsChanged={undefined}
renderItem={[Function]}
renderScrollComponent={[Function]}
renderSectionHeader={[Function]}
scrollEventThrottle={50}
sections={
@@ -63,11 +64,9 @@ exports[`SectionList rendering empty section headers is fine 1`] = `
<View>
<View
onLayout={[Function]}
style={null}
/>
<View
onLayout={[Function]}
style={null}
>
<item
v="i1"
@@ -75,7 +74,6 @@ exports[`SectionList rendering empty section headers is fine 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
v="i2"
@@ -83,7 +81,6 @@ exports[`SectionList rendering empty section headers is fine 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
/>
</View>
</RCTScrollView>
@@ -116,6 +113,7 @@ exports[`SectionList renders a footer when there is no data 1`] = `
onScrollEndDrag={[Function]}
onViewableItemsChanged={undefined}
renderItem={[Function]}
renderScrollComponent={[Function]}
renderSectionFooter={[Function]}
renderSectionHeader={[Function]}
scrollEventThrottle={50}
@@ -139,7 +137,6 @@ exports[`SectionList renders a footer when there is no data 1`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<sectionHeader
v="section:s1"
@@ -147,7 +144,6 @@ exports[`SectionList renders a footer when there is no data 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<sectionFooter
v="section:s1"
@@ -184,6 +180,7 @@ exports[`SectionList renders a footer when there is no data and no header 1`] =
onScrollEndDrag={[Function]}
onViewableItemsChanged={undefined}
renderItem={[Function]}
renderScrollComponent={[Function]}
renderSectionFooter={[Function]}
scrollEventThrottle={50}
sections={
@@ -206,11 +203,9 @@ exports[`SectionList renders a footer when there is no data and no header 1`] =
<View>
<View
onLayout={[Function]}
style={null}
/>
<View
onLayout={[Function]}
style={null}
>
<sectionFooter
v="section:s1"
@@ -286,12 +281,12 @@ exports[`SectionList renders all the bells and whistles 1`] = `
refreshControl={
<RefreshControlMock
onRefresh={[Function]}
progressViewOffset={undefined}
refreshing={false}
/>
}
refreshing={false}
renderItem={[Function]}
renderScrollComponent={[Function]}
renderSectionFooter={[Function]}
renderSectionHeader={[Function]}
scrollEventThrottle={50}
@@ -350,7 +345,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<header
v=""
@@ -358,7 +352,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<sectionHeader
v="section:s1"
@@ -366,7 +359,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<View>
<sectionSeparator
@@ -382,7 +374,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<View>
<itemForSection1
@@ -395,7 +386,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<sectionFooter
v="section:s1"
@@ -403,7 +393,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<sectionHeader
v="section:s2"
@@ -411,7 +400,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<View>
<sectionSeparator
@@ -427,7 +415,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<View>
<defaultItem
@@ -440,7 +427,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<sectionFooter
v="section:s2"
@@ -448,7 +434,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<sectionHeader
v="section:s3"
@@ -456,7 +441,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<View>
<sectionSeparator
@@ -472,7 +456,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<View>
<defaultItem
@@ -485,7 +468,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<sectionFooter
v="section:s3"
@@ -493,7 +475,6 @@ exports[`SectionList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<footer
v=""
@@ -523,6 +504,7 @@ exports[`SectionList renders empty list 1`] = `
onScrollEndDrag={[Function]}
onViewableItemsChanged={undefined}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
sections={Array []}
stickyHeaderIndices={Array []}
@@ -1,150 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`VirtualizedList handles nested lists 1`] = `
<RCTScrollView
data={
Array [
Object {
"key": "outer0",
},
Object {
"key": "outer1",
},
]
}
disableVirtualization={false}
getItem={[Function]}
getItemCount={[Function]}
horizontal={false}
initialNumToRender={10}
keyExtractor={[Function]}
maxToRenderPerBatch={10}
onContentSizeChange={[Function]}
onEndReachedThreshold={2}
onLayout={[Function]}
onMomentumScrollEnd={[Function]}
onScroll={[Function]}
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
windowSize={21}
>
<View>
<View
onLayout={[Function]}
style={null}
>
<View
data={
Array [
Object {
"key": "outer0:inner0",
},
Object {
"key": "outer0:inner1",
},
]
}
disableVirtualization={false}
getItem={[Function]}
getItemCount={[Function]}
horizontal={false}
initialNumToRender={10}
keyExtractor={[Function]}
maxToRenderPerBatch={10}
onContentSizeChange={[Function]}
onEndReachedThreshold={2}
onLayout={[Function]}
onMomentumScrollEnd={[Function]}
onScroll={[Function]}
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
windowSize={21}
>
<View
onLayout={[Function]}
style={null}
>
<item
title="outer0:inner0"
/>
</View>
<View
onLayout={[Function]}
style={null}
>
<item
title="outer0:inner1"
/>
</View>
</View>
</View>
<View
onLayout={[Function]}
style={null}
>
<RCTScrollView
data={
Array [
Object {
"key": "outer1:inner0",
},
Object {
"key": "outer1:inner1",
},
]
}
disableVirtualization={false}
getItem={[Function]}
getItemCount={[Function]}
horizontal={true}
initialNumToRender={10}
keyExtractor={[Function]}
maxToRenderPerBatch={10}
onContentSizeChange={[Function]}
onEndReachedThreshold={2}
onLayout={[Function]}
onMomentumScrollEnd={[Function]}
onScroll={[Function]}
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
windowSize={21}
>
<View>
<View
onLayout={[Function]}
style={null}
>
<item
title="outer1:inner0"
/>
</View>
<View
onLayout={[Function]}
style={null}
>
<item
title="outer1:inner1"
/>
</View>
</View>
</RCTScrollView>
</View>
</View>
</RCTScrollView>
`;
exports[`VirtualizedList handles separators correctly 1`] = `
<RCTScrollView
ItemSeparatorComponent={[Function]}
@@ -176,6 +31,7 @@ exports[`VirtualizedList handles separators correctly 1`] = `
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -184,7 +40,6 @@ exports[`VirtualizedList handles separators correctly 1`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<item
title="i0"
@@ -200,7 +55,6 @@ exports[`VirtualizedList handles separators correctly 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
title="i1"
@@ -216,7 +70,6 @@ exports[`VirtualizedList handles separators correctly 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
title="i2"
@@ -257,6 +110,7 @@ exports[`VirtualizedList handles separators correctly 2`] = `
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -265,7 +119,6 @@ exports[`VirtualizedList handles separators correctly 2`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<item
title="i0"
@@ -281,7 +134,6 @@ exports[`VirtualizedList handles separators correctly 2`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
title="i1"
@@ -297,7 +149,6 @@ exports[`VirtualizedList handles separators correctly 2`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
title="i2"
@@ -338,6 +189,7 @@ exports[`VirtualizedList handles separators correctly 3`] = `
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -346,7 +198,6 @@ exports[`VirtualizedList handles separators correctly 3`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<item
title="i0"
@@ -362,7 +213,6 @@ exports[`VirtualizedList handles separators correctly 3`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
title="i1"
@@ -379,7 +229,6 @@ exports[`VirtualizedList handles separators correctly 3`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
title="i2"
@@ -420,7 +269,6 @@ exports[`VirtualizedList renders all the bells and whistles 1`] = `
getItemLayout={[Function]}
horizontal={false}
initialNumToRender={10}
inverted={true}
keyExtractor={[Function]}
maxToRenderPerBatch={10}
onContentSizeChange={[Function]}
@@ -434,26 +282,14 @@ exports[`VirtualizedList renders all the bells and whistles 1`] = `
refreshControl={
<RefreshControlMock
onRefresh={[Function]}
progressViewOffset={undefined}
refreshing={false}
/>
}
refreshing={false}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
style={
Array [
Object {
"transform": Array [
Object {
"scaleY": -1,
},
],
},
undefined,
]
}
updateCellsBatchingPeriod={50}
windowSize={21}
>
@@ -461,29 +297,11 @@ exports[`VirtualizedList renders all the bells and whistles 1`] = `
<View>
<View
onLayout={[Function]}
style={
Object {
"transform": Array [
Object {
"scaleY": -1,
},
],
}
}
>
<header />
</View>
<View
onLayout={undefined}
style={
Object {
"transform": Array [
Object {
"scaleY": -1,
},
],
}
}
>
<item
value="0"
@@ -492,15 +310,6 @@ exports[`VirtualizedList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={undefined}
style={
Object {
"transform": Array [
Object {
"scaleY": -1,
},
],
}
}
>
<item
value="1"
@@ -509,15 +318,6 @@ exports[`VirtualizedList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={undefined}
style={
Object {
"transform": Array [
Object {
"scaleY": -1,
},
],
}
}
>
<item
value="2"
@@ -526,15 +326,6 @@ exports[`VirtualizedList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={undefined}
style={
Object {
"transform": Array [
Object {
"scaleY": -1,
},
],
}
}
>
<item
value="3"
@@ -543,15 +334,6 @@ exports[`VirtualizedList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={undefined}
style={
Object {
"transform": Array [
Object {
"scaleY": -1,
},
],
}
}
>
<item
value="4"
@@ -559,15 +341,6 @@ exports[`VirtualizedList renders all the bells and whistles 1`] = `
</View>
<View
onLayout={[Function]}
style={
Object {
"transform": Array [
Object {
"scaleY": -1,
},
],
}
}
>
<footer />
</View>
@@ -593,6 +366,7 @@ exports[`VirtualizedList renders empty list 1`] = `
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -623,6 +397,7 @@ exports[`VirtualizedList renders empty list with empty component 1`] = `
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -631,19 +406,16 @@ exports[`VirtualizedList renders empty list with empty component 1`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<header />
</View>
<View
onLayout={[Function]}
style={null}
>
<empty />
</View>
<View
onLayout={[Function]}
style={null}
>
<footer />
</View>
@@ -676,6 +448,7 @@ exports[`VirtualizedList renders list with empty component 1`] = `
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -684,7 +457,6 @@ exports[`VirtualizedList renders list with empty component 1`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<item
value="hello"
@@ -712,6 +484,7 @@ exports[`VirtualizedList renders null list 1`] = `
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -751,6 +524,7 @@ exports[`VirtualizedList renders simple list 1`] = `
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -759,7 +533,6 @@ exports[`VirtualizedList renders simple list 1`] = `
<View>
<View
onLayout={[Function]}
style={null}
>
<item
value="i1"
@@ -767,7 +540,6 @@ exports[`VirtualizedList renders simple list 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
value="i2"
@@ -775,7 +547,6 @@ exports[`VirtualizedList renders simple list 1`] = `
</View>
<View
onLayout={[Function]}
style={null}
>
<item
value="i3"
@@ -809,6 +580,7 @@ exports[`VirtualizedList test getItem functionality where data is not an Array 1
onScrollBeginDrag={[Function]}
onScrollEndDrag={[Function]}
renderItem={[Function]}
renderScrollComponent={[Function]}
scrollEventThrottle={50}
stickyHeaderIndices={Array []}
updateCellsBatchingPeriod={50}
@@ -817,7 +589,6 @@ exports[`VirtualizedList test getItem functionality where data is not an Array 1
<View>
<View
onLayout={[Function]}
style={null}
>
<item
value="item_0"
-39
View File
@@ -78,7 +78,6 @@ const RCTModalHostView = requireNativeComponent('RCTModalHostView', null);
* }
* ```
*/
class Modal extends React.Component {
static propTypes = {
/**
@@ -91,19 +90,6 @@ class Modal extends React.Component {
* Default is set to `none`.
*/
animationType: PropTypes.oneOf(['none', 'slide', 'fade']),
/**
* The `presentationStyle` prop controls how the modal appears (generally on larger devices such as iPad or plus-sized iPhones).
* See https://developer.apple.com/reference/uikit/uimodalpresentationstyle for details.
* @platform ios
*
* - `fullScreen` covers the screen completely
* - `pageSheet` covers portrait-width view centered (only on larger devices)
* - `formSheet` covers narrow-width view centered (only on larger devices)
* - `overFullScreen` covers the screen completely, but allows transparency
*
* Default is set to `overFullScreen` or `fullScreen` depending on `transparent` property.
*/
presentationStyle: PropTypes.oneOf(['fullScreen', 'pageSheet', 'formSheet', 'overFullScreen']),
/**
* The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background.
*/
@@ -133,7 +119,6 @@ class Modal extends React.Component {
/**
* The `supportedOrientations` prop allows the modal to be rotated to any of the specified orientations.
* On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field.
* When using `presentationStyle` of `pageSheet` or `formSheet`, this property will be ignored by iOS.
* @platform ios
*/
supportedOrientations: PropTypes.arrayOf(PropTypes.oneOf(['portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right'])),
@@ -154,21 +139,6 @@ class Modal extends React.Component {
rootTag: PropTypes.number,
};
constructor(props: Object) {
super(props);
Modal._confirmProps(props);
}
componentWillReceiveProps(nextProps: Object) {
Modal._confirmProps(nextProps);
}
static _confirmProps(props: Object) {
if (props.presentationStyle && props.presentationStyle !== 'overFullScreen' && props.transparent) {
console.warn(`Modal with '${props.presentationStyle}' presentation style and 'transparent' value is not supported.`);
}
}
render(): ?React.Element<any> {
if (this.props.visible === false) {
return null;
@@ -187,14 +157,6 @@ class Modal extends React.Component {
}
}
let presentationStyle = this.props.presentationStyle;
if (!presentationStyle) {
presentationStyle = 'fullScreen';
if (this.props.transparent) {
presentationStyle = 'overFullScreen';
}
}
const innerChildren = __DEV__ ?
( <AppContainer rootTag={this.context.rootTag}>
{this.props.children}
@@ -204,7 +166,6 @@ class Modal extends React.Component {
return (
<RCTModalHostView
animationType={animationType}
presentationStyle={presentationStyle}
transparent={this.props.transparent}
hardwareAccelerated={this.props.hardwareAccelerated}
onRequestClose={this.props.onRequestClose}
+1 -1
View File
@@ -95,7 +95,7 @@ class RCTNetworking extends NativeEventEmitter {
if (__DEV__ && !RCTNetworkingNative) {
class MissingNativeRCTNetworkingShim extends MissingNativeEventEmitterShim {
constructor() {
super('RCTNetworking', 'Networking');
super('RCTAppState', 'AppState');
}
sendRequest(...args: Array<any>) {
+1 -1
View File
@@ -63,7 +63,7 @@ class RCTNetworking extends NativeEventEmitter {
if (__DEV__ && !RCTNetworkingNative) {
class MissingNativeRCTNetworkingShim extends MissingNativeEventEmitterShim {
constructor() {
super('RCTNetworking', 'Networking');
super('RCTAppState', 'AppState');
}
sendRequest(...args: Array<any>) {
@@ -9,6 +9,8 @@
'use strict';
jest.unmock('FormData');
const FormData = require('FormData');
describe('FormData', function() {
@@ -20,6 +20,7 @@ function setRequestId(id){
}
jest
.disableAutomock()
.dontMock('event-target-shim')
.setMock('NativeModules', {
Networking: {
+1 -3
View File
@@ -7,11 +7,9 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule fetch
* @nolint
*
*/
/* eslint-disable */
'use strict';
import 'whatwg-fetch';
+91
View File
@@ -0,0 +1,91 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule RCTRenderingPerf
* @flow
*/
'use strict';
var ReactDebugTool = require('ReactDebugTool');
var ReactPerf = require('ReactPerf');
var invariant = require('fbjs/lib/invariant');
var performanceNow = require('fbjs/lib/performanceNow');
type perfModule = {
start: () => void,
stop: () => void,
}
var perfModules = [];
var enabled = false;
var lastRenderStartTime = 0;
var totalRenderDuration = 0;
var RCTRenderingPerfDevtool = {
onBeginLifeCycleTimer(debugID, timerType) {
if (timerType === 'render') {
lastRenderStartTime = performanceNow();
}
},
onEndLifeCycleTimer(debugID, timerType) {
if (timerType === 'render') {
var lastRenderDuration = performanceNow() - lastRenderStartTime;
totalRenderDuration += lastRenderDuration;
}
},
};
var RCTRenderingPerf = {
// Once perf is enabled, it stays enabled
toggle: function() {
console.log('Render perfomance measurements enabled');
enabled = true;
},
start: function() {
if (!enabled) {
return;
}
ReactPerf.start();
ReactDebugTool.addHook(RCTRenderingPerfDevtool);
perfModules.forEach((module) => module.start());
},
stop: function() {
if (!enabled) {
return;
}
ReactPerf.stop();
ReactPerf.printInclusive();
ReactPerf.printWasted();
ReactDebugTool.removeHook(RCTRenderingPerfDevtool);
console.log(`Total time spent in render(): ${totalRenderDuration.toFixed(2)} ms`);
lastRenderStartTime = 0;
totalRenderDuration = 0;
perfModules.forEach((module) => module.stop());
},
register: function(module: perfModule) {
invariant(
typeof module.start === 'function',
'Perf module should have start() function'
);
invariant(
typeof module.stop === 'function',
'Perf module should have stop() function'
);
perfModules.push(module);
}
};
module.exports = RCTRenderingPerf;
+32 -71
View File
@@ -11,8 +11,6 @@
*/
'use strict';
const invariant = require('fbjs/lib/invariant');
type RelayProfiler = {
attachProfileHandler(
name: string,
@@ -31,89 +29,52 @@ const TRACE_TAG_JSC_CALLS = 1 << 27;
let _enabled = false;
let _asyncCookie = 0;
const _markStack = [];
let _markStackIndex = -1;
// Implements a subset of User Timing API necessary for React measurements.
// https://developer.mozilla.org/en-US/docs/Web/API/User_Timing_API
const REACT_MARKER = '\u269B';
const userTimingPolyfill = {
mark(markName: string) {
if (__DEV__) {
if (_enabled) {
_markStackIndex++;
_markStack[_markStackIndex] = markName;
let systraceLabel = markName;
// Since perf measurements are a shared namespace in User Timing API,
// we prefix all React results with a React emoji.
if (markName[0] === REACT_MARKER) {
// This is coming from React.
// Removing component IDs keeps trace colors stable.
const indexOfId = markName.lastIndexOf(' (#');
const cutoffIndex = indexOfId !== -1 ? indexOfId : markName.length;
// Also cut off the emoji because it breaks Systrace
systraceLabel = markName.slice(2, cutoffIndex);
}
Systrace.beginEvent(systraceLabel);
}
}
const ReactSystraceDevtool = __DEV__ ? {
onBeforeMountComponent(debugID) {
const ReactComponentTreeHook = require('ReactGlobalSharedState').ReactComponentTreeHook;
const displayName = ReactComponentTreeHook.getDisplayName(debugID);
Systrace.beginEvent(`ReactReconciler.mountComponent(${displayName})`);
},
measure(measureName: string, startMark: ?string, endMark: ?string) {
if (__DEV__) {
if (_enabled) {
invariant(
typeof measureName === 'string' &&
typeof startMark === 'string' &&
typeof endMark === 'undefined',
'Only performance.measure(string, string) overload is supported.'
);
const topMark = _markStack[_markStackIndex];
invariant(
startMark === topMark,
'There was a mismatching performance.measure() call. ' +
'Expected "%s" but got "%s."',
topMark,
startMark,
);
_markStackIndex--;
// We can't use more descriptive measureName because Systrace doesn't
// let us edit labels post factum.
Systrace.endEvent();
}
}
onMountComponent(debugID) {
Systrace.endEvent();
},
clearMarks(markName: string) {
if (__DEV__) {
if (_enabled) {
if (_markStackIndex === -1) {
return;
}
if (markName === _markStack[_markStackIndex]) {
// React uses this for "cancelling" started measurements.
// Systrace doesn't support deleting measurements, so we just stop them.
userTimingPolyfill.measure(markName, markName);
}
}
}
onBeforeUpdateComponent(debugID) {
const ReactComponentTreeHook = require('ReactGlobalSharedState').ReactComponentTreeHook;
const displayName = ReactComponentTreeHook.getDisplayName(debugID);
Systrace.beginEvent(`ReactReconciler.updateComponent(${displayName})`);
},
clearMeasures() {
// React calls this to avoid memory leaks in browsers, but we don't keep
// measurements anyway.
onUpdateComponent(debugID) {
Systrace.endEvent();
},
};
onBeforeUnmountComponent(debugID) {
const ReactComponentTreeHook = require('ReactGlobalSharedState').ReactComponentTreeHook;
const displayName = ReactComponentTreeHook.getDisplayName(debugID);
Systrace.beginEvent(`ReactReconciler.unmountComponent(${displayName})`);
},
onUnmountComponent(debugID) {
Systrace.endEvent();
},
onBeginLifeCycleTimer(debugID, timerType) {
const ReactComponentTreeHook = require('ReactGlobalSharedState').ReactComponentTreeHook;
const displayName = ReactComponentTreeHook.getDisplayName(debugID);
Systrace.beginEvent(`${displayName}.${timerType}()`);
},
onEndLifeCycleTimer(debugID, timerType) {
Systrace.endEvent();
},
} : null;
const Systrace = {
getUserTimingPolyfill() {
return userTimingPolyfill;
},
setEnabled(enabled: boolean) {
if (_enabled !== enabled) {
if (__DEV__) {
if (enabled) {
global.nativeTraceBeginLegacy && global.nativeTraceBeginLegacy(TRACE_TAG_JSC_CALLS);
require('ReactDebugTool').addHook(ReactSystraceDevtool);
} else {
global.nativeTraceEndLegacy && global.nativeTraceEndLegacy(TRACE_TAG_JSC_CALLS);
require('ReactDebugTool').removeHook(ReactSystraceDevtool);
}
}
_enabled = enabled;
+3 -1
View File
@@ -13,6 +13,8 @@
const Promise = require('fbjs/lib/Promise.native');
const prettyFormat = require('pretty-format');
if (__DEV__) {
require('promise/setimmediate/rejection-tracking').enable({
allRejections: true,
@@ -25,7 +27,7 @@ if (__DEV__) {
message = Error.prototype.toString.call(error);
stack = error.stack;
} else {
message = require('pretty-format')(error);
message = prettyFormat(error);
}
const warning =
@@ -24,8 +24,6 @@ const NOTIF_REGISTER_EVENT = 'remoteNotificationsRegistered';
const NOTIF_REGISTRATION_ERROR_EVENT = 'remoteNotificationRegistrationError';
const DEVICE_LOCAL_NOTIF_EVENT = 'localNotificationReceived';
export type ContentAvailable = 1 | null | void;
export type FetchResult = {
NewData: string,
NoData: string,
@@ -124,11 +122,10 @@ class PushNotificationIOS {
_alert: string | Object;
_sound: string;
_category: string;
_contentAvailable: ContentAvailable;
_badgeCount: number;
_notificationId: string;
_isRemote: boolean;
_remoteNotificationCompleteCallbackCalled: boolean;
_remoteNotificationCompleteCalllbackCalled: boolean;
static FetchResult: FetchResult = {
NewData: 'UIBackgroundFetchResultNewData',
@@ -406,7 +403,7 @@ class PushNotificationIOS {
*/
constructor(nativeNotif: Object) {
this._data = {};
this._remoteNotificationCompleteCallbackCalled = false;
this._remoteNotificationCompleteCalllbackCalled = false;
this._isRemote = nativeNotif.remote;
if (this._isRemote) {
this._notificationId = nativeNotif.notificationId;
@@ -422,7 +419,6 @@ class PushNotificationIOS {
this._sound = notifVal.sound;
this._badgeCount = notifVal.badge;
this._category = notifVal.category;
this._contentAvailable = notifVal['content-available'];
} else {
this._data[notifKey] = notifVal;
}
@@ -451,10 +447,10 @@ class PushNotificationIOS {
* be throttled, to read more about it see the above documentation link.
*/
finish(fetchResult: FetchResult) {
if (!this._isRemote || !this._notificationId || this._remoteNotificationCompleteCallbackCalled) {
if (!this._isRemote || !this._notificationId || this._remoteNotificationCompleteCalllbackCalled) {
return;
}
this._remoteNotificationCompleteCallbackCalled = true;
this._remoteNotificationCompleteCalllbackCalled = true;
RCTPushNotificationManager.onFinishRemoteNotification(this._notificationId, fetchResult);
}
@@ -488,13 +484,6 @@ class PushNotificationIOS {
return this._alert;
}
/**
* Gets the content-available number from the `aps` object
*/
getContentAvailable(): ContentAvailable {
return this._contentAvailable;
}
/**
* Gets the badge count number from the `aps` object
*/
+14 -32
View File
@@ -7,7 +7,6 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule AppContainer
* @format
* @flow
*/
@@ -24,11 +23,10 @@ const View = require('View');
type Context = {
rootTag: number,
};
type Props = {|
type Props = {
children?: React.Children,
rootTag: number,
WrapperComponent?: ?ReactClass<*>,
|};
};
type State = {
inspector: ?React.Element<*>,
mainKey: number,
@@ -64,13 +62,12 @@ class AppContainer extends React.Component {
? null
: <Inspector
inspectedViewTag={ReactNative.findNodeHandle(this._mainRef)}
onRequestRerenderApp={updateInspectedViewTag => {
onRequestRerenderApp={(updateInspectedViewTag) => {
this.setState(
s => ({mainKey: s.mainKey + 1}),
() =>
updateInspectedViewTag(
ReactNative.findNodeHandle(this._mainRef),
),
(s) => ({mainKey: s.mainKey + 1}),
() => updateInspectedViewTag(
ReactNative.findNodeHandle(this._mainRef)
)
);
}}
/>;
@@ -96,30 +93,15 @@ class AppContainer extends React.Component {
}
}
let innerView = (
<View
collapsable={!this.state.inspector}
key={this.state.mainKey}
pointerEvents="box-none"
style={styles.appContainer}
ref={ref => {
this._mainRef = ref;
}}>
{this.props.children}
</View>
);
const Wrapper = this.props.WrapperComponent;
if (Wrapper) {
innerView = (
<Wrapper>
{innerView}
</Wrapper>
);
}
return (
<View style={styles.appContainer} pointerEvents="box-none">
{innerView}
<View
collapsable={!this.state.inspector}
key={this.state.mainKey}
pointerEvents="box-none"
style={styles.appContainer} ref={(ref) => {this._mainRef = ref;}}>
{this.props.children}
</View>
{yellowBox}
{this.state.inspector}
</View>
+1 -9
View File
@@ -43,7 +43,6 @@ export type Registry = {
sections: Array<string>,
runnables: Runnables,
};
export type WrapperComponentProvider = any => ReactClass<*>;
const runnables: Runnables = {};
let runCount = 1;
@@ -52,8 +51,6 @@ const tasks: Map<string, TaskProvider> = new Map();
let componentProviderInstrumentationHook: ComponentProviderInstrumentationHook =
(component: ComponentProvider) => component();
let wrapperComponentProvider: ?WrapperComponentProvider;
/**
* <div class="banner-crna-ejected">
* <h3>Project with Native Code Required</h3>
@@ -81,10 +78,6 @@ let wrapperComponentProvider: ?WrapperComponentProvider;
* `require`d.
*/
const AppRegistry = {
setWrapperComponentProvider(provider: WrapperComponentProvider) {
wrapperComponentProvider = provider;
},
registerConfig(config: Array<AppConfig>): void {
config.forEach((appConfig) => {
if (appConfig.run) {
@@ -116,8 +109,7 @@ const AppRegistry = {
renderApplication(
componentProviderInstrumentationHook(componentProvider),
appParameters.initialProps,
appParameters.rootTag,
wrapperComponentProvider && wrapperComponentProvider(appParameters),
appParameters.rootTag
)
};
if (section) {
+16 -13
View File
@@ -7,17 +7,16 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule renderApplication
* @format
* @flow
*/
'use strict';
const AppContainer = require('AppContainer');
const React = require('React');
const ReactNative = require('ReactNative');
var AppContainer = require('AppContainer');
var React = require('React');
var ReactNative = require('ReactNative');
const invariant = require('fbjs/lib/invariant');
var invariant = require('fbjs/lib/invariant');
// require BackHandler so it sets the default handler that exits the app if no listeners respond
require('BackHandler');
@@ -25,16 +24,20 @@ require('BackHandler');
function renderApplication<Props: Object>(
RootComponent: ReactClass<Props>,
initialProps: Props,
rootTag: any,
WrapperComponent?: ?ReactClass<*>,
rootTag: any
) {
invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag);
ReactNative.render(
<AppContainer rootTag={rootTag} WrapperComponent={WrapperComponent}>
<RootComponent {...initialProps} rootTag={rootTag} />
</AppContainer>,
invariant(
rootTag,
'Expect to have a valid rootTag, instead got ', rootTag
);
ReactNative.render(
<AppContainer rootTag={rootTag}>
<RootComponent
{...initialProps}
rootTag={rootTag}
/>
</AppContainer>,
rootTag
);
}
@@ -70,19 +70,13 @@ function requireNativeComponent(
viewConfig.propTypes = null;
}
let baseModuleName = viewConfig.baseModuleName;
let nativeProps = { ...viewConfig.NativeProps };
while (baseModuleName) {
const baseModule = UIManager[baseModuleName];
if (!baseModule) {
warning(false, 'Base module "%s" does not exist', baseModuleName);
baseModuleName = null;
} else {
nativeProps = { ...nativeProps, ...baseModule.NativeProps };
baseModuleName = baseModule.baseModuleName;
}
}
// The ViewConfig doesn't contain any props inherited from the view manager's
// superclass, so we manually merge in the RCTView ones. Other inheritance
// patterns are currenty not supported.
const nativeProps = {
...UIManager.RCTView.NativeProps,
...viewConfig.NativeProps,
};
for (const key in nativeProps) {
let useAttribute = false;
const attribute = {};
+1 -1
View File
@@ -1 +1 @@
5495e495de0bd15cd96a76ee0d7ca823cc09cc71
3630bf3559b72d66437187901fb5eab3f976c6a4

Some files were not shown because too many files have changed in this diff Show More