Compare commits

..

41 Commits

Author SHA1 Message Date
Satyajit Sahoo
9f553c2ad1 chore: publish
- react-navigation-animated-switch@0.6.4
 - react-navigation-drawer@2.7.0
 - react-navigation-material-bottom-tabs@2.3.4
 - @react-navigation/native@3.8.4
 - react-navigation@4.4.4
 - react-navigation-stack@2.10.3
 - react-navigation-tabs@2.11.0
2021-02-21 16:49:38 +01:00
Satyajit Sahoo
10ad9154a2 chore: sync latest stack 2021-02-21 16:46:26 +01:00
Satyajit Sahoo
fb1e8d4a07 fix: address breaking change in react-native for Linking 2021-02-21 15:45:49 +01:00
WoLewicki
5c7f892d77 feat: add activityState to other navigators 2020-12-18 13:49:05 +01:00
Satyajit Sahoo
10c6c3280f chore: publish
- react-navigation-stack@2.10.2
2020-11-22 14:15:14 +01:00
Satyajit Sahoo
e5856dae79 chore: sync latest stack 2020-11-22 14:13:52 +01:00
Satyajit Sahoo
db24639445 chore: sync latest stack 2020-11-10 21:10:31 +01:00
Satyajit Sahoo
f10543f9fc chore: publish
- react-navigation-stack@2.10.1
2020-11-04 22:48:09 +01:00
Satyajit Sahoo
a3e3fa2cfd chore: sync latest stack 2020-11-04 22:46:35 +01:00
otrepanier
ec25edd658 test: add tests to getEventManager 2020-11-04 22:34:38 +01:00
otrepanier
09d4bc24e9 test: add tests for getChildrenNavigationCache 2020-11-04 22:34:25 +01:00
Satyajit Sahoo
8d0e0f48ad chore: publish
- react-navigation-stack@2.10.0
2020-10-30 11:40:12 +01:00
Satyajit Sahoo
8411e6f764 feat: enable react-native-screens in Stack by default on iOS 2020-10-30 01:59:25 +01:00
Satyajit Sahoo
dff6c3ee7c chore: publish
- react-navigation-tabs@2.10.1
2020-10-28 15:04:08 +01:00
Satyajit Sahoo
ffe3bddcb2 fix: add bottom insets to custom height for bottom tabs 2020-10-28 15:02:54 +01:00
Satyajit Sahoo
9b55493e76 chore: publish
- react-navigation-animated-switch@0.6.3
 - @react-navigation/core@3.7.9
 - react-navigation-drawer@2.6.0
 - react-navigation-material-bottom-tabs@2.3.3
 - @react-navigation/native@3.8.3
 - react-navigation@4.4.3
 - react-navigation-stack@2.9.0
 - react-navigation-tabs@2.10.0
2020-10-26 18:19:28 +01:00
Satyajit Sahoo
ebe70f51fb fix: use react-native-iphone-x-helper in bottom-tabs navigator 2020-10-26 18:16:23 +01:00
Satyajit Sahoo
256e5aec2a chore: upgrade depenendecies 2020-10-26 18:16:22 +01:00
Wojciech Lewicki
707bea3cba feat: add detachInactiveScreens prop for bottom tabs and drawer (#8816) 2020-10-26 18:10:35 +01:00
Satyajit Sahoo
6bdc1e9e5f feat: sync latest stack 2020-10-26 16:28:59 +01:00
oltrep
b3db099a00 test: add navigation focus events tests (#8983)
This PR adds a few unit tests on the NavigationFocusEvents. It asserts that events are emitted in the expected order in different cases.
2020-10-25 02:00:19 +02:00
Satyajit Sahoo
1f5000e86b chore: publish
- react-navigation-animated-switch@0.6.2
 - @react-navigation/core@3.7.8
 - react-navigation-drawer@2.5.2
 - react-navigation-material-bottom-tabs@2.3.2
 - @react-navigation/native@3.8.2
 - react-navigation@4.4.2
 - react-navigation-stack@2.8.4
 - react-navigation-tabs@2.9.2
2020-10-02 09:16:08 +02:00
oltrep
6390aacd07 fix: NavigationEvents subscribe events on new nav state (#8920)
If the navigation prop changes, the NavigationEvents component was not
subscribing to the new value. These changes fix this problem and add a
test to verify that behavior.
2020-10-01 16:00:49 +02:00
oltrep
20e2625f35 test: fix usage of routerTestHelper back action (#8844)
Found this case were the key gets set to `{ key: null }` instead of just being `null`. Should I just call `back()` at this point? Because I don't think there is a difference between a `null` vs `undefined` key
2020-09-25 05:44:02 +02:00
Satyajit Sahoo
162e225fa4 chore: publish
- react-navigation-animated-switch@0.6.1
 - @react-navigation/core@3.7.7
 - react-navigation-drawer@2.5.1
 - react-navigation-material-bottom-tabs@2.3.1
 - @react-navigation/native@3.8.1
 - react-navigation@4.4.1
 - react-navigation-stack@2.8.3
 - react-navigation-tabs@2.9.1
2020-09-24 13:18:11 +02:00
Satyajit Sahoo
ce9991ffff chore: sync latest stack 2020-09-24 13:13:12 +02:00
Satyajit Sahoo
3bb21e256f chore: upgrade depenendecies 2020-09-24 01:06:00 +02:00
oltrep
f1a06e2f92 refactor: improve error message of StateUtils.jumpTo (#8831) 2020-09-22 11:59:20 +02:00
oltrep
c0763fca16 refactor: remove undefined assignment in switch router (#8770)
`undefined` should be left to the javascript compiler.

Originally, I opened this PR because I thought there was an inconsistency between the stack and switch routers, in the way they handle params. Turns out it's all fine, but I found this case where `undefined` is assigned to a variable and I thought I could submit a small refactor for it.
2020-09-21 15:20:36 +02:00
oltrep
62da341b67 test: move assertions into their own tests (#8703)
This change makes the tests in NavigationStateUtils more specific by splitting tests with multiple assertions.

I also grouped the tests into describe blocks by the function they test. Let me know if that's something you want or not, I can revert it if needed.

This is my first contribution, but I plan to make more of these which would mostly consists on improving tests.
2020-09-10 13:34:55 +02:00
otrepanier
09a10faa44 test: fix and enable skipped test 2020-09-10 13:33:15 +02:00
otrepanier
b9ecbd222d refactor: rename reduce accumulator variable 2020-09-10 13:32:34 +02:00
otrepanier
a57e47786c test: add KeyGenerator tests 2020-09-02 16:01:41 +02:00
otrepanier
424923019a test: document set params action for routers
These tests document the behavior of using set params action for the
different routers. Even if the action is named `SET_PARAMS`, it merges
the params with the previous one: this behavior matches the `setState`
method used in React's components.
2020-09-02 15:55:31 +02:00
Adrian Carolli
06a69f1bfd fix: don't use deprecated currentlyFocusedField (#8684)
currentlyFocusedField => currentlyFocusedInput

Fixes #8457 for 4.x because `createKeyboardAwareNavigator.js` is not inside the `main` branch.

Fixed in main here: 35d6b9e3a4
2020-09-02 15:54:45 +02:00
otrepanier
1fa2edd9f2 test: add test case for StateUtils.pop
From the current implementation of `NavigationStateUtils.pop`, a new
test case was added to document the behavior when popping when the index
is at the first route and there are multiple routes.
2020-09-02 15:42:59 +02:00
Satyajit Sahoo
fcd7d83c4c chore: sync latest stack 2020-07-11 00:05:15 +02:00
Satyajit Sahoo
4f7983134b chore: publish
- react-navigation-stack@2.8.2
2020-06-25 11:52:12 +02:00
Satyajit Sahoo
46b797dd29 fix: sync latest stack 2020-06-25 11:50:39 +02:00
Satyajit Sahoo
1a6f4a581f chore: publish
- react-navigation-stack@2.8.1
2020-06-25 03:02:46 +02:00
Satyajit Sahoo
2e7f4a6d10 fix: pop with correct key from nested stack 2020-06-25 03:01:47 +02:00
109 changed files with 9004 additions and 6079 deletions

View File

@@ -14,5 +14,8 @@
"react-native-screens" "react-native-screens"
] ]
}, },
"env": { "browser": true, "node": true } "env": { "browser": true, "node": true },
"rules": {
"import/named": "off"
}
} }

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { registerRootComponent } from 'expo'; import { registerRootComponent } from 'expo';
import { import {
Animated, Animated,

View File

@@ -7,7 +7,6 @@
"slug": "react-navigation-4-example", "slug": "react-navigation-4-example",
"description": "Demo app to showcase various functionality of React Navigation", "description": "Demo app to showcase various functionality of React Navigation",
"privacy": "public", "privacy": "public",
"sdkVersion": "36.0.0",
"platforms": [ "platforms": [
"ios", "ios",
"android", "android",

View File

@@ -8,29 +8,29 @@
"ios": "expo start --ios" "ios": "expo start --ios"
}, },
"dependencies": { "dependencies": {
"@babel/runtime": "^7.8.7", "@babel/runtime": "^7.12.1",
"@expo/vector-icons": "^10.0.6", "@expo/vector-icons": "^10.0.0",
"@react-native-community/masked-view": "0.1.7", "@react-native-community/masked-view": "0.1.10",
"expo": "^36.0.0", "expo": "^39.0.0",
"expo-asset": "~8.0.0", "expo-asset": "~8.2.0",
"expo-barcode-scanner": "^8.0.0", "expo-barcode-scanner": "~9.0.0",
"expo-blur": "~8.0.0", "expo-blur": "~8.2.0",
"expo-constants": "~8.0.0", "expo-constants": "~9.2.0",
"hoist-non-react-statics": "^3.3.1", "hoist-non-react-statics": "^3.3.1",
"react": "16.9.0", "react": "~16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-36.0.1.tar.gz", "react-native": "~0.63.2",
"react-native-gesture-handler": "~1.6.0", "react-native-gesture-handler": "~1.7.0",
"react-native-iphone-x-helper": "^1.2.1", "react-native-iphone-x-helper": "^1.3.0",
"react-native-maps": "0.27.0", "react-native-maps": "0.27.1",
"react-native-paper": "^3.4.0", "react-native-paper": "^4.0.1",
"react-native-reanimated": "~1.7.0", "react-native-reanimated": "~1.13.0",
"react-native-safe-area-context": "0.7.3", "react-native-safe-area-context": "3.1.4",
"react-native-screens": "2.3.0", "react-native-screens": "~2.10.1",
"react-native-webview": "8.1.2", "react-native-webview": "10.7.0",
"react-navigation-header-buttons": "^3.0.5" "react-navigation-header-buttons": "^6.0.0"
}, },
"devDependencies": { "devDependencies": {
"babel-plugin-module-resolver": "^4.0.0", "babel-plugin-module-resolver": "^4.0.0",
"expo-cli": "^3.13.8" "expo-cli": "^3.28.2"
} }
} }

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { import {
Alert, Alert,
TouchableOpacity, TouchableOpacity,

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { ScrollView, StyleSheet } from 'react-native'; import { ScrollView, StyleSheet } from 'react-native';
import { BorderlessButton } from 'react-native-gesture-handler'; import { BorderlessButton } from 'react-native-gesture-handler';
import { import {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { View, Text, StyleSheet, Dimensions } from 'react-native'; import { View, Text, StyleSheet, Dimensions } from 'react-native';
import { NavigationStackScreenComponent } from 'react-navigation-stack'; import { NavigationStackScreenComponent } from 'react-navigation-stack';

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { ScrollView, StyleProp, TextStyle } from 'react-native'; import { ScrollView, StyleProp, TextStyle } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons'; import { MaterialIcons } from '@expo/vector-icons';
import { import {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { Button, ScrollView, View, Text } from 'react-native'; import { Button, ScrollView, View, Text } from 'react-native';
import { createBottomTabNavigator } from 'react-navigation-tabs'; import { createBottomTabNavigator } from 'react-navigation-tabs';
import { import {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { import {
Button, Button,
Dimensions, Dimensions,

View File

@@ -1,6 +1,5 @@
import React from 'react'; import * as React from 'react';
import { import {
AccessibilityStates,
Platform, Platform,
StyleSheet, StyleSheet,
Text, Text,
@@ -88,11 +87,9 @@ export default class Button extends React.Component<ButtonProps> {
buttonStyles.push({ backgroundColor: color }); buttonStyles.push({ backgroundColor: color });
} }
} }
const accessibilityStates: AccessibilityStates[] = [];
if (disabled) { if (disabled) {
buttonStyles.push(styles.buttonDisabled); buttonStyles.push(styles.buttonDisabled);
textStyles.push(styles.textDisabled); textStyles.push(styles.textDisabled);
accessibilityStates.push('disabled');
} }
const formattedTitle = const formattedTitle =
Platform.OS === 'android' ? title.toUpperCase() : title; Platform.OS === 'android' ? title.toUpperCase() : title;
@@ -100,7 +97,7 @@ export default class Button extends React.Component<ButtonProps> {
<TouchableOpacity <TouchableOpacity
accessibilityLabel={accessibilityLabel} accessibilityLabel={accessibilityLabel}
accessibilityRole="button" accessibilityRole="button"
accessibilityStates={accessibilityStates} accessibilityState={{ disabled }}
testID={testID} testID={testID}
disabled={disabled} disabled={disabled}
onPress={onPress} onPress={onPress}

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { Platform, StyleSheet, View } from 'react-native'; import { Platform, StyleSheet, View } from 'react-native';
import BaseButton, { ButtonProps } from './Button'; import BaseButton, { ButtonProps } from './Button';

View File

@@ -23,13 +23,13 @@ class NavigationAwareScrollViewBase extends React.Component<{
componentDidMount() { componentDidMount() {
this.subscription = this.props.navigation.addListener('refocus', () => { this.subscription = this.props.navigation.addListener('refocus', () => {
if (this.props.navigation.isFocused()) { if (this.props.navigation.isFocused()) {
this.root.current && this.root.current.scrollTo({ x: 0, y: 0 }); this.root.current?.scrollTo({ x: 0, y: 0 });
} }
}); });
} }
componentWillUnmount() { componentWillUnmount() {
this.subscription && this.subscription.remove(); this.subscription?.remove();
} }
setNativeProps(props: ScrollViewProperties) { setNativeProps(props: ScrollViewProperties) {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { Button, ScrollView, StyleSheet, View } from 'react-native'; import { Button, ScrollView, StyleSheet, View } from 'react-native';
import { import {
ThemeColors, ThemeColors,

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { Text, View } from 'react-native'; import { Text, View } from 'react-native';
import { Themed } from 'react-navigation'; import { Themed } from 'react-navigation';
import { import {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { Text } from 'react-native'; import { Text } from 'react-native';
import { import {
Themed, Themed,

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { ScrollView, StatusBar } from 'react-native'; import { ScrollView, StatusBar } from 'react-native';
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons';
import { import {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { import {
ScrollView, ScrollView,
StatusBar, StatusBar,

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { Button, ScrollView } from 'react-native'; import { Button, ScrollView } from 'react-native';
import { Themed, SafeAreaView } from 'react-navigation'; import { Themed, SafeAreaView } from 'react-navigation';
import { import {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { MaterialIcons } from '@expo/vector-icons'; import { MaterialIcons } from '@expo/vector-icons';
import { createDrawerNavigator } from 'react-navigation-drawer'; import { createDrawerNavigator } from 'react-navigation-drawer';
import SimpleTabs from './SimpleTabs'; import SimpleTabs from './SimpleTabs';

View File

@@ -25,28 +25,28 @@
"example": "yarn --cwd example" "example": "yarn --cwd example"
}, },
"devDependencies": { "devDependencies": {
"@babel/plugin-proposal-class-properties": "^7.8.3", "@babel/plugin-proposal-class-properties": "^7.12.1",
"@babel/plugin-proposal-optional-chaining": "^7.8.3", "@babel/plugin-proposal-optional-chaining": "^7.12.1",
"@babel/preset-env": "^7.8.7", "@babel/preset-env": "^7.12.1",
"@babel/preset-react": "^7.8.3", "@babel/preset-react": "^7.12.1",
"@babel/preset-typescript": "^7.8.3", "@babel/preset-typescript": "^7.12.1",
"@babel/runtime": "^7.8.7", "@babel/runtime": "^7.12.1",
"@commitlint/config-conventional": "^8.3.4", "@commitlint/config-conventional": "^11.0.0",
"@types/jest": "^25.1.4", "@types/jest": "^26.0.15",
"babel-jest": "^25.2.3", "babel-jest": "^26.6.1",
"commitlint": "^8.3.5", "commitlint": "^11.0.0",
"core-js": "^3.6.4", "core-js": "^3.6.5",
"eslint": "^7.0.0", "eslint": "^7.12.0",
"eslint-config-satya164": "^3.1.7", "eslint-config-satya164": "^3.1.8",
"husky": "^4.2.1", "husky": "^4.2.5",
"jest": "^25.1.0", "jest": "^26.6.1",
"lerna": "^3.20.2", "lerna": "^3.22.1",
"prettier": "^2.0.5", "prettier": "^2.1.2",
"typescript": "^3.9.5" "typescript": "^4.0.3"
}, },
"resolutions": { "resolutions": {
"react": "~16.9.0", "react": "~16.13.1",
"react-native": "~0.61.5" "react-native": "~0.63.2"
}, },
"husky": { "husky": {
"hooks": { "hooks": {

View File

@@ -3,6 +3,38 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [0.6.4](https://github.com/react-navigation/react-navigation/compare/react-navigation-animated-switch@0.6.3...react-navigation-animated-switch@0.6.4) (2021-02-21)
**Note:** Version bump only for package react-navigation-animated-switch
## [0.6.3](https://github.com/react-navigation/react-navigation/compare/react-navigation-animated-switch@0.6.2...react-navigation-animated-switch@0.6.3) (2020-10-26)
**Note:** Version bump only for package react-navigation-animated-switch
## [0.6.2](https://github.com/react-navigation/react-navigation/compare/react-navigation-animated-switch@0.6.1...react-navigation-animated-switch@0.6.2) (2020-10-02)
**Note:** Version bump only for package react-navigation-animated-switch
## [0.6.1](https://github.com/react-navigation/react-navigation/compare/react-navigation-animated-switch@0.6.0...react-navigation-animated-switch@0.6.1) (2020-09-24)
**Note:** Version bump only for package react-navigation-animated-switch
# [0.6.0](https://github.com/react-navigation/react-navigation/compare/react-navigation-animated-switch@0.5.12...react-navigation-animated-switch@0.6.0) (2020-06-25) # [0.6.0](https://github.com/react-navigation/react-navigation/compare/react-navigation-animated-switch@0.5.12...react-navigation-animated-switch@0.6.0) (2020-06-25)

View File

@@ -1,6 +1,6 @@
{ {
"name": "react-navigation-animated-switch", "name": "react-navigation-animated-switch",
"version": "0.6.0", "version": "0.6.4",
"description": "Animated switch for React Navigation", "description": "Animated switch for React Navigation",
"main": "lib/commonjs/index.js", "main": "lib/commonjs/index.js",
"react-native": "lib/module/index.js", "react-native": "lib/module/index.js",
@@ -21,15 +21,15 @@
"access": "public" "access": "public"
}, },
"devDependencies": { "devDependencies": {
"@react-native-community/bob": "0.10.0", "@react-native-community/bob": "0.16.2",
"@types/react": "16.9.23", "@types/react": "16.9.53",
"@types/react-native": "0.61.22", "@types/react-native": "0.63.30",
"del-cli": "^3.0.0", "del-cli": "^3.0.1",
"react": "~16.9.0", "react": "~16.13.1",
"react-native": "~0.61.5", "react-native": "~0.63.2",
"react-native-reanimated": "~1.7.0", "react-native-reanimated": "~1.13.0",
"react-navigation": "^4.4.0", "react-navigation": "^4.4.4",
"typescript": "^3.9.5" "typescript": "^4.0.3"
}, },
"peerDependencies": { "peerDependencies": {
"react": "*", "react": "*",

View File

@@ -3,6 +3,33 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [3.7.9](https://github.com/react-navigation/react-navigation-core/compare/@react-navigation/core@3.7.8...@react-navigation/core@3.7.9) (2020-10-26)
**Note:** Version bump only for package @react-navigation/core
## [3.7.8](https://github.com/react-navigation/react-navigation-core/compare/@react-navigation/core@3.7.7...@react-navigation/core@3.7.8) (2020-10-02)
### Bug Fixes
* NavigationEvents subscribe events on new nav state ([#8920](https://github.com/react-navigation/react-navigation-core/issues/8920)) ([6390aac](https://github.com/react-navigation/react-navigation-core/commit/6390aacd07fd647d925dfec842a766c8aad5272f))
## [3.7.7](https://github.com/react-navigation/react-navigation-core/compare/@react-navigation/core@3.7.6...@react-navigation/core@3.7.7) (2020-09-24)
**Note:** Version bump only for package @react-navigation/core
## [3.7.6](https://github.com/react-navigation/react-navigation-core/compare/@react-navigation/core@3.7.5...@react-navigation/core@3.7.6) (2020-04-30) ## [3.7.6](https://github.com/react-navigation/react-navigation-core/compare/@react-navigation/core@3.7.5...@react-navigation/core@3.7.6) (2020-04-30)

View File

@@ -1,6 +1,6 @@
{ {
"name": "@react-navigation/core", "name": "@react-navigation/core",
"version": "3.7.6", "version": "3.7.9",
"description": "Core utilities for the react-navigation framework", "description": "Core utilities for the react-navigation framework",
"main": "lib/commonjs/index.js", "main": "lib/commonjs/index.js",
"react-native": "lib/module/index.js", "react-native": "lib/module/index.js",
@@ -37,16 +37,16 @@
"dependencies": { "dependencies": {
"hoist-non-react-statics": "^3.3.2", "hoist-non-react-statics": "^3.3.2",
"path-to-regexp": "^1.8.0", "path-to-regexp": "^1.8.0",
"query-string": "^6.11.1", "query-string": "^6.13.6",
"react-is": "^16.13.0" "react-is": "^16.13.0"
}, },
"devDependencies": { "devDependencies": {
"@react-native-community/bob": "^0.10.0", "@react-native-community/bob": "^0.16.2",
"del-cli": "^3.0.0", "del-cli": "^3.0.1",
"react": "~16.9.0", "react": "~16.13.1",
"react-native": "~0.61.5", "react-native": "~0.63.2",
"react-native-testing-library": "^1.12.0", "react-native-testing-library": "^6.0.0",
"react-test-renderer": "^16.9.2" "react-test-renderer": "~16.13.1"
}, },
"peerDependencies": { "peerDependencies": {
"react": "*" "react": "*"

View File

@@ -93,6 +93,7 @@ const StateUtils = {
*/ */
jumpTo(state, key) { jumpTo(state, key) {
const index = StateUtils.indexOf(state, key); const index = StateUtils.indexOf(state, key);
invariant(index !== -1, 'attempt to jump to unknown key "%s"', key);
return StateUtils.jumpToIndex(state, index); return StateUtils.jumpToIndex(state, index);
}, },

View File

@@ -1,6 +1,6 @@
/* eslint-disable react/sort-comp */ /* eslint-disable react/sort-comp */
import React from 'react'; import * as React from 'react';
import { NavigationActions, getNavigation, NavigationProvider } from '../index'; import { NavigationActions, getNavigation, NavigationProvider } from '../index';
export default function createNavigationContainer(Component) { export default function createNavigationContainer(Component) {

View File

@@ -3,32 +3,51 @@ import NavigationStateUtils from '../StateUtils';
const routeName = 'Anything'; const routeName = 'Anything';
describe('StateUtils', () => { describe('StateUtils', () => {
// Getters describe('get', () => {
it('gets route', () => { it('gets route', () => {
const state = { const state = {
index: 0, index: 0,
routes: [{ key: 'a', routeName }], routes: [{ key: 'a', routeName }],
isTransitioning: false, isTransitioning: false,
}; };
expect(NavigationStateUtils.get(state, 'a')).toEqual({ expect(NavigationStateUtils.get(state, 'a')).toEqual({
key: 'a', key: 'a',
routeName, routeName,
});
});
it('returns null when getting an unknown route', () => {
const state = {
index: 0,
routes: [{ key: 'a', routeName }],
isTransitioning: false,
};
expect(NavigationStateUtils.get(state, 'b')).toBe(null);
}); });
expect(NavigationStateUtils.get(state, 'b')).toBe(null);
}); });
it('gets route index', () => { describe('indexOf', () => {
const state = { it('gets route index', () => {
index: 1, const state = {
routes: [ index: 1,
{ key: 'a', routeName }, routes: [
{ key: 'b', routeName }, { key: 'a', routeName },
], { key: 'b', routeName },
isTransitioning: false, ],
}; isTransitioning: false,
expect(NavigationStateUtils.indexOf(state, 'a')).toBe(0); };
expect(NavigationStateUtils.indexOf(state, 'b')).toBe(1); expect(NavigationStateUtils.indexOf(state, 'a')).toBe(0);
expect(NavigationStateUtils.indexOf(state, 'c')).toBe(-1); expect(NavigationStateUtils.indexOf(state, 'b')).toBe(1);
});
it('returns -1 when getting an unknown route index', () => {
const state = {
index: 1,
routes: [{ key: 'a', routeName }],
isTransitioning: false,
};
expect(NavigationStateUtils.indexOf(state, 'b')).toBe(-1);
});
}); });
it('has a route', () => { it('has a route', () => {
@@ -44,303 +63,390 @@ describe('StateUtils', () => {
expect(NavigationStateUtils.has(state, 'c')).toBe(false); expect(NavigationStateUtils.has(state, 'c')).toBe(false);
}); });
// Push describe('push', () => {
it('pushes a route', () => { it('pushes a route', () => {
const state = { const state = {
index: 0, index: 0,
routes: [{ key: 'a', routeName }], routes: [{ key: 'a', routeName }],
isTransitioning: false, isTransitioning: false,
}; };
const newState = { const newState = {
index: 1, index: 1,
isTransitioning: false, isTransitioning: false,
routes: [ routes: [
{ key: 'a', routeName }, { key: 'a', routeName },
{ key: 'b', routeName }, { key: 'b', routeName },
],
};
expect(NavigationStateUtils.push(state, { key: 'b', routeName })).toEqual(
newState
);
});
it('does not push duplicated route', () => {
const state = {
index: 0,
routes: [{ key: 'a', routeName }],
isTransitioning: false,
};
expect(() =>
NavigationStateUtils.push(state, { key: 'a', routeName })
).toThrow('should not push route with duplicated key a');
});
// Pop
it('pops route', () => {
const state = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 0,
routes: [{ key: 'a', routeName }],
isTransitioning: false,
};
expect(NavigationStateUtils.pop(state)).toEqual(newState);
});
it('does not pop route if not applicable', () => {
const state = {
index: 0,
routes: [{ key: 'a', routeName }],
isTransitioning: false,
};
expect(NavigationStateUtils.pop(state)).toBe(state);
});
// Jump
it('jumps to new index', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.jumpToIndex(state, 0)).toBe(state);
expect(NavigationStateUtils.jumpToIndex(state, 1)).toEqual(newState);
});
it('throws if jumps to invalid index', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(() => NavigationStateUtils.jumpToIndex(state, 2)).toThrow(
'invalid index 2 to jump to'
);
});
it('jumps to new key', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.jumpTo(state, 'a')).toBe(state);
expect(NavigationStateUtils.jumpTo(state, 'b')).toEqual(newState);
});
it('throws if jumps to invalid key', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(() => NavigationStateUtils.jumpTo(state, 'c')).toThrow(
'invalid index -1 to jump to'
);
});
it('move backwards', () => {
const state = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.back(state)).toEqual(newState);
expect(NavigationStateUtils.back(newState)).toBe(newState);
});
it('move forwards', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.forward(state)).toEqual(newState);
expect(NavigationStateUtils.forward(newState)).toBe(newState);
});
// Replace
it('Replaces by key', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'c', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.replaceAt(state, 'b', { key: 'c', routeName })
).toEqual(newState);
});
it('Replaces by index', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'c', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.replaceAtIndex(state, 1, { key: 'c', routeName })
).toEqual(newState);
});
it('Returns the state with updated index if route is unchanged but index changes', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.replaceAtIndex(state, 1, state.routes[1])
).toEqual({ ...state, index: 1 });
});
// Reset
it('Resets routes', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'x', routeName },
{ key: 'y', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.reset(state, [
{ key: 'x', routeName },
{ key: 'y', routeName },
])
).toEqual(newState);
expect(() => {
NavigationStateUtils.reset(state, []);
}).toThrow('invalid routes to replace');
});
it('Resets routes with index', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 0,
routes: [
{ key: 'x', routeName },
{ key: 'y', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.reset(
state,
[
{ key: 'x', routeName },
{ key: 'y', routeName },
], ],
0 };
) expect(NavigationStateUtils.push(state, { key: 'b', routeName })).toEqual(
).toEqual(newState); newState
expect(() => {
NavigationStateUtils.reset(
state,
[
{ key: 'x', routeName },
{ key: 'y', routeName },
],
100
); );
}).toThrow('invalid index 100 to reset'); });
it('does not push duplicated route', () => {
const state = {
index: 0,
routes: [{ key: 'a', routeName }],
isTransitioning: false,
};
expect(() =>
NavigationStateUtils.push(state, { key: 'a', routeName })
).toThrow('should not push route with duplicated key a');
});
});
describe('pop', () => {
it('pops route', () => {
const state = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 0,
routes: [{ key: 'a', routeName }],
isTransitioning: false,
};
expect(NavigationStateUtils.pop(state)).toEqual(newState);
});
it('does not pop route if not applicable with single route config', () => {
const state = {
index: 0,
routes: [{ key: 'a', routeName }],
isTransitioning: false,
};
expect(NavigationStateUtils.pop(state)).toBe(state);
});
it('does not pop route if not applicable with multiple route config', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.pop(state)).toBe(state);
});
});
describe('jumpToIndex', () => {
it('jumps to new index', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.jumpToIndex(state, 0)).toBe(state);
expect(NavigationStateUtils.jumpToIndex(state, 1)).toEqual(newState);
});
it('throws if jumps to invalid index', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(() => NavigationStateUtils.jumpToIndex(state, 2)).toThrow(
'invalid index 2 to jump to'
);
});
});
describe('jumpTo', () => {
it('jumps to the current key', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.jumpTo(state, 'a')).toBe(state);
});
it('jumps to new key', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.jumpTo(state, 'b')).toEqual(newState);
});
it('throws if jumps to invalid key', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(() => NavigationStateUtils.jumpTo(state, 'c')).toThrow(
'attempt to jump to unknown key "c"'
);
});
});
describe('back', () => {
it('move backwards', () => {
const state = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.back(state)).toEqual(newState);
});
it('does not move backwards when the active route is the first', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.back(state)).toBe(state);
});
});
describe('forward', () => {
it('move forwards', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.forward(state)).toEqual(newState);
});
it('does not move forward when active route is already the top-most', () => {
const state = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(NavigationStateUtils.forward(state)).toEqual(state);
});
});
describe('replace', () => {
it('Replaces by key', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'c', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.replaceAt(state, 'b', { key: 'c', routeName })
).toEqual(newState);
});
it('Replaces by index', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'a', routeName },
{ key: 'c', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.replaceAtIndex(state, 1, { key: 'c', routeName })
).toEqual(newState);
});
it('Returns the state with updated index if route is unchanged but index changes', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.replaceAtIndex(state, 1, state.routes[1])
).toEqual({ ...state, index: 1 });
});
});
describe('reset', () => {
it('Resets routes', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 1,
routes: [
{ key: 'x', routeName },
{ key: 'y', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.reset(state, [
{ key: 'x', routeName },
{ key: 'y', routeName },
])
).toEqual(newState);
});
it('throws when attempting to set empty state', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(() => {
NavigationStateUtils.reset(state, []);
}).toThrow('invalid routes to replace');
});
it('Resets routes with index', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
const newState = {
index: 0,
routes: [
{ key: 'x', routeName },
{ key: 'y', routeName },
],
isTransitioning: false,
};
expect(
NavigationStateUtils.reset(
state,
[
{ key: 'x', routeName },
{ key: 'y', routeName },
],
0
)
).toEqual(newState);
expect(() => {
NavigationStateUtils.reset(
state,
[
{ key: 'x', routeName },
{ key: 'y', routeName },
],
100
);
}).toThrow('invalid index 100 to reset');
});
it('throws when attempting to set an out of range route index', () => {
const state = {
index: 0,
routes: [
{ key: 'a', routeName },
{ key: 'b', routeName },
],
isTransitioning: false,
};
expect(() => {
NavigationStateUtils.reset(
state,
[
{ key: 'x', routeName },
{ key: 'y', routeName },
],
100
);
}).toThrow('invalid index 100 to reset');
});
}); });
}); });

View File

@@ -0,0 +1,60 @@
import getChildrenNavigationCache from '../getChildrenNavigationCache';
it('should return empty table if navigation arg not provided', () => {
expect(getChildrenNavigationCache()._childrenNavigation).toBeUndefined();
});
it('should populate navigation._childrenNavigation as a side-effect', () => {
const navigation = {
state: {
routes: [{ key: 'one' }],
},
};
const result = getChildrenNavigationCache(navigation);
expect(result).toBeDefined();
expect(navigation._childrenNavigation).toBe(result);
});
it('should delete children cache keys that are no longer valid', () => {
const navigation = {
state: {
routes: [{ key: 'one' }, { key: 'two' }, { key: 'three' }],
},
_childrenNavigation: {
one: {},
two: {},
three: {},
four: {},
},
};
const result = getChildrenNavigationCache(navigation);
expect(result).toEqual({
one: {},
two: {},
three: {},
});
});
it('should not delete children cache keys if in transitioning state', () => {
const navigation = {
state: {
routes: [{ key: 'one' }, { key: 'two' }, { key: 'three' }],
isTransitioning: true,
},
_childrenNavigation: {
one: {},
two: {},
three: {},
four: {},
},
};
const result = getChildrenNavigationCache(navigation);
expect(result).toEqual({
one: {},
two: {},
three: {},
four: {},
});
});

View File

@@ -0,0 +1,48 @@
import getEventManager from '../getEventManager';
const TARGET = 'target';
it('calls listeners to emitted event', () => {
const eventManager = getEventManager(TARGET);
const callback = jest.fn();
eventManager.addListener('didFocus', callback);
eventManager.emit('didFocus');
expect(callback).toHaveBeenCalledTimes(1);
});
it('does not call listeners connected to a different event', () => {
const eventManager = getEventManager(TARGET);
const callback = jest.fn();
eventManager.addListener('didFocus', callback);
eventManager.emit('didBlur');
expect(callback).not.toHaveBeenCalled();
});
it('does not call removed listeners', () => {
const eventManager = getEventManager(TARGET);
const callback = jest.fn();
const { remove } = eventManager.addListener('didFocus', callback);
eventManager.emit('didFocus');
expect(callback).toHaveBeenCalled();
remove();
eventManager.emit('didFocus');
expect(callback).toHaveBeenCalledTimes(1);
});
it('calls the listeners with the given payload', () => {
const eventManager = getEventManager(TARGET);
const callback = jest.fn();
eventManager.addListener('didFocus', callback);
const payload = { foo: 0 };
eventManager.emit('didFocus', payload);
expect(callback).toHaveBeenCalledWith(payload);
});

View File

@@ -1,4 +1,5 @@
import getNavigation from '../getNavigation'; import getNavigation from '../getNavigation';
import * as NavigationActions from '../NavigationActions';
it('getNavigation provides default action helpers', () => { it('getNavigation provides default action helpers', () => {
const router = { const router = {
@@ -22,12 +23,11 @@ it('getNavigation provides default action helpers', () => {
topNav.navigate('GreatRoute'); topNav.navigate('GreatRoute');
expect(dispatch.mock.calls.length).toBe(1); expect(dispatch.mock.calls.length).toBe(1);
expect(dispatch.mock.calls[0][0].type).toBe('Navigation/NAVIGATE'); expect(dispatch.mock.calls[0][0].type).toBe(NavigationActions.NAVIGATE);
expect(dispatch.mock.calls[0][0].routeName).toBe('GreatRoute'); expect(dispatch.mock.calls[0][0].routeName).toBe('GreatRoute');
}); });
// eslint-disable-next-line jest/no-disabled-tests it('getNavigation provides router action helpers', () => {
it.skip('getNavigation provides router action helpers', () => {
const router = { const router = {
getActionCreators: () => ({ getActionCreators: () => ({
foo: (bar) => ({ type: 'FooBarAction', bar }), foo: (bar) => ({ type: 'FooBarAction', bar }),
@@ -39,7 +39,8 @@ it.skip('getNavigation provides router action helpers', () => {
const dispatch = jest.fn(); const dispatch = jest.fn();
const topNav = getNavigation( let topNav;
topNav = getNavigation(
router, router,
{}, {},
dispatch, dispatch,

View File

@@ -1,5 +1,5 @@
export default function getChildRouter(router: any, routeName: string) { export default function getChildRouter(router: any, routeName: string) {
if (router.childRouters && router.childRouters[routeName]) { if (router.childRouters?.[routeName]) {
return router.childRouters[routeName]; return router.childRouters[routeName];
} }

View File

@@ -36,7 +36,7 @@ function createNavigator(NavigatorView, router, navigationConfig) {
); );
} }
const descriptors = routes.reduce((acc, route) => { const descriptors = routes.reduce((descriptors, route) => {
if ( if (
prevDescriptors && prevDescriptors &&
prevDescriptors[route.key] && prevDescriptors[route.key] &&
@@ -44,8 +44,8 @@ function createNavigator(NavigatorView, router, navigationConfig) {
screenProps === currentState.screenProps && screenProps === currentState.screenProps &&
currentState.themeContext === currentState.theme currentState.themeContext === currentState.theme
) { ) {
acc[route.key] = prevDescriptors[route.key]; descriptors[route.key] = prevDescriptors[route.key];
return acc; return descriptors;
} }
const getComponent = router.getComponentForRouteName.bind( const getComponent = router.getComponentForRouteName.bind(
null, null,
@@ -57,14 +57,14 @@ function createNavigator(NavigatorView, router, navigationConfig) {
screenProps, screenProps,
currentState.themeContext currentState.themeContext
); );
acc[route.key] = { descriptors[route.key] = {
key: route.key, key: route.key,
getComponent, getComponent,
options, options,
state: route, state: route,
navigation: childNavigation, navigation: childNavigation,
}; };
return acc; return descriptors;
}, {}); }, {});
return { descriptors, screenProps, theme: state.themeContext }; return { descriptors, screenProps, theme: state.themeContext };

View File

@@ -19,7 +19,7 @@ export default (routeConfigs, config = {}) => {
const getCustomActionCreators = const getCustomActionCreators =
config.getCustomActionCreators || defaultActionCreators; config.getCustomActionCreators || defaultActionCreators;
const initialRouteParams = config.initialRouteParams; const { initialRouteParams } = config;
const initialRouteName = config.initialRouteName || order[0]; const initialRouteName = config.initialRouteName || order[0];
const backBehavior = config.backBehavior || 'none'; const backBehavior = config.backBehavior || 'none';
const resetOnBlur = config.hasOwnProperty('resetOnBlur') const resetOnBlur = config.hasOwnProperty('resetOnBlur')
@@ -59,7 +59,7 @@ export default (routeConfigs, config = {}) => {
function resetChildRoute(routeName) { function resetChildRoute(routeName) {
let initialParams = let initialParams =
routeName === initialRouteName ? initialRouteParams : undefined; routeName === initialRouteName ? initialRouteParams : null;
// note(brentvatne): merging initialRouteParams *on top* of default params // note(brentvatne): merging initialRouteParams *on top* of default params
// on the route seems incorrect but it's consistent with existing behavior // on the route seems incorrect but it's consistent with existing behavior
// in stackrouter // in stackrouter
@@ -71,13 +71,13 @@ export default (routeConfigs, config = {}) => {
...childRouter.getStateForAction(childAction), ...childRouter.getStateForAction(childAction),
key: routeName, key: routeName,
routeName, routeName,
params, ...(params ? { params } : {}),
}; };
} }
return { return {
key: routeName, key: routeName,
routeName, routeName,
params, ...(params ? { params } : {}),
}; };
} }

View File

@@ -0,0 +1,12 @@
import { _TESTING_ONLY_normalize_keys, generateKey } from '../KeyGenerator';
it('should generate a new string key when called', () => {
_TESTING_ONLY_normalize_keys();
expect(generateKey()).toBe('id-0');
expect(generateKey()).toBe('id-1');
});
it('should generate unique string keys without being normalized', () => {
expect(generateKey()).not.toBe(generateKey());
});

View File

@@ -1,6 +1,6 @@
/* eslint no-shadow:0, react/no-multi-comp:0, react/display-name:0 */ /* eslint no-shadow:0, react/no-multi-comp:0, react/display-name:0 */
import React from 'react'; import * as React from 'react';
import SwitchRouter from '../SwitchRouter'; import SwitchRouter from '../SwitchRouter';
import StackRouter from '../StackRouter'; import StackRouter from '../StackRouter';

View File

@@ -1,6 +1,6 @@
/* eslint react/no-multi-comp:0, react/display-name:0 */ /* eslint react/no-multi-comp:0, react/display-name:0 */
import React from 'react'; import * as React from 'react';
import StackRouter from '../StackRouter'; import StackRouter from '../StackRouter';
import TabRouter from '../TabRouter'; import TabRouter from '../TabRouter';
@@ -114,6 +114,51 @@ Object.keys(ROUTERS).forEach((routerName) => {
); );
expect(state0.routes[state0.index].params.foo).toEqual(42); expect(state0.routes[state0.index].params.foo).toEqual(42);
}); });
it('merges existing params when set params on existing state', () => {
const Screen = () => <div />;
const router = Router({
Foo: {
screen: Screen,
params: { a: 1 },
},
});
const key = 'Foo';
const state = router.getStateForAction({
type: NavigationActions.INIT,
key,
});
expect(state).toMatchObject({
index: 0,
routes: [{ key, params: { a: 1 } }],
});
const newState = router.getStateForAction(
NavigationActions.setParams({ key, params: { b: 2 } }),
state
);
expect(newState.routes[newState.index].params).toEqual({ a: 1, b: 2 });
});
it('merges params when setting params during init', () => {
const Screen = () => <div />;
const router = Router({
Foo: {
screen: Screen,
params: { a: 1 },
},
});
const newState = router.getStateForAction(
NavigationActions.setParams({ key: 'Foo', params: { b: 2 } })
);
expect(newState.routes[newState.index].params).toEqual({ a: 1, b: 2 });
});
}); });
}); });

View File

@@ -1,6 +1,6 @@
/* eslint no-shadow:0, react/no-multi-comp:0, react/display-name:0 */ /* eslint no-shadow:0, react/no-multi-comp:0, react/display-name:0 */
import React from 'react'; import * as React from 'react';
import StackRouter from '../StackRouter'; import StackRouter from '../StackRouter';
import * as StackActions from '../StackActions'; import * as StackActions from '../StackActions';

View File

@@ -1,6 +1,6 @@
/* eslint react/display-name:0 */ /* eslint react/display-name:0 */
import React from 'react'; import * as React from 'react';
import SwitchRouter from '../SwitchRouter'; import SwitchRouter from '../SwitchRouter';
import StackRouter from '../StackRouter'; import StackRouter from '../StackRouter';
import * as NavigationActions from '../../NavigationActions'; import * as NavigationActions from '../../NavigationActions';
@@ -158,7 +158,7 @@ describe('SwitchRouter', () => {
expect(getSubState(1).routeName).toEqual('A'); expect(getSubState(1).routeName).toEqual('A');
// The back action should not switch to B. It should stay on A // The back action should not switch to B. It should stay on A
back({ key: null }); back(null);
expect(getSubState(1).routeName).toEqual('A'); expect(getSubState(1).routeName).toEqual('A');
}); });

View File

@@ -1,6 +1,6 @@
/* eslint react/display-name:0 */ /* eslint react/display-name:0 */
import React from 'react'; import * as React from 'react';
import TabRouter from '../TabRouter'; import TabRouter from '../TabRouter';
import * as NavigationActions from '../../NavigationActions'; import * as NavigationActions from '../../NavigationActions';

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import validateRouteConfigMap from '../validateRouteConfigMap'; import validateRouteConfigMap from '../validateRouteConfigMap';
import StackRouter from '../StackRouter'; import StackRouter from '../StackRouter';

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import withNavigation from './withNavigation'; import withNavigation from './withNavigation';
const EventNameToPropName = { const EventNameToPropName = {
@@ -12,11 +12,28 @@ const EventNames = Object.keys(EventNameToPropName);
class NavigationEvents extends React.Component { class NavigationEvents extends React.Component {
componentDidMount() { componentDidMount() {
this.subscriptions = {};
// We register all navigation listeners on mount to ensure listener stability across re-render // We register all navigation listeners on mount to ensure listener stability across re-render
// A former implementation was replacing (removing/adding) listeners on all update (if prop provided) // A former implementation was replacing (removing/adding) listeners on all update (if prop provided)
// but there were issues (see https://github.com/react-navigation/react-navigation/issues/5058) // but there were issues (see https://github.com/react-navigation/react-navigation/issues/5058)
this.subscribeAll();
}
componentDidUpdate(prevProps) {
if (this.props.navigation !== prevProps.navigation) {
this.removeAll();
this.subscribeAll();
}
}
componentWillUnmount() {
this.removeAll();
}
getPropListener = (eventName) => this.props[EventNameToPropName[eventName]];
subscribeAll() {
this.subscriptions = {};
EventNames.forEach((eventName) => { EventNames.forEach((eventName) => {
this.subscriptions[eventName] = this.props.navigation.addListener( this.subscriptions[eventName] = this.props.navigation.addListener(
eventName, eventName,
@@ -28,14 +45,12 @@ class NavigationEvents extends React.Component {
}); });
} }
componentWillUnmount() { removeAll() {
EventNames.forEach((eventName) => { EventNames.forEach((eventName) => {
this.subscriptions[eventName].remove(); this.subscriptions[eventName].remove();
}); });
} }
getPropListener = (eventName) => this.props[EventNameToPropName[eventName]];
render() { render() {
return null; return null;
} }

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import NavigationContext from './NavigationContext'; import NavigationContext from './NavigationContext';
export default class SceneView extends React.PureComponent { export default class SceneView extends React.PureComponent {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import SceneView from '../SceneView'; import SceneView from '../SceneView';
export default class SwitchView extends React.Component { export default class SwitchView extends React.Component {

View File

@@ -1,10 +1,17 @@
import React from 'react'; import * as React from 'react';
import renderer from 'react-test-renderer'; import renderer from 'react-test-renderer';
import NavigationEvents from '../NavigationEvents'; import NavigationEvents from '../NavigationEvents';
import NavigationContext from '../NavigationContext'; import NavigationContext from '../NavigationContext';
const createPropListener = () => jest.fn(); const createPropListener = () => jest.fn();
const EVENT_TO_PROP_NAME = {
willFocus: 'onWillFocus',
didFocus: 'onDidFocus',
willBlur: 'onWillBlur',
didBlur: 'onDidBlur',
};
// An easy way to create the 4 listeners prop // An easy way to create the 4 listeners prop
const createEventListenersProp = () => ({ const createEventListenersProp = () => ({
onWillFocus: createPropListener(), onWillFocus: createPropListener(),
@@ -122,6 +129,39 @@ describe('NavigationEvents', () => {
checkPropListenerIsCalled('didBlur', 'onDidBlur'); checkPropListenerIsCalled('didBlur', 'onDidBlur');
}); });
it('wires props listeners to latest navigation updates', () => {
const {
navigation,
NavigationListenersAPI,
} = createTestNavigationAndHelpers();
const {
navigation: nextNavigation,
NavigationListenersAPI: nextNavigationListenersAPI,
} = createTestNavigationAndHelpers();
const eventListenerProps = createEventListenersProp();
const component = renderer.create(
<NavigationEvents navigation={navigation} {...eventListenerProps} />
);
Object.entries(EVENT_TO_PROP_NAME).forEach(([eventName, propName]) => {
expect(eventListenerProps[propName]).toHaveBeenCalledTimes(0);
NavigationListenersAPI.call(eventName);
expect(eventListenerProps[propName]).toHaveBeenCalledTimes(1);
});
component.update(
<NavigationEvents navigation={nextNavigation} {...eventListenerProps} />
);
Object.entries(EVENT_TO_PROP_NAME).forEach(([eventName, propName]) => {
NavigationListenersAPI.call(eventName);
expect(eventListenerProps[propName]).toHaveBeenCalledTimes(1);
nextNavigationListenersAPI.call(eventName);
expect(eventListenerProps[propName]).toHaveBeenCalledTimes(2);
});
});
it('wire latest props listener to navigation listeners on updates (support closure/arrow functions update)', () => { it('wire latest props listener to navigation listeners on updates (support closure/arrow functions update)', () => {
const { const {
navigation, navigation,

View File

@@ -0,0 +1,307 @@
import * as React from 'react';
import renderer from 'react-test-renderer';
import NavigationFocusEvents from '../NavigationFocusEvents';
import getEventManager from '../../getEventManager';
import { NavigationActions, StackActions } from '@react-navigation/core';
const getNavigationMock = (mock = {}) => {
const { addListener, emit } = getEventManager('target');
return {
state: {
routes: [
{ key: 'a', routeName: 'foo' },
{ key: 'b', routeName: 'bar' },
],
index: 0,
},
isFocused: () => true,
addListener: jest.fn(addListener),
emit: emit,
dangerouslyGetParent: () => null,
...mock,
};
};
it('emits refocus event with current route key on refocus', () => {
const navigation = getNavigationMock();
const onEvent = jest.fn();
renderer.create(
<NavigationFocusEvents navigation={navigation} onEvent={onEvent} />
);
navigation.emit('refocus');
expect(onEvent).toHaveBeenCalledTimes(1);
const key = navigation.state.routes[navigation.state.index].key;
expect(onEvent).toHaveBeenCalledWith(key, 'refocus');
});
describe('on navigation action emitted', () => {
it('does not emit if navigation is not focused', () => {
const navigation = getNavigationMock({
isFocused: () => false,
});
const onEvent = jest.fn();
renderer.create(
<NavigationFocusEvents navigation={navigation} onEvent={onEvent} />
);
navigation.emit('action', {
state: navigation.state,
action: NavigationActions.init(),
type: 'action',
});
expect(onEvent).not.toHaveBeenCalled();
});
it('emits only willFocus and willBlur if state is transitioning', () => {
const state = {
routes: [
{ key: 'First', routeName: 'First' },
{ key: 'Second', routeName: 'Second' },
],
index: 1,
routeKeyHistory: ['First', 'Second'],
isTransitioning: true,
};
const action = NavigationActions.init();
const navigation = getNavigationMock({
state: state,
});
const onEvent = jest.fn();
renderer.create(
<NavigationFocusEvents navigation={navigation} onEvent={onEvent} />
);
const lastState = {
routes: [
{ key: 'First', routeName: 'First' },
{ key: 'Second', routeName: 'Second' },
],
index: 0,
routeKeyHistory: ['First'],
};
navigation.emit('action', {
state,
lastState,
action,
type: 'action',
});
const expectedPayload = {
action,
state: { key: 'Second', routeName: 'Second' },
lastState: { key: 'First', routeName: 'First' },
context: 'Second:Navigation/INIT_Root',
type: 'action',
};
expect(onEvent.mock.calls).toEqual([
['Second', 'willFocus', expectedPayload],
['First', 'willBlur', expectedPayload],
['Second', 'action', expectedPayload],
]);
});
it('emits didFocus after willFocus and didBlur after willBlur if no transitions', () => {
const state = {
routes: [
{ key: 'First', routeName: 'First' },
{ key: 'Second', routeName: 'Second' },
],
index: 1,
routeKeyHistory: ['First', 'Second'],
};
const action = NavigationActions.navigate({
routeName: 'Second',
});
const navigation = getNavigationMock({
state: state,
});
const onEvent = jest.fn();
renderer.create(
<NavigationFocusEvents navigation={navigation} onEvent={onEvent} />
);
const lastState = {
routes: [
{ key: 'First', routeName: 'First' },
{ key: 'Second', routeName: 'Second' },
],
index: 0,
routeKeyHistory: ['First'],
};
navigation.emit('action', {
state,
lastState,
action,
type: 'action',
});
const expectedPayload = {
action,
state: { key: 'Second', routeName: 'Second' },
lastState: { key: 'First', routeName: 'First' },
context: 'Second:Navigation/NAVIGATE_Root',
type: 'action',
};
expect(onEvent.mock.calls).toEqual([
['Second', 'willFocus', expectedPayload],
['Second', 'didFocus', expectedPayload],
['First', 'willBlur', expectedPayload],
['First', 'didBlur', expectedPayload],
['Second', 'action', expectedPayload],
]);
});
it('emits didBlur and didFocus when transition ends', () => {
const initialState = {
routes: [
{ key: 'First', routeName: 'First' },
{ key: 'Second', routeName: 'Second' },
],
index: 0,
routeKeyHistory: ['First'],
isTransitioning: true,
};
const intermediateState = {
routes: [
{ key: 'First', routeName: 'First' },
{ key: 'Second', routeName: 'Second' },
],
index: 1,
routeKeyHistory: ['First', 'Second'],
isTransitioning: true,
};
const finalState = {
routes: [
{ key: 'First', routeName: 'First' },
{ key: 'Second', routeName: 'Second' },
],
index: 1,
routeKeyHistory: ['First', 'Second'],
isTransitioning: false,
};
const actionNavigate = NavigationActions.navigate({ routeName: 'Second' });
const actionEndTransition = StackActions.completeTransition({
key: 'Second',
});
const navigation = getNavigationMock({
state: intermediateState,
});
const onEvent = jest.fn();
renderer.create(
<NavigationFocusEvents navigation={navigation} onEvent={onEvent} />
);
navigation.emit('action', {
state: intermediateState,
lastState: initialState,
action: actionNavigate,
type: 'action',
});
const expectedPayloadNavigate = {
action: actionNavigate,
state: { key: 'Second', routeName: 'Second' },
lastState: { key: 'First', routeName: 'First' },
context: 'Second:Navigation/NAVIGATE_Root',
type: 'action',
};
expect(onEvent.mock.calls).toEqual([
['Second', 'willFocus', expectedPayloadNavigate],
['First', 'willBlur', expectedPayloadNavigate],
['Second', 'action', expectedPayloadNavigate],
]);
onEvent.mockClear();
navigation.emit('action', {
state: finalState,
lastState: intermediateState,
action: actionEndTransition,
type: 'action',
});
const expectedPayloadEndTransition = {
action: actionEndTransition,
state: { key: 'Second', routeName: 'Second' },
lastState: { key: 'Second', routeName: 'Second' },
context: 'Second:Navigation/COMPLETE_TRANSITION_Root',
type: 'action',
};
expect(onEvent.mock.calls).toEqual([
['First', 'didBlur', expectedPayloadEndTransition],
['Second', 'didFocus', expectedPayloadEndTransition],
['Second', 'action', expectedPayloadEndTransition],
]);
});
});
describe('on willFocus emitted', () => {
it('emits didFocus after willFocus if no transition', () => {
const navigation = getNavigationMock({
state: {
routes: [
{ key: 'FirstLanding', routeName: 'FirstLanding' },
{ key: 'Second', routeName: 'Second' },
],
index: 0,
key: 'First',
routeName: 'First',
},
});
const onEvent = jest.fn();
renderer.create(
<NavigationFocusEvents navigation={navigation} onEvent={onEvent} />
);
const lastState = { key: 'Third', routeName: 'Third' };
const action = NavigationActions.navigate({ routeName: 'First' });
navigation.emit('willFocus', {
lastState,
action,
context: 'First:Navigation/NAVIGATE_Root',
type: 'action',
});
const expectedPayload = {
action,
state: { key: 'FirstLanding', routeName: 'FirstLanding' },
context:
'FirstLanding:Navigation/NAVIGATE_First:Navigation/NAVIGATE_Root',
type: 'action',
};
expect(onEvent.mock.calls).toEqual([
['FirstLanding', 'willFocus', expectedPayload],
['FirstLanding', 'didFocus', expectedPayload],
]);
onEvent.mockClear();
// the nested navigator might emit a didFocus that should be ignored
navigation.emit('didFocus', {
lastState,
action,
context: 'First:Navigation/NAVIGATE_Root',
type: 'action',
});
expect(onEvent).not.toHaveBeenCalled();
});
});

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import hoistStatics from 'hoist-non-react-statics'; import hoistStatics from 'hoist-non-react-statics';
import invariant from '../utils/invariant'; import invariant from '../utils/invariant';
import NavigationContext from './NavigationContext'; import NavigationContext from './NavigationContext';

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import hoistStatics from 'hoist-non-react-statics'; import hoistStatics from 'hoist-non-react-statics';
import withNavigation from './withNavigation'; import withNavigation from './withNavigation';

View File

@@ -3,6 +3,44 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [2.7.0](https://github.com/react-navigation/drawer/compare/react-navigation-drawer@2.6.0...react-navigation-drawer@2.7.0) (2021-02-21)
### Features
* add activityState to other navigators ([5c7f892](https://github.com/react-navigation/drawer/commit/5c7f892d77298f5c89534fa78a1a6a59c7f35a60))
# [2.6.0](https://github.com/react-navigation/drawer/compare/react-navigation-drawer@2.5.2...react-navigation-drawer@2.6.0) (2020-10-26)
### Features
* add detachInactiveScreens prop for bottom tabs and drawer ([#8816](https://github.com/react-navigation/drawer/issues/8816)) ([707bea3](https://github.com/react-navigation/drawer/commit/707bea3cba1aa1f7b1eb5884dd1d129dcc2bbdc2))
## [2.5.2](https://github.com/react-navigation/drawer/compare/react-navigation-drawer@2.5.1...react-navigation-drawer@2.5.2) (2020-10-02)
**Note:** Version bump only for package react-navigation-drawer
## [2.5.1](https://github.com/react-navigation/drawer/compare/react-navigation-drawer@2.5.0...react-navigation-drawer@2.5.1) (2020-09-24)
**Note:** Version bump only for package react-navigation-drawer
# [2.5.0](https://github.com/react-navigation/drawer/compare/react-navigation-drawer@2.4.13...react-navigation-drawer@2.5.0) (2020-06-25) # [2.5.0](https://github.com/react-navigation/drawer/compare/react-navigation-drawer@2.4.13...react-navigation-drawer@2.5.0) (2020-06-25)

View File

@@ -1,6 +1,6 @@
{ {
"name": "react-navigation-drawer", "name": "react-navigation-drawer",
"version": "2.5.0", "version": "2.7.0",
"description": "Drawer navigator component for React Navigation", "description": "Drawer navigator component for React Navigation",
"main": "lib/commonjs/index.js", "main": "lib/commonjs/index.js",
"react-native": "lib/module/index.js", "react-native": "lib/module/index.js",
@@ -38,19 +38,19 @@
}, },
"homepage": "https://github.com/react-navigation/drawer#readme", "homepage": "https://github.com/react-navigation/drawer#readme",
"devDependencies": { "devDependencies": {
"@react-native-community/bob": "^0.10.0", "@react-native-community/bob": "^0.16.2",
"@types/react": "^16.9.23", "@types/react": "^16.9.53",
"@types/react-native": "^0.61.22", "@types/react-native": "^0.63.30",
"del-cli": "^3.0.0", "del-cli": "^3.0.1",
"react": "~16.9.0", "react": "~16.13.1",
"react-lifecycles-compat": "^3.0.4", "react-lifecycles-compat": "^3.0.4",
"react-native": "~0.61.5", "react-native": "~0.63.2",
"react-native-gesture-handler": "^1.6.0", "react-native-gesture-handler": "~1.7.0",
"react-native-reanimated": "^1.2.0", "react-native-reanimated": "~1.13.0",
"react-native-screens": "^2.3.0", "react-native-screens": "~2.10.1",
"react-native-testing-library": "^1.12.0", "react-native-testing-library": "^6.0.0",
"react-navigation": "^4.4.0", "react-navigation": "^4.4.4",
"typescript": "^3.9.5" "typescript": "^4.0.3"
}, },
"peerDependencies": { "peerDependencies": {
"react": "*", "react": "*",

View File

@@ -69,6 +69,7 @@ export type NavigationDrawerConfig = {
drawerBackgroundColor?: ThemedColor; drawerBackgroundColor?: ThemedColor;
overlayColor?: ThemedColor; overlayColor?: ThemedColor;
screenContainerStyle?: StyleProp<ViewStyle>; screenContainerStyle?: StyleProp<ViewStyle>;
detachInactiveScreens?: boolean;
}; };
export type NavigationDrawerRouterConfig = { export type NavigationDrawerRouterConfig = {

View File

@@ -49,6 +49,7 @@ type Props = {
contentOptions?: object; contentOptions?: object;
}; };
screenProps: unknown; screenProps: unknown;
detachInactiveScreens: boolean;
}; };
type State = { type State = {
@@ -166,7 +167,7 @@ export default class DrawerView extends React.PureComponent<Props, State> {
}; };
private renderContent = () => { private renderContent = () => {
let { lazy, navigation } = this.props; let { lazy, navigation, detachInactiveScreens = true } = this.props;
let { loaded } = this.state; let { loaded } = this.state;
let { routes } = navigation.state; let { routes } = navigation.state;
@@ -183,7 +184,8 @@ export default class DrawerView extends React.PureComponent<Props, State> {
); );
} else { } else {
return ( return (
<ScreenContainer style={styles.content}> // @ts-ignore
<ScreenContainer enabled={detachInactiveScreens} style={styles.content}>
{routes.map((route, index) => { {routes.map((route, index) => {
if (lazy && !loaded.includes(index)) { if (lazy && !loaded.includes(index)) {
// Don't render a screen if we've never navigated to it // Don't render a screen if we've never navigated to it
@@ -201,6 +203,7 @@ export default class DrawerView extends React.PureComponent<Props, State> {
{ opacity: isFocused ? 1 : 0 }, { opacity: isFocused ? 1 : 0 },
]} ]}
isVisible={isFocused} isVisible={isFocused}
enabled={detachInactiveScreens}
> >
<SceneView <SceneView
navigation={descriptor.navigation} navigation={descriptor.navigation}

View File

@@ -1,11 +1,17 @@
import * as React from 'react'; import * as React from 'react';
import { Platform, StyleSheet, View } from 'react-native'; import { Platform, StyleSheet, View } from 'react-native';
import { Screen, screensEnabled } from 'react-native-screens'; import {
Screen,
screensEnabled,
// @ts-ignore
shouldUseActivityState,
} from 'react-native-screens';
type Props = { type Props = {
isVisible: boolean; isVisible: boolean;
children: React.ReactNode; children: React.ReactNode;
style?: any; style?: any;
enabled: boolean;
}; };
const FAR_FAR_AWAY = 30000; // this should be big enough to move the whole view out of its container const FAR_FAR_AWAY = 30000; // this should be big enough to move the whole view out of its container
@@ -13,11 +19,20 @@ const FAR_FAR_AWAY = 30000; // this should be big enough to move the whole view
export default class ResourceSavingScene extends React.Component<Props> { export default class ResourceSavingScene extends React.Component<Props> {
render() { render() {
// react-native-screens is buggy on web // react-native-screens is buggy on web
if (screensEnabled?.() && Platform.OS !== 'web') { if (screensEnabled?.() && this.props.enabled && Platform.OS !== 'web') {
const { isVisible, ...rest } = this.props; const { isVisible, ...rest } = this.props;
// @ts-ignore if (shouldUseActivityState) {
return <Screen active={isVisible ? 1 : 0} {...rest} />; return (
// @ts-expect-error: there was an `active` prop and no `activityState` in older version and stackPresentation was required
<Screen activityState={isVisible ? 2 : 0} {...rest} />
);
} else {
return (
// @ts-expect-error: there was an `active` prop and no `activityState` in older version and stackPresentation was required
<Screen active={isVisible ? 1 : 0} {...rest} />
);
}
} }
const { isVisible, children, style, ...rest } = this.props; const { isVisible, children, style, ...rest } = this.props;

View File

@@ -3,6 +3,38 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [2.3.4](https://github.com/react-navigation/react-navigation-material-bottom-tabs/compare/react-navigation-material-bottom-tabs@2.3.3...react-navigation-material-bottom-tabs@2.3.4) (2021-02-21)
**Note:** Version bump only for package react-navigation-material-bottom-tabs
## [2.3.3](https://github.com/react-navigation/react-navigation-material-bottom-tabs/compare/react-navigation-material-bottom-tabs@2.3.2...react-navigation-material-bottom-tabs@2.3.3) (2020-10-26)
**Note:** Version bump only for package react-navigation-material-bottom-tabs
## [2.3.2](https://github.com/react-navigation/react-navigation-material-bottom-tabs/compare/react-navigation-material-bottom-tabs@2.3.1...react-navigation-material-bottom-tabs@2.3.2) (2020-10-02)
**Note:** Version bump only for package react-navigation-material-bottom-tabs
## [2.3.1](https://github.com/react-navigation/react-navigation-material-bottom-tabs/compare/react-navigation-material-bottom-tabs@2.3.0...react-navigation-material-bottom-tabs@2.3.1) (2020-09-24)
**Note:** Version bump only for package react-navigation-material-bottom-tabs
# [2.3.0](https://github.com/react-navigation/react-navigation-material-bottom-tabs/compare/react-navigation-material-bottom-tabs@2.2.12...react-navigation-material-bottom-tabs@2.3.0) (2020-06-25) # [2.3.0](https://github.com/react-navigation/react-navigation-material-bottom-tabs/compare/react-navigation-material-bottom-tabs@2.2.12...react-navigation-material-bottom-tabs@2.3.0) (2020-06-25)

View File

@@ -1,6 +1,6 @@
{ {
"name": "react-navigation-material-bottom-tabs", "name": "react-navigation-material-bottom-tabs",
"version": "2.3.0", "version": "2.3.4",
"description": "Material Bottom Tab Navigation component for React Navigation", "description": "Material Bottom Tab Navigation component for React Navigation",
"main": "lib/commonjs/index.js", "main": "lib/commonjs/index.js",
"module": "lib/module/index.js", "module": "lib/module/index.js",
@@ -38,18 +38,16 @@
}, },
"homepage": "https://github.com/react-navigation/react-navigation-material-bottom-tabs#readme", "homepage": "https://github.com/react-navigation/react-navigation-material-bottom-tabs#readme",
"devDependencies": { "devDependencies": {
"@react-native-community/bob": "^0.10.0", "@react-native-community/bob": "^0.16.2",
"@types/hoist-non-react-statics": "^3.3.1", "@types/hoist-non-react-statics": "^3.3.1",
"@types/react": "^16.9.23", "@types/react": "^16.9.53",
"@types/react-native": "^0.61.22", "@types/react-native": "^0.63.30",
"del-cli": "^3.0.0", "del-cli": "^3.0.1",
"react": "~16.9.0", "react": "~16.13.1",
"react-native": "~0.61.5", "react-native": "~0.63.2",
"react-native-gesture-handler": "^1.6.0", "react-native-paper": "^4.2.0",
"react-native-paper": "^3.1.1", "react-navigation": "^4.4.4",
"react-native-reanimated": "^1.2.0", "typescript": "^4.0.3"
"react-navigation": "^4.4.0",
"typescript": "^3.9.5"
}, },
"peerDependencies": { "peerDependencies": {
"react": "*", "react": "*",

View File

@@ -3,6 +3,44 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [3.8.4](https://github.com/react-navigation/react-navigation-native/compare/@react-navigation/native@3.8.3...@react-navigation/native@3.8.4) (2021-02-21)
### Bug Fixes
* address breaking change in react-native for Linking ([fb1e8d4](https://github.com/react-navigation/react-navigation-native/commit/fb1e8d4a077cece663633408d279459df66033a4))
## [3.8.3](https://github.com/react-navigation/react-navigation-native/compare/@react-navigation/native@3.8.2...@react-navigation/native@3.8.3) (2020-10-26)
**Note:** Version bump only for package @react-navigation/native
## [3.8.2](https://github.com/react-navigation/react-navigation-native/compare/@react-navigation/native@3.8.1...@react-navigation/native@3.8.2) (2020-10-02)
**Note:** Version bump only for package @react-navigation/native
## [3.8.1](https://github.com/react-navigation/react-navigation-native/compare/@react-navigation/native@3.8.0...@react-navigation/native@3.8.1) (2020-09-24)
### Bug Fixes
* don't use deprecated currentlyFocusedField ([#8684](https://github.com/react-navigation/react-navigation-native/issues/8684)) ([06a69f1](https://github.com/react-navigation/react-navigation-native/commit/06a69f1bfd81fe06b784ff4e6da290fee0c6467d)), closes [#8457](https://github.com/react-navigation/react-navigation-native/issues/8457)
# [3.8.0](https://github.com/react-navigation/react-navigation-native/compare/@react-navigation/native@3.7.13...@react-navigation/native@3.8.0) (2020-06-25) # [3.8.0](https://github.com/react-navigation/react-navigation-native/compare/@react-navigation/native@3.7.13...@react-navigation/native@3.8.0) (2020-06-25)

View File

@@ -1,6 +1,6 @@
{ {
"name": "@react-navigation/native", "name": "@react-navigation/native",
"version": "3.8.0", "version": "3.8.4",
"description": "React Native support for React Navigation", "description": "React Native support for React Navigation",
"main": "lib/commonjs/index.js", "main": "lib/commonjs/index.js",
"react-native": "lib/module/index.js", "react-native": "lib/module/index.js",
@@ -39,14 +39,14 @@
"react-native-safe-area-view": "^0.14.9" "react-native-safe-area-view": "^0.14.9"
}, },
"devDependencies": { "devDependencies": {
"@react-native-community/bob": "^0.10.0", "@react-native-community/bob": "^0.16.2",
"@react-navigation/core": "^3.7.6", "@react-navigation/core": "^3.7.9",
"@types/react-test-renderer": "^16.9.2", "@types/react-test-renderer": "^16.9.3",
"del-cli": "^3.0.0", "del-cli": "^3.0.1",
"react": "~16.9.0", "react": "~16.13.1",
"react-native": "~0.61.5", "react-native": "~0.63.2",
"react-native-gesture-handler": "^1.6.0", "react-native-gesture-handler": "~1.7.0",
"react-test-renderer": "^16.9.2" "react-test-renderer": "~16.13.1"
}, },
"@react-native-community/bob": { "@react-native-community/bob": {
"source": "src", "source": "src",

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { Platform, StyleSheet, View } from 'react-native'; import { Platform, StyleSheet, View } from 'react-native';
import { SceneView } from '@react-navigation/core'; import { SceneView } from '@react-navigation/core';

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { import {
ScrollView, ScrollView,
Platform, Platform,
@@ -6,7 +6,6 @@ import {
SectionList, SectionList,
RefreshControl, RefreshControl,
} from 'react-native'; } from 'react-native';
// eslint-disable-next-line import/named
import { ScrollView as GHScrollView } from 'react-native-gesture-handler'; import { ScrollView as GHScrollView } from 'react-native-gesture-handler';
import createNavigationAwareScrollable from './createNavigationAwareScrollable'; import createNavigationAwareScrollable from './createNavigationAwareScrollable';
import invariant from './utils/invariant'; import invariant from './utils/invariant';

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { View } from 'react-native'; import { View } from 'react-native';
import renderer from 'react-test-renderer'; import renderer from 'react-test-renderer';

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { View } from 'react-native'; import { View } from 'react-native';
import renderer from 'react-test-renderer'; import renderer from 'react-test-renderer';
import withOrientation, { isOrientationLandscape } from '../withOrientation'; import withOrientation, { isOrientationLandscape } from '../withOrientation';

View File

@@ -1,6 +1,6 @@
/* eslint-disable react/sort-comp */ /* eslint-disable react/sort-comp */
import React from 'react'; import * as React from 'react';
import { Linking, Platform, BackHandler } from 'react-native'; import { Linking, Platform, BackHandler } from 'react-native';
import { import {
NavigationActions, NavigationActions,
@@ -214,7 +214,7 @@ export default function createNavigationContainer(Component) {
} }
} }
_statefulContainerCount++; _statefulContainerCount++;
Linking.addEventListener('url', this._handleOpenURL); this._linkingSub = Linking.addEventListener('url', this._handleOpenURL);
// Pull out anything that can impact state // Pull out anything that can impact state
let parsedUrl = null; let parsedUrl = null;
@@ -331,7 +331,14 @@ export default function createNavigationContainer(Component) {
componentWillUnmount() { componentWillUnmount() {
this._isMounted = false; this._isMounted = false;
Linking.removeEventListener('url', this._handleOpenURL);
// https://github.com/facebook/react-native/commit/6d1aca806cee86ad76de771ed3a1cc62982ebcd7
if (this._linkingSub?.remove) {
this._linkingSub?.remove();
} else {
Linking.removeEventListener('url', this._handleOpenURL);
}
this.subs && this.subs.remove(); this.subs && this.subs.remove();
if (this._isStateful()) { if (this._isStateful()) {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { TextInput } from 'react-native'; import { TextInput } from 'react-native';
export default (Navigator, navigatorConfig) => export default (Navigator, navigatorConfig) =>
@@ -8,7 +8,9 @@ export default (Navigator, navigatorConfig) =>
_previouslyFocusedTextInput = null; _previouslyFocusedTextInput = null;
_handleGestureBegin = () => { _handleGestureBegin = () => {
this._previouslyFocusedTextInput = TextInput.State.currentlyFocusedField(); this._previouslyFocusedTextInput = TextInput.State.currentlyFocusedInput
? TextInput.State.currentlyFocusedInput()
: TextInput.State.currentlyFocusedField();
if (this._previouslyFocusedTextInput) { if (this._previouslyFocusedTextInput) {
TextInput.State.blurTextInput(this._previouslyFocusedTextInput); TextInput.State.blurTextInput(this._previouslyFocusedTextInput);
} }
@@ -32,7 +34,9 @@ export default (Navigator, navigatorConfig) =>
// in the case where the index did not change, I believe. We // in the case where the index did not change, I believe. We
// should revisit this after 2.0 release. // should revisit this after 2.0 release.
if (transitionProps.index !== prevTransitionProps.index) { if (transitionProps.index !== prevTransitionProps.index) {
const currentField = TextInput.State.currentlyFocusedField(); const currentField = TextInput.State.currentlyFocusedInput
? TextInput.State.currentlyFocusedInput()
: TextInput.State.currentlyFocusedField();
if (currentField) { if (currentField) {
TextInput.State.blurTextInput(currentField); TextInput.State.blurTextInput(currentField);
} }

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import hoistStatics from 'hoist-non-react-statics'; import hoistStatics from 'hoist-non-react-statics';
import { withNavigation } from '@react-navigation/core'; import { withNavigation } from '@react-navigation/core';

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { Dimensions } from 'react-native'; import { Dimensions } from 'react-native';
import hoistNonReactStatic from 'hoist-non-react-statics'; import hoistNonReactStatic from 'hoist-non-react-statics';

View File

@@ -3,6 +3,38 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [4.4.4](https://github.com/react-navigation/react-navigation/compare/react-navigation@4.4.3...react-navigation@4.4.4) (2021-02-21)
**Note:** Version bump only for package react-navigation
## [4.4.3](https://github.com/react-navigation/react-navigation/compare/react-navigation@4.4.2...react-navigation@4.4.3) (2020-10-26)
**Note:** Version bump only for package react-navigation
## [4.4.2](https://github.com/react-navigation/react-navigation/compare/react-navigation@4.4.1...react-navigation@4.4.2) (2020-10-02)
**Note:** Version bump only for package react-navigation
## [4.4.1](https://github.com/react-navigation/react-navigation/compare/react-navigation@4.4.0...react-navigation@4.4.1) (2020-09-24)
**Note:** Version bump only for package react-navigation
# [4.4.0](https://github.com/react-navigation/react-navigation/compare/react-navigation@4.3.9...react-navigation@4.4.0) (2020-06-25) # [4.4.0](https://github.com/react-navigation/react-navigation/compare/react-navigation@4.3.9...react-navigation@4.4.0) (2020-06-25)

View File

@@ -1,6 +1,6 @@
{ {
"name": "react-navigation", "name": "react-navigation",
"version": "4.4.0", "version": "4.4.4",
"description": "Routing and navigation for your React Native apps", "description": "Routing and navigation for your React Native apps",
"main": "src/index.js", "main": "src/index.js",
"types": "typescript/react-navigation.d.ts", "types": "typescript/react-navigation.d.ts",
@@ -24,16 +24,16 @@
"react-native": "*" "react-native": "*"
}, },
"dependencies": { "dependencies": {
"@react-navigation/core": "^3.7.6", "@react-navigation/core": "^3.7.9",
"@react-navigation/native": "^3.8.0" "@react-navigation/native": "^3.8.4"
}, },
"devDependencies": { "devDependencies": {
"@types/react": "^16.9.23", "@types/react": "^16.9.53",
"@types/react-native": "^0.61.22", "@types/react-native": "^0.63.30",
"@types/react-test-renderer": "^16.9.2", "@types/react-test-renderer": "^16.9.3",
"react": "~16.9.0", "react": "~16.13.1",
"react-native": "~0.61.5", "react-native": "~0.63.2",
"react-test-renderer": "^16.9.2", "react-test-renderer": "~16.13.1",
"typescript": "^3.9.5" "typescript": "^4.0.3"
} }
} }

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { View } from 'react-native'; import { View } from 'react-native';
import renderer from 'react-test-renderer'; import renderer from 'react-test-renderer';

View File

@@ -812,6 +812,7 @@ export interface NavigationDescriptor<
getComponent: () => React.ComponentType; getComponent: () => React.ComponentType;
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type NavigationView<Options, State, ScreenProps = unknown> = export type NavigationView<Options, State, ScreenProps = unknown> =
| React.ComponentType< | React.ComponentType<
{ {
@@ -897,11 +898,13 @@ export function withNavigation<
} }
>; >;
// eslint-disable-next-line no-redeclare
export function withNavigation<P extends NavigationInjectedProps>( export function withNavigation<P extends NavigationInjectedProps>(
Component: React.ComponentType<P> Component: React.ComponentType<P>
): React.ComponentType<Omit<P, keyof NavigationInjectedProps>>; ): React.ComponentType<Omit<P, keyof NavigationInjectedProps>>;
// For backwards compatibility // For backwards compatibility
// eslint-disable-next-line no-redeclare
export function withNavigation<T = {}, P = NavigationParams>( export function withNavigation<T = {}, P = NavigationParams>(
Component: React.ComponentType<T & NavigationInjectedProps<P>> Component: React.ComponentType<T & NavigationInjectedProps<P>>
): React.ComponentType< ): React.ComponentType<
@@ -929,11 +932,13 @@ export function withNavigationFocus<
} }
>; >;
// eslint-disable-next-line no-redeclare
export function withNavigationFocus<P extends NavigationFocusInjectedProps>( export function withNavigationFocus<P extends NavigationFocusInjectedProps>(
Component: React.ComponentType<P> Component: React.ComponentType<P>
): React.ComponentType<Omit<P, keyof NavigationFocusInjectedProps>>; ): React.ComponentType<Omit<P, keyof NavigationFocusInjectedProps>>;
// For backwards compatibility // For backwards compatibility
// eslint-disable-next-line no-redeclare
export function withNavigationFocus<T = {}, P = NavigationParams>( export function withNavigationFocus<T = {}, P = NavigationParams>(
Component: React.ComponentType<T & NavigationFocusInjectedProps<P>> Component: React.ComponentType<T & NavigationFocusInjectedProps<P>>
): React.ComponentType< ): React.ComponentType<

View File

@@ -3,6 +3,90 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [2.10.3](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.10.2...react-navigation-stack@2.10.3) (2021-02-21)
**Note:** Version bump only for package react-navigation-stack
## [2.10.2](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.10.1...react-navigation-stack@2.10.2) (2020-11-22)
**Note:** Version bump only for package react-navigation-stack
## [2.10.1](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.10.0...react-navigation-stack@2.10.1) (2020-11-04)
**Note:** Version bump only for package react-navigation-stack
# [2.10.0](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.9.0...react-navigation-stack@2.10.0) (2020-10-30)
### Features
* enable react-native-screens in Stack by default on iOS ([8411e6f](https://github.com/react-navigation/react-navigation-stack/commit/8411e6f764b86341e747cb7ca1ff4a775b4a827a))
# [2.9.0](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.8.4...react-navigation-stack@2.9.0) (2020-10-26)
### Features
* sync latest stack ([6bdc1e9](https://github.com/react-navigation/react-navigation-stack/commit/6bdc1e9e5f6ca05e0494f6b9a1f7b9b60764628a))
## [2.8.4](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.8.3...react-navigation-stack@2.8.4) (2020-10-02)
**Note:** Version bump only for package react-navigation-stack
## [2.8.3](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.8.2...react-navigation-stack@2.8.3) (2020-09-24)
**Note:** Version bump only for package react-navigation-stack
## [2.8.2](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.8.1...react-navigation-stack@2.8.2) (2020-06-25)
### Bug Fixes
* sync latest stack ([46b797d](https://github.com/react-navigation/react-navigation-stack/commit/46b797dd297f789e3c92ff6f5c4432fedc891767))
## [2.8.1](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.8.0...react-navigation-stack@2.8.1) (2020-06-25)
### Bug Fixes
* pop with correct key from nested stack ([2e7f4a6](https://github.com/react-navigation/react-navigation-stack/commit/2e7f4a6d10a00930bd5c53ef6f4bf964c9638db5))
# [2.8.0](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.7.0...react-navigation-stack@2.8.0) (2020-06-25) # [2.8.0](https://github.com/react-navigation/react-navigation-stack/compare/react-navigation-stack@2.7.0...react-navigation-stack@2.8.0) (2020-06-25)

View File

@@ -49,7 +49,7 @@ yarn example start
The code in this repo uses the source from [`@react-navigation/stack`](https://github.com/react-navigation/navigation-ex/tree/master/packages/stack) and patches it to make it usable in React Navigation 4. If you need to make changes, please send a pull request there. The code in this repo uses the source from [`@react-navigation/stack`](https://github.com/react-navigation/navigation-ex/tree/master/packages/stack) and patches it to make it usable in React Navigation 4. If you need to make changes, please send a pull request there.
If the change is specifically related to React Navigation 4 integration, first run `yarn sync`, then change the files in `src/vendor` and then run `yarn patch` to update the patch file with the latest changes. If the change is specifically related to React Navigation 4 integration, first run `yarn patch:apply`, then change the files in `src/vendor` to resolve any conflicts and then run `yarn patch:create` to update the patch file with the latest changes.
Make sure your code passes TypeScript and ESLint. Run the following to verify: Make sure your code passes TypeScript and ESLint. Run the following to verify:

View File

@@ -1,6 +1,6 @@
{ {
"name": "react-navigation-stack", "name": "react-navigation-stack",
"version": "2.8.0", "version": "2.10.3",
"description": "Stack navigator component for React Navigation", "description": "Stack navigator component for React Navigation",
"main": "lib/commonjs/index.js", "main": "lib/commonjs/index.js",
"module": "lib/module/index.js", "module": "lib/module/index.js",
@@ -13,8 +13,8 @@
"scripts": { "scripts": {
"prepare": "bob build", "prepare": "bob build",
"clean": "del lib", "clean": "del lib",
"sync": "bash scripts/sync-stack.sh", "patch:apply": "bash scripts/sync-stack.sh",
"patch": "diff -Naur ../../node_modules/@react-navigation/stack/src src/vendor > scripts/stack.patch; printf ''" "patch:create": "diff -Naur ../../node_modules/@react-navigation/stack/src src/vendor > scripts/stack.patch; printf ''"
}, },
"sideEffects": false, "sideEffects": false,
"publishConfig": { "publishConfig": {
@@ -39,26 +39,26 @@
}, },
"homepage": "https://github.com/react-navigation/react-navigation-stack#readme", "homepage": "https://github.com/react-navigation/react-navigation-stack#readme",
"dependencies": { "dependencies": {
"color": "^3.1.2", "color": "^3.1.3",
"react-native-iphone-x-helper": "^1.2.1" "react-native-iphone-x-helper": "^1.3.0"
}, },
"devDependencies": { "devDependencies": {
"@react-native-community/bob": "^0.10.0", "@react-native-community/bob": "^0.16.2",
"@react-native-community/masked-view": "^0.1.7", "@react-native-community/masked-view": "0.1.10",
"@react-navigation/stack": "^5.6.0", "@react-navigation/stack": "^5.14.3",
"@types/color": "^3.0.1", "@types/color": "^3.0.1",
"@types/react": "^16.9.23", "@types/react": "^16.9.53",
"@types/react-native": "^0.61.22", "@types/react-native": "^0.63.30",
"@types/react-test-renderer": "^16.9.2", "@types/react-test-renderer": "^16.9.3",
"del-cli": "^3.0.0", "del-cli": "^3.0.1",
"react": "~16.9.0", "react": "~16.13.1",
"react-native": "~0.61.4", "react-native": "~0.63.2",
"react-native-gesture-handler": "^1.6.0", "react-native-gesture-handler": "~1.7.0",
"react-native-safe-area-context": "^0.7.3", "react-native-safe-area-context": "3.1.4",
"react-native-screens": "^2.3.0", "react-native-screens": "~2.10.1",
"react-navigation": "^4.4.0", "react-navigation": "^4.4.4",
"react-test-renderer": "~16.9.0", "react-test-renderer": "~16.13.1",
"typescript": "^3.9.5" "typescript": "^4.0.3"
}, },
"peerDependencies": { "peerDependencies": {
"@react-native-community/masked-view": ">=0.1.0", "@react-native-community/masked-view": ">=0.1.0",

View File

@@ -1,10 +1,10 @@
diff -Naur ../../node_modules/@react-navigation/stack/src/index.tsx src/vendor/index.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/index.tsx src/vendor/index.tsx
--- ../../node_modules/@react-navigation/stack/src/index.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/index.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/index.tsx 2020-06-24 23:16:17.000000000 +0200 +++ src/vendor/index.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -3,11 +3,6 @@ @@ -3,11 +3,6 @@
import * as TransitionSpecs from './TransitionConfigs/TransitionSpecs'; import * as TransitionSpecs from './TransitionConfigs/TransitionSpecs';
import * as TransitionPresets from './TransitionConfigs/TransitionPresets'; import * as TransitionPresets from './TransitionConfigs/TransitionPresets';
-/** -/**
- * Navigators - * Navigators
- */ - */
@@ -28,9 +28,9 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/index.tsx src/vendor/i
StackHeaderLeftButtonProps, StackHeaderLeftButtonProps,
StackHeaderTitleProps, StackHeaderTitleProps,
diff -Naur ../../node_modules/@react-navigation/stack/src/navigators/createStackNavigator.tsx src/vendor/navigators/createStackNavigator.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/navigators/createStackNavigator.tsx src/vendor/navigators/createStackNavigator.tsx
--- ../../node_modules/@react-navigation/stack/src/navigators/createStackNavigator.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/navigators/createStackNavigator.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/navigators/createStackNavigator.tsx 1970-01-01 01:00:00.000000000 +0100 +++ src/vendor/navigators/createStackNavigator.tsx 1970-01-01 01:00:00.000000000 +0100
@@ -1,96 +0,0 @@ @@ -1,101 +0,0 @@
-import * as React from 'react'; -import * as React from 'react';
-import { Platform } from 'react-native'; -import { Platform } from 'react-native';
-import { -import {
@@ -42,6 +42,8 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/navigators/createStack
- StackRouterOptions, - StackRouterOptions,
- StackNavigationState, - StackNavigationState,
- StackActions, - StackActions,
- ParamListBase,
- StackActionHelpers,
-} from '@react-navigation/native'; -} from '@react-navigation/native';
-import StackView from '../views/Stack/StackView'; -import StackView from '../views/Stack/StackView';
-import type { -import type {
@@ -62,12 +64,16 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/navigators/createStack
-}: Props) { -}: Props) {
- const defaultOptions = { - const defaultOptions = {
- gestureEnabled: Platform.OS === 'ios', - gestureEnabled: Platform.OS === 'ios',
- animationEnabled: Platform.OS !== 'web', - animationEnabled:
- Platform.OS !== 'web' &&
- Platform.OS !== 'windows' &&
- Platform.OS !== 'macos',
- }; - };
- -
- const { state, descriptors, navigation } = useNavigationBuilder< - const { state, descriptors, navigation } = useNavigationBuilder<
- StackNavigationState, - StackNavigationState<ParamListBase>,
- StackRouterOptions, - StackRouterOptions,
- StackActionHelpers<ParamListBase>,
- StackNavigationOptions, - StackNavigationOptions,
- StackNavigationEventMap - StackNavigationEventMap
- >(StackRouter, { - >(StackRouter, {
@@ -87,8 +93,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/navigators/createStack
- -
- React.useEffect( - React.useEffect(
- () => - () =>
- navigation.addListener && - navigation.addListener?.('tabPress', (e) => {
- navigation.addListener('tabPress', (e) => {
- const isFocused = navigation.isFocused(); - const isFocused = navigation.isFocused();
- -
- // Run the operation in the next frame so we're sure all listeners have been run - // Run the operation in the next frame so we're sure all listeners have been run
@@ -122,15 +127,15 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/navigators/createStack
-} -}
- -
-export default createNavigatorFactory< -export default createNavigatorFactory<
- StackNavigationState, - StackNavigationState<ParamListBase>,
- StackNavigationOptions, - StackNavigationOptions,
- StackNavigationEventMap, - StackNavigationEventMap,
- typeof StackNavigator - typeof StackNavigator
->(StackNavigator); ->(StackNavigator);
diff -Naur ../../node_modules/@react-navigation/stack/src/types.tsx src/vendor/types.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/types.tsx src/vendor/types.tsx
--- ../../node_modules/@react-navigation/stack/src/types.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/types.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/types.tsx 2020-06-24 23:18:40.000000000 +0200 +++ src/vendor/types.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -8,15 +8,28 @@ @@ -8,15 +8,29 @@
} from 'react-native'; } from 'react-native';
import type { EdgeInsets } from 'react-native-safe-area-context'; import type { EdgeInsets } from 'react-native-safe-area-context';
import type { import type {
@@ -155,6 +160,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/types.tsx src/vendor/t
+} from 'react-navigation'; +} from 'react-navigation';
+ +
+// @ts-ignore +// @ts-ignore
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+export type Route<T extends string> = NavigationRoute; +export type Route<T extends string> = NavigationRoute;
+ +
+export type NavigationStackState = NavigationState; +export type NavigationStackState = NavigationState;
@@ -164,26 +170,27 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/types.tsx src/vendor/t
+ | 'didFocus' + | 'didFocus'
+ | 'willBlur' + | 'willBlur'
+ | 'didBlur'; + | 'didBlur';
export type StackNavigationEventMap = { export type StackNavigationEventMap = {
/** /**
@@ -29,29 +42,28 @@ @@ -41,30 +55,29 @@
transitionEnd: { data: { closing: boolean } }; gestureCancel: { data: undefined };
}; };
-export type StackNavigationHelpers = NavigationHelpers< -export type StackNavigationHelpers = NavigationHelpers<
- ParamListBase, - ParamListBase,
- StackNavigationEventMap - StackNavigationEventMap
->; -> &
- - StackActionHelpers<ParamListBase>;
+export type StackNavigationHelpers = NavigationProp<NavigationStackState>; +export type StackNavigationHelpers = NavigationProp<NavigationStackState>;
export type StackNavigationProp< export type StackNavigationProp<
- ParamList extends ParamListBase, - ParamList extends ParamListBase,
- RouteName extends keyof ParamList = string - RouteName extends keyof ParamList = string
-> = NavigationProp< -> = NavigationProp<
- ParamList, - ParamList,
- RouteName, - RouteName,
- StackNavigationState, - StackNavigationState<ParamList>,
- StackNavigationOptions, - StackNavigationOptions,
- StackNavigationEventMap - StackNavigationEventMap
-> & -> &
@@ -216,9 +223,9 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/types.tsx src/vendor/t
+ callback: NavigationEventCallback + callback: NavigationEventCallback
+ ) => NavigationEventSubscription; + ) => NavigationEventSubscription;
}; };
export type Layout = { width: number; height: number }; export type Layout = { width: number; height: number };
@@ -228,24 +240,27 @@ @@ -245,24 +258,27 @@
/** /**
* Navigation prop for the header. * Navigation prop for the header.
*/ */
@@ -229,22 +236,22 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/types.tsx src/vendor/t
*/ */
styleInterpolator: StackHeaderStyleInterpolator; styleInterpolator: StackHeaderStyleInterpolator;
}; };
-export type StackDescriptor = Descriptor< -export type StackDescriptor = Descriptor<
- ParamListBase, - ParamListBase,
- string, - string,
- StackNavigationState, - StackNavigationState<ParamListBase>,
- StackNavigationOptions - StackNavigationOptions
+export type StackDescriptor = NavigationDescriptor< +export type StackDescriptor = NavigationDescriptor<
+ NavigationParams, + NavigationParams,
+ StackNavigationOptions, + StackNavigationOptions,
+ StackNavigationProp + StackNavigationProp
>; >;
export type StackDescriptorMap = { export type StackDescriptorMap = {
[key: string]: StackDescriptor; [key: string]: StackDescriptor;
}; };
+export type TransitionCallbackProps = { +export type TransitionCallbackProps = {
+ closing: boolean; + closing: boolean;
+}; +};
@@ -252,29 +259,29 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/types.tsx src/vendor/t
export type StackNavigationOptions = StackHeaderOptions & export type StackNavigationOptions = StackHeaderOptions &
Partial<TransitionPreset> & { Partial<TransitionPreset> & {
/** /**
@@ -330,6 +345,8 @@ @@ -356,6 +372,8 @@
bottom?: number; * Defaults to `false` for the last screen when mode='modal', otherwise `true`.
left?: number; */
}; detachPreviousScreen?: boolean;
+ onTransitionStart?: (props: TransitionCallbackProps) => void; + onTransitionStart?: (props: TransitionCallbackProps) => void;
+ onTransitionEnd?: (props: TransitionCallbackProps) => void; + onTransitionEnd?: (props: TransitionCallbackProps) => void;
}; };
export type StackNavigationConfig = { export type StackNavigationConfig = {
diff -Naur ../../node_modules/@react-navigation/stack/src/utils/PreviousSceneContext.tsx src/vendor/utils/PreviousSceneContext.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/utils/PreviousSceneContext.tsx src/vendor/utils/PreviousSceneContext.tsx
--- ../../node_modules/@react-navigation/stack/src/utils/PreviousSceneContext.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/utils/PreviousSceneContext.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/utils/PreviousSceneContext.tsx 2020-06-24 23:26:38.000000000 +0200 +++ src/vendor/utils/PreviousSceneContext.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -1,6 +1,5 @@ @@ -1,6 +1,5 @@
import * as React from 'react'; import * as React from 'react';
-import type { Route } from '@react-navigation/native'; -import type { Route } from '@react-navigation/native';
-import type { Scene } from '../types'; -import type { Scene } from '../types';
+import type { Route, Scene } from '../types'; +import type { Route, Scene } from '../types';
const PreviousSceneContext = React.createContext< const PreviousSceneContext = React.createContext<
Scene<Route<string>> | undefined Scene<Route<string>> | undefined
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/Header.tsx src/vendor/views/Header/Header.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/Header.tsx src/vendor/views/Header/Header.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Header/Header.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Header/Header.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Header/Header.tsx 2020-06-24 23:33:25.000000000 +0200 +++ src/vendor/views/Header/Header.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -1,12 +1,15 @@ @@ -1,12 +1,15 @@
import * as React from 'react'; import * as React from 'react';
-import { StackActions } from '@react-navigation/native'; -import { StackActions } from '@react-navigation/native';
@@ -283,12 +290,12 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/Header.ts
+import { getStatusBarHeight } from 'react-native-iphone-x-helper'; +import { getStatusBarHeight } from 'react-native-iphone-x-helper';
+ +
+import HeaderSegment, { getDefaultHeaderHeight } from './HeaderSegment'; +import HeaderSegment, { getDefaultHeaderHeight } from './HeaderSegment';
-import HeaderSegment from './HeaderSegment'; -import HeaderSegment from './HeaderSegment';
import HeaderTitle from './HeaderTitle'; import HeaderTitle from './HeaderTitle';
import debounce from '../../utils/debounce'; import debounce from '../../utils/debounce';
import type { StackHeaderProps, StackHeaderTitleProps } from '../../types'; import type { StackHeaderProps, StackHeaderTitleProps } from '../../types';
-export default React.memo(function Header(props: StackHeaderProps) { -export default React.memo(function Header(props: StackHeaderProps) {
+const Header = React.memo(function Header(props: StackHeaderProps) { +const Header = React.memo(function Header(props: StackHeaderProps) {
const { const {
@@ -300,17 +307,17 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/Header.ts
? options.title ? options.title
- : scene.route.name; - : scene.route.name;
+ : scene.route.routeName; + : scene.route.routeName;
let leftLabel; let leftLabel;
@@ -38,17 +41,18 @@ @@ -38,17 +41,20 @@
? o.headerTitle ? o.headerTitle
: o.title !== undefined : o.title !== undefined
? o.title ? o.title
- : previous.route.name; - : previous.route.name;
+ : previous.route.routeName; + : previous.route.routeName;
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
const goBack = React.useCallback( const goBack = React.useCallback(
debounce(() => { debounce(() => {
@@ -319,16 +326,18 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/Header.ts
- ...StackActions.pop(), - ...StackActions.pop(),
- source: scene.route.key, - source: scene.route.key,
- }); - });
+ if (navigation.isFirstRouteInParent()) { + const key = navigation.isFirstRouteInParent()
+ // If we're the first route, we're going back to a parent navigator + ? // If we're the first route, we're going back to a parent navigator
+ // So we can't specify a key here + // So we need to get the key of the route we're nested in
+ navigation.dispatch(StackActions.pop()); + navigation.dangerouslyGetParent()?.state.key
+ } else { + : scene.route.key;
+ navigation.dispatch(StackActions.pop({ key: scene.route.key })); +
+ if (key !== undefined) {
+ navigation.dispatch(StackActions.pop({ key }));
} }
}, 50), }, 50),
[navigation, scene.route.key] [navigation, scene.route.key]
@@ -64,7 +68,10 @@ @@ -64,7 +70,10 @@
leftLabel={leftLabel} leftLabel={leftLabel}
headerTitle={ headerTitle={
typeof options.headerTitle !== 'function' typeof options.headerTitle !== 'function'
@@ -340,7 +349,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/Header.ts
: options.headerTitle : options.headerTitle
} }
onGoBack={previous ? goBack : undefined} onGoBack={previous ? goBack : undefined}
@@ -72,3 +79,18 @@ @@ -72,3 +81,18 @@
/> />
); );
}); });
@@ -360,37 +369,37 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/Header.ts
+ +
+export default Header; +export default Header;
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderBackButton.tsx src/vendor/views/Header/HeaderBackButton.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderBackButton.tsx src/vendor/views/Header/HeaderBackButton.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderBackButton.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderBackButton.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Header/HeaderBackButton.tsx 2020-06-24 23:21:49.000000000 +0200 +++ src/vendor/views/Header/HeaderBackButton.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -8,9 +8,9 @@ @@ -8,9 +8,9 @@
StyleSheet, StyleSheet,
LayoutChangeEvent, LayoutChangeEvent,
} from 'react-native'; } from 'react-native';
-import { useTheme } from '@react-navigation/native'; -import { useTheme } from '@react-navigation/native';
import MaskedView from '../MaskedView'; import MaskedView from '../MaskedView';
import { TouchableItem } from '../TouchableItem'; import TouchableItem from '../TouchableItem';
+import useTheme from '../../../utils/useTheme'; +import useTheme from '../../../utils/useTheme';
import type { StackHeaderLeftButtonProps } from '../../types'; import type { StackHeaderLeftButtonProps } from '../../types';
type Props = StackHeaderLeftButtonProps; type Props = StackHeaderLeftButtonProps;
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderBackground.tsx src/vendor/views/Header/HeaderBackground.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderBackground.tsx src/vendor/views/Header/HeaderBackground.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderBackground.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderBackground.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Header/HeaderBackground.tsx 2020-06-24 23:16:23.000000000 +0200 +++ src/vendor/views/Header/HeaderBackground.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -7,7 +7,7 @@ @@ -7,7 +7,7 @@
StyleProp, StyleProp,
ViewStyle, ViewStyle,
} from 'react-native'; } from 'react-native';
-import { useTheme } from '@react-navigation/native'; -import { useTheme } from '@react-navigation/native';
+import useTheme from '../../../utils/useTheme'; +import useTheme from '../../../utils/useTheme';
type Props = ViewProps & { type Props = ViewProps & {
style?: Animated.WithAnimatedValue<StyleProp<ViewStyle>>; style?: Animated.WithAnimatedValue<StyleProp<ViewStyle>>;
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderContainer.tsx src/vendor/views/Header/HeaderContainer.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderContainer.tsx src/vendor/views/Header/HeaderContainer.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderContainer.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderContainer.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Header/HeaderContainer.tsx 2020-06-24 23:21:29.000000000 +0200 +++ src/vendor/views/Header/HeaderContainer.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -1,11 +1,6 @@ @@ -1,11 +1,6 @@
import * as React from 'react'; import * as React from 'react';
import { View, StyleSheet, StyleProp, ViewStyle } from 'react-native'; import { Animated, View, StyleSheet, StyleProp, ViewStyle } from 'react-native';
-import { -import {
- NavigationContext, - NavigationContext,
- NavigationRouteContext, - NavigationRouteContext,
@@ -399,9 +408,9 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderCon
-} from '@react-navigation/native'; -} from '@react-navigation/native';
+import { NavigationContext } from 'react-navigation'; +import { NavigationContext } from 'react-navigation';
import type { EdgeInsets } from 'react-native-safe-area-context'; import type { EdgeInsets } from 'react-native-safe-area-context';
import Header from './Header'; import Header from './Header';
@@ -19,6 +14,7 @@ @@ -18,6 +13,7 @@
import PreviousSceneContext from '../../utils/PreviousSceneContext'; import PreviousSceneContext from '../../utils/PreviousSceneContext';
import type { import type {
Layout, Layout,
@@ -409,7 +418,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderCon
Scene, Scene,
StackHeaderStyleInterpolator, StackHeaderStyleInterpolator,
StackNavigationProp, StackNavigationProp,
@@ -109,9 +105,7 @@ @@ -99,9 +95,7 @@
insets, insets,
scene, scene,
previous, previous,
@@ -420,7 +429,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderCon
styleInterpolator: styleInterpolator:
mode === 'float' mode === 'float'
? isHeaderStatic ? isHeaderStatic
@@ -130,7 +124,7 @@ @@ -120,7 +114,7 @@
key={scene.route.key} key={scene.route.key}
value={scene.descriptor.navigation} value={scene.descriptor.navigation}
> >
@@ -429,7 +438,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderCon
<View <View
onLayout={ onLayout={
onContentHeightChange onContentHeightChange
@@ -156,7 +150,7 @@ @@ -149,7 +143,7 @@
> >
{header !== undefined ? header(props) : <Header {...props} />} {header !== undefined ? header(props) : <Header {...props} />}
</View> </View>
@@ -439,8 +448,8 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderCon
); );
})} })}
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderSegment.tsx src/vendor/views/Header/HeaderSegment.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderSegment.tsx src/vendor/views/Header/HeaderSegment.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderSegment.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderSegment.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Header/HeaderSegment.tsx 2020-06-24 23:20:58.000000000 +0200 +++ src/vendor/views/Header/HeaderSegment.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -8,7 +8,7 @@ @@ -8,7 +8,7 @@
ViewStyle, ViewStyle,
} from 'react-native'; } from 'react-native';
@@ -449,8 +458,8 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderSeg
+import type { NavigationRoute } from 'react-navigation'; +import type { NavigationRoute } from 'react-navigation';
import HeaderBackButton from './HeaderBackButton'; import HeaderBackButton from './HeaderBackButton';
import HeaderBackground from './HeaderBackground'; import HeaderBackground from './HeaderBackground';
import memoize from '../../utils/memoize'; import HeaderShownContext from '../../utils/HeaderShownContext';
@@ -28,7 +28,7 @@ @@ -29,7 +29,7 @@
onGoBack?: () => void; onGoBack?: () => void;
title?: string; title?: string;
leftLabel?: string; leftLabel?: string;
@@ -458,33 +467,34 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderSeg
+ scene: Scene<NavigationRoute>; + scene: Scene<NavigationRoute>;
styleInterpolator: StackHeaderStyleInterpolator; styleInterpolator: StackHeaderStyleInterpolator;
}; };
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderTitle.tsx src/vendor/views/Header/HeaderTitle.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Header/HeaderTitle.tsx src/vendor/views/Header/HeaderTitle.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderTitle.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Header/HeaderTitle.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Header/HeaderTitle.tsx 2020-06-24 23:16:23.000000000 +0200 +++ src/vendor/views/Header/HeaderTitle.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -1,6 +1,6 @@ @@ -7,7 +7,7 @@
import * as React from 'react'; StyleProp,
import { Animated, StyleSheet, Platform } from 'react-native'; TextStyle,
} from 'react-native';
-import { useTheme } from '@react-navigation/native'; -import { useTheme } from '@react-navigation/native';
+import useTheme from '../../../utils/useTheme'; +import useTheme from '../../../utils/useTheme';
type Props = Omit<React.ComponentProps<typeof Animated.Text>, 'key'> & { type Props = Omit<TextProps, 'style'> & {
tintColor?: string; tintColor?: string;
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/Card.tsx src/vendor/views/Stack/Card.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/Card.tsx src/vendor/views/Stack/Card.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Stack/Card.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Stack/Card.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Stack/Card.tsx 2020-06-24 23:16:23.000000000 +0200 +++ src/vendor/views/Stack/Card.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -146,7 +146,7 @@ @@ -162,7 +162,7 @@
private interactionHandle: number | undefined; private interactionHandle: number | undefined;
- private pendingGestureCallback: number | undefined; - private pendingGestureCallback: number | undefined;
+ private pendingGestureCallback: any; + private pendingGestureCallback: any;
private animate = ({ private lastToValue: number | undefined;
closing,
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/CardContainer.tsx src/vendor/views/Stack/CardContainer.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/CardContainer.tsx src/vendor/views/Stack/CardContainer.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Stack/CardContainer.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Stack/CardContainer.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Stack/CardContainer.tsx 2020-06-24 23:20:38.000000000 +0200 +++ src/vendor/views/Stack/CardContainer.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -1,12 +1,13 @@ @@ -1,12 +1,13 @@
import * as React from 'react'; import * as React from 'react';
import { Animated, View, StyleSheet, StyleProp, ViewStyle } from 'react-native'; import { Animated, View, StyleSheet, StyleProp, ViewStyle } from 'react-native';
@@ -501,18 +511,22 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/CardContai
Layout, Layout,
StackHeaderMode, StackHeaderMode,
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/CardStack.tsx src/vendor/views/Stack/CardStack.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/CardStack.tsx src/vendor/views/Stack/CardStack.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Stack/CardStack.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Stack/CardStack.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Stack/CardStack.tsx 2020-06-24 23:20:16.000000000 +0200 +++ src/vendor/views/Stack/CardStack.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -7,7 +7,7 @@ @@ -6,11 +6,7 @@
Platform, Dimensions,
} from 'react-native'; } from 'react-native';
import type { EdgeInsets } from 'react-native-safe-area-context'; import type { EdgeInsets } from 'react-native-safe-area-context';
-import type { Route, StackNavigationState } from '@react-navigation/native'; -import type {
- ParamListBase,
- Route,
- StackNavigationState,
-} from '@react-navigation/native';
+import type { NavigationState as StackNavigationState } from 'react-navigation'; +import type { NavigationState as StackNavigationState } from 'react-navigation';
import { MaybeScreenContainer, MaybeScreen } from '../Screens'; import {
import { getDefaultHeaderHeight } from '../Header/HeaderSegment'; MaybeScreenContainer,
@@ -25,6 +25,7 @@ @@ -31,6 +27,7 @@
Layout, Layout,
StackHeaderMode, StackHeaderMode,
StackCardMode, StackCardMode,
@@ -520,10 +534,19 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/CardStack.
Scene, Scene,
StackDescriptorMap, StackDescriptorMap,
StackNavigationOptions, StackNavigationOptions,
@@ -44,7 +41,7 @@
type Props = {
mode: StackCardMode;
insets: EdgeInsets;
- state: StackNavigationState<ParamListBase>;
+ state: StackNavigationState;
descriptors: StackDescriptorMap;
routes: Route<string>[];
openingRouteKeys: string[];
diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.tsx src/vendor/views/Stack/StackView.tsx diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.tsx src/vendor/views/Stack/StackView.tsx
--- ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.tsx 2020-06-24 23:11:52.000000000 +0200 --- ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.tsx 2020-11-10 21:02:55.000000000 +0100
+++ src/vendor/views/Stack/StackView.tsx 2020-06-24 23:19:46.000000000 +0200 +++ src/vendor/views/Stack/StackView.tsx 2020-11-10 21:04:07.000000000 +0100
@@ -2,11 +2,11 @@ @@ -2,12 +2,11 @@
import { View, Platform, StyleSheet } from 'react-native'; import { View, Platform, StyleSheet } from 'react-native';
import { SafeAreaConsumer, EdgeInsets } from 'react-native-safe-area-context'; import { SafeAreaConsumer, EdgeInsets } from 'react-native-safe-area-context';
import { import {
@@ -531,15 +554,16 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.
StackActions, StackActions,
- StackNavigationState, - StackNavigationState,
- Route, - Route,
- ParamListBase,
-} from '@react-navigation/native'; -} from '@react-navigation/native';
+ NavigationState as StackNavigationState, + NavigationState as StackNavigationState,
+ NavigationActions, + NavigationActions,
+ SceneView, + SceneView,
+} from 'react-navigation'; +} from 'react-navigation';
import { GestureHandlerRootView } from '../GestureHandler'; import { GestureHandlerRootView } from '../GestureHandler';
import CardStack from './CardStack'; import CardStack from './CardStack';
@@ -16,6 +16,7 @@ @@ -17,6 +16,7 @@
} from '../Header/HeaderContainer'; } from '../Header/HeaderContainer';
import SafeAreaProviderCompat from '../SafeAreaProviderCompat'; import SafeAreaProviderCompat from '../SafeAreaProviderCompat';
import type { import type {
@@ -547,29 +571,33 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.
StackNavigationHelpers, StackNavigationHelpers,
StackNavigationConfig, StackNavigationConfig,
StackDescriptorMap, StackDescriptorMap,
@@ -25,6 +26,7 @@ @@ -24,9 +24,10 @@
state: StackNavigationState; import HeaderShownContext from '../../utils/HeaderShownContext';
type Props = StackNavigationConfig & {
- state: StackNavigationState<ParamListBase>;
+ state: StackNavigationState;
navigation: StackNavigationHelpers; navigation: StackNavigationHelpers;
descriptors: StackDescriptorMap; descriptors: StackDescriptorMap;
+ screenProps: unknown; + screenProps: unknown;
}; };
type State = { type State = {
@@ -293,7 +295,9 @@ @@ -295,7 +296,9 @@
return false; return false;
} }
- return gestureEnabled !== false; - return gestureEnabled !== false;
+ return gestureEnabled !== undefined + return gestureEnabled !== undefined
+ ? gestureEnabled + ? gestureEnabled
+ : Platform.OS !== 'android'; + : Platform.OS !== 'android';
} }
return false; return false;
@@ -321,26 +325,49 @@ @@ -323,26 +326,49 @@
return null; return null;
} }
- return descriptor.render(); - return descriptor.render();
+ const { navigation, getComponent } = descriptor; + const { navigation, getComponent } = descriptor;
+ const SceneComponent = getComponent(); + const SceneComponent = getComponent();
@@ -582,11 +610,11 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.
+ /> + />
+ ); + );
}; };
private renderHeader = (props: HeaderContainerProps) => { private renderHeader = (props: HeaderContainerProps) => {
return <HeaderContainer {...props} />; return <HeaderContainer {...props} />;
}; };
+ private handleTransitionComplete = () => { + private handleTransitionComplete = () => {
+ const { state, navigation } = this.props; + const { state, navigation } = this.props;
+ +
@@ -603,7 +631,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.
private handleOpenRoute = ({ route }: { route: Route<string> }) => { private handleOpenRoute = ({ route }: { route: Route<string> }) => {
const { state, navigation } = this.props; const { state, navigation } = this.props;
const { closingRouteKeys, replacingRouteKeys } = this.state; const { closingRouteKeys, replacingRouteKeys } = this.state;
+ this.handleTransitionComplete(); + this.handleTransitionComplete();
+ +
if ( if (
@@ -619,7 +647,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.
} else { } else {
this.setState((state) => ({ this.setState((state) => ({
routes: state.replacingRouteKeys.length routes: state.replacingRouteKeys.length
@@ -366,12 +393,11 @@ @@ -368,12 +394,11 @@
// If a route exists in state, trigger a pop // If a route exists in state, trigger a pop
// This will happen in when the route was closed from the card component // This will happen in when the route was closed from the card component
// e.g. When the close animation triggered from a gesture ends // e.g. When the close animation triggered from a gesture ends
@@ -636,7 +664,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.
// We need to clean up any state tracking the route and pop it immediately // We need to clean up any state tracking the route and pop it immediately
this.setState((state) => ({ this.setState((state) => ({
routes: state.routes.filter((r) => r.key !== route.key), routes: state.routes.filter((r) => r.key !== route.key),
@@ -388,26 +414,29 @@ @@ -390,47 +415,41 @@
private handleTransitionStart = ( private handleTransitionStart = (
{ route }: { route: Route<string> }, { route }: { route: Route<string> },
closing: boolean closing: boolean
@@ -653,7 +681,7 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.
+ +
+ descriptor?.options.onTransitionStart?.({ closing }); + descriptor?.options.onTransitionStart?.({ closing });
+ }; + };
private handleTransitionEnd = ( private handleTransitionEnd = (
{ route }: { route: Route<string> }, { route }: { route: Route<string> },
closing: boolean closing: boolean
@@ -663,14 +691,46 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.
- data: { closing }, - data: { closing },
- target: route.key, - target: route.key,
- }); - });
-
- private handleGestureStart = ({ route }: { route: Route<string> }) => {
- this.props.navigation.emit({
- type: 'gestureStart',
- target: route.key,
- });
- };
-
- private handleGestureEnd = ({ route }: { route: Route<string> }) => {
- this.props.navigation.emit({
- type: 'gestureEnd',
- target: route.key,
- });
- };
-
- private handleGestureCancel = ({ route }: { route: Route<string> }) => {
- this.props.navigation.emit({
- type: 'gestureCancel',
- target: route.key,
- });
+ ) => { + ) => {
+ const { descriptors } = this.props; + const { descriptors } = this.props;
+ const descriptor = + const descriptor =
+ descriptors[route.key] || this.state.descriptors[route.key]; + descriptors[route.key] || this.state.descriptors[route.key];
+ +
+ descriptor?.options.onTransitionEnd?.({ closing }); + descriptor?.options.onTransitionStart?.({ closing });
+ }; + };
+
+ private handleGestureStart = () => {
+ // Do nothing
+ };
+
+ private handleGestureEnd = () => {
+ // Do nothing
+ };
+
+ private handleGestureCancel = () => {
+ // Do nothing
};
render() { render() {
const { const {
state, state,
@@ -678,16 +738,16 @@ diff -Naur ../../node_modules/@react-navigation/stack/src/views/Stack/StackView.
navigation, navigation,
keyboardHandlingEnabled, keyboardHandlingEnabled,
mode = 'card', mode = 'card',
@@ -427,7 +456,7 @@ @@ -450,7 +469,7 @@
} = this.state; } = this.state;
return ( return (
- <NavigationHelpersContext.Provider value={navigation}> - <NavigationHelpersContext.Provider value={navigation}>
+ <> + <>
<GestureHandlerWrapper style={styles.container}> <GestureHandlerWrapper style={styles.container}>
<SafeAreaProviderCompat> <SafeAreaProviderCompat>
<SafeAreaConsumer> <SafeAreaConsumer>
@@ -460,7 +489,7 @@ @@ -491,7 +510,7 @@
</SafeAreaConsumer> </SafeAreaConsumer>
</SafeAreaProviderCompat> </SafeAreaProviderCompat>
</GestureHandlerWrapper> </GestureHandlerWrapper>

View File

@@ -11,12 +11,9 @@ exports[`Nested navigators renders succesfully as direct child 1`] = `
<View <View
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Array [ Object {
Object { "zIndex": 1,
"zIndex": 1, }
},
false,
]
} }
> >
<View <View
@@ -99,6 +96,7 @@ exports[`Nested navigators renders succesfully as direct child 1`] = `
> >
<Text <Text
accessibilityRole="header" accessibilityRole="header"
aria-level="1"
numberOfLines={1} numberOfLines={1}
onLayout={[Function]} onLayout={[Function]}
style={ style={
@@ -152,17 +150,23 @@ exports[`Nested navigators renders succesfully as direct child 1`] = `
onClose={[Function]} onClose={[Function]}
onGestureBegin={[Function]} onGestureBegin={[Function]}
onGestureCanceled={[Function]} onGestureCanceled={[Function]}
onGestureEnd={[Function]}
onOpen={[Function]} onOpen={[Function]}
onTransitionStart={[Function]} onTransition={[Function]}
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Object { Array [
"bottom": 0, Object {
"left": 0, "overflow": undefined,
"position": "absolute", },
"right": 0, Object {
"top": 0, "bottom": 0,
} "left": 0,
"position": "absolute",
"right": 0,
"top": 0,
},
]
} }
transitionSpec={ transitionSpec={
Object { Object {
@@ -192,6 +196,7 @@ exports[`Nested navigators renders succesfully as direct child 1`] = `
} }
> >
<View <View
needsOffscreenAlphaCompositing={false}
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Object { Object {
@@ -283,6 +288,112 @@ exports[`Nested navigators renders succesfully as direct child 1`] = `
} }
} }
> >
<View
pointerEvents="box-none"
style={
Object {
"zIndex": 1,
}
}
>
<View
accessibilityElementsHidden={false}
importantForAccessibility="auto"
onLayout={[Function]}
pointerEvents="box-none"
style={null}
>
<View
pointerEvents="box-none"
style={
Object {
"bottom": 0,
"left": 0,
"opacity": 1,
"position": "absolute",
"right": 0,
"top": 0,
"zIndex": 0,
}
}
>
<View
style={
Object {
"backgroundColor": "#fff",
"borderBottomColor": "#a7a7aa",
"flex": 1,
"shadowColor": "#a7a7aa",
"shadowOffset": Object {
"height": 0.5,
"width": 0,
},
"shadowOpacity": 0.85,
"shadowRadius": 0,
}
}
/>
</View>
<View
pointerEvents="box-none"
style={
Object {
"height": 44,
"maxHeight": undefined,
"minHeight": undefined,
"opacity": undefined,
"transform": undefined,
}
}
>
<View
pointerEvents="none"
style={
Object {
"height": 0,
}
}
/>
<View
pointerEvents="box-none"
style={
Object {
"alignItems": "center",
"flex": 1,
"flexDirection": "row",
"justifyContent": "center",
}
}
>
<View
pointerEvents="box-none"
style={
Object {
"marginHorizontal": 16,
"opacity": 1,
}
}
>
<Text
accessibilityRole="header"
aria-level="1"
numberOfLines={1}
onLayout={[Function]}
style={
Object {
"color": "rgba(0, 0, 0, 0.9)",
"fontSize": 17,
"fontWeight": "600",
}
}
>
Home
</Text>
</View>
</View>
</View>
</View>
</View>
<View <View
onLayout={[Function]} onLayout={[Function]}
style={ style={
@@ -319,17 +430,23 @@ exports[`Nested navigators renders succesfully as direct child 1`] = `
onClose={[Function]} onClose={[Function]}
onGestureBegin={[Function]} onGestureBegin={[Function]}
onGestureCanceled={[Function]} onGestureCanceled={[Function]}
onGestureEnd={[Function]}
onOpen={[Function]} onOpen={[Function]}
onTransitionStart={[Function]} onTransition={[Function]}
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Object { Array [
"bottom": 0, Object {
"left": 0, "overflow": undefined,
"position": "absolute", },
"right": 0, Object {
"top": 0, "bottom": 0,
} "left": 0,
"position": "absolute",
"right": 0,
"top": 0,
},
]
} }
transitionSpec={ transitionSpec={
Object { Object {
@@ -359,11 +476,11 @@ exports[`Nested navigators renders succesfully as direct child 1`] = `
} }
> >
<View <View
needsOffscreenAlphaCompositing={false}
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Object { Object {
"flex": 1, "flex": 1,
"marginTop": 0,
} }
} }
> >
@@ -452,22 +569,6 @@ exports[`Nested navigators renders succesfully as direct child 1`] = `
</View> </View>
</View> </View>
</View> </View>
<View
pointerEvents="box-none"
style={
Array [
Object {
"zIndex": 1,
},
Object {
"left": 0,
"position": "absolute",
"right": 0,
"top": 0,
},
]
}
/>
</View> </View>
</View> </View>
</View> </View>

View File

@@ -11,12 +11,9 @@ exports[`StackNavigator applies correct values when headerRight is present 1`] =
<View <View
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Array [ Object {
Object { "zIndex": 1,
"zIndex": 1, }
},
false,
]
} }
> >
<View <View
@@ -100,6 +97,7 @@ exports[`StackNavigator applies correct values when headerRight is present 1`] =
> >
<Text <Text
accessibilityRole="header" accessibilityRole="header"
aria-level="1"
numberOfLines={1} numberOfLines={1}
onLayout={[Function]} onLayout={[Function]}
style={ style={
@@ -169,17 +167,23 @@ exports[`StackNavigator applies correct values when headerRight is present 1`] =
onClose={[Function]} onClose={[Function]}
onGestureBegin={[Function]} onGestureBegin={[Function]}
onGestureCanceled={[Function]} onGestureCanceled={[Function]}
onGestureEnd={[Function]}
onOpen={[Function]} onOpen={[Function]}
onTransitionStart={[Function]} onTransition={[Function]}
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Object { Array [
"bottom": 0, Object {
"left": 0, "overflow": undefined,
"position": "absolute", },
"right": 0, Object {
"top": 0, "bottom": 0,
} "left": 0,
"position": "absolute",
"right": 0,
"top": 0,
},
]
} }
transitionSpec={ transitionSpec={
Object { Object {
@@ -209,6 +213,7 @@ exports[`StackNavigator applies correct values when headerRight is present 1`] =
} }
> >
<View <View
needsOffscreenAlphaCompositing={false}
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Object { Object {
@@ -315,12 +320,9 @@ exports[`StackNavigator renders successfully 1`] = `
<View <View
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Array [ Object {
Object { "zIndex": 1,
"zIndex": 1, }
},
false,
]
} }
> >
<View <View
@@ -404,6 +406,7 @@ exports[`StackNavigator renders successfully 1`] = `
> >
<Text <Text
accessibilityRole="header" accessibilityRole="header"
aria-level="1"
numberOfLines={1} numberOfLines={1}
onLayout={[Function]} onLayout={[Function]}
style={ style={
@@ -457,17 +460,23 @@ exports[`StackNavigator renders successfully 1`] = `
onClose={[Function]} onClose={[Function]}
onGestureBegin={[Function]} onGestureBegin={[Function]}
onGestureCanceled={[Function]} onGestureCanceled={[Function]}
onGestureEnd={[Function]}
onOpen={[Function]} onOpen={[Function]}
onTransitionStart={[Function]} onTransition={[Function]}
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Object { Array [
"bottom": 0, Object {
"left": 0, "overflow": undefined,
"position": "absolute", },
"right": 0, Object {
"top": 0, "bottom": 0,
} "left": 0,
"position": "absolute",
"right": 0,
"top": 0,
},
]
} }
transitionSpec={ transitionSpec={
Object { Object {
@@ -497,6 +506,7 @@ exports[`StackNavigator renders successfully 1`] = `
} }
> >
<View <View
needsOffscreenAlphaCompositing={false}
pointerEvents="box-none" pointerEvents="box-none"
style={ style={
Object { Object {

View File

@@ -289,8 +289,8 @@ export function forScaleFromCenterAndroid({
); );
const opacity = progress.interpolate({ const opacity = progress.interpolate({
inputRange: [0, 0.8, 1, 1.2, 2], inputRange: [0, 0.75, 0.875, 1, 1.0825, 1.2075, 2],
outputRange: [0, 0.5, 1, 0.33, 0], outputRange: [0, 0, 1, 1, 1, 1, 0],
}); });
const scale = conditional( const scale = conditional(

View File

@@ -18,6 +18,7 @@ import {
import type { TransitionPreset } from '../types'; import type { TransitionPreset } from '../types';
const ANDROID_VERSION_PIE = 28; const ANDROID_VERSION_PIE = 28;
const ANDROID_VERSION_10 = 29;
/** /**
* Standard iOS navigation transition. * Standard iOS navigation transition.
@@ -102,10 +103,13 @@ export const ScaleFromCenterAndroid: TransitionPreset = {
*/ */
export const DefaultTransition = Platform.select({ export const DefaultTransition = Platform.select({
ios: SlideFromRightIOS, ios: SlideFromRightIOS,
default: android:
Platform.OS === 'android' && Platform.Version >= ANDROID_VERSION_PIE Platform.Version >= ANDROID_VERSION_10
? ScaleFromCenterAndroid
: Platform.Version >= ANDROID_VERSION_PIE
? RevealFromBottomAndroid ? RevealFromBottomAndroid
: FadeFromBottomAndroid, : FadeFromBottomAndroid,
default: ScaleFromCenterAndroid,
}); });
/** /**

View File

@@ -57,4 +57,5 @@ export type {
StackHeaderInterpolatedStyle, StackHeaderInterpolatedStyle,
StackHeaderInterpolationProps, StackHeaderInterpolationProps,
StackHeaderStyleInterpolator, StackHeaderStyleInterpolator,
TransitionPreset,
} from './types'; } from './types';

View File

@@ -21,6 +21,7 @@ import type {
} from 'react-navigation'; } from 'react-navigation';
// @ts-ignore // @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type Route<T extends string> = NavigationRoute; export type Route<T extends string> = NavigationRoute;
export type NavigationStackState = NavigationState; export type NavigationStackState = NavigationState;
@@ -40,9 +41,22 @@ export type StackNavigationEventMap = {
* Event which fires when a transition animation ends. * Event which fires when a transition animation ends.
*/ */
transitionEnd: { data: { closing: boolean } }; transitionEnd: { data: { closing: boolean } };
/**
* Event which fires when navigation gesture starts.
*/
gestureStart: { data: undefined };
/**
* Event which fires when navigation gesture is completed.
*/
gestureEnd: { data: undefined };
/**
* Event which fires when navigation gesture is canceled.
*/
gestureCancel: { data: undefined };
}; };
export type StackNavigationHelpers = NavigationProp<NavigationStackState>; export type StackNavigationHelpers = NavigationProp<NavigationStackState>;
export type StackNavigationProp< export type StackNavigationProp<
State = NavigationRoute, State = NavigationRoute,
Params = NavigationParams Params = NavigationParams
@@ -124,7 +138,7 @@ export type StackHeaderOptions = {
/** /**
* Style object for the title component. * Style object for the title component.
*/ */
headerTitleStyle?: React.ComponentProps<typeof Animated.Text>['style']; headerTitleStyle?: Animated.WithAnimatedValue<StyleProp<TextStyle>>;
/** /**
* Style object for the container of the `headerTitle` component, for example to add padding. * Style object for the container of the `headerTitle` component, for example to add padding.
* By default, `headerTitleContainerStyle` is with an absolute position style and offsets both `left` and `right`. * By default, `headerTitleContainerStyle` is with an absolute position style and offsets both `left` and `right`.
@@ -144,6 +158,10 @@ export type StackHeaderOptions = {
* Whether back button title font should scale to respect Text Size accessibility settings. Defaults to `false`. * Whether back button title font should scale to respect Text Size accessibility settings. Defaults to `false`.
*/ */
headerBackAllowFontScaling?: boolean; headerBackAllowFontScaling?: boolean;
/**
* Accessibility label for the header back button.
*/
headerBackAccessibilityLabel?: string;
/** /**
* Title string used by the back button on iOS. Defaults to the previous scene's `headerTitle`. * Title string used by the back button on iOS. Defaults to the previous scene's `headerTitle`.
* Use `headerBackTitleVisible: false` to hide it. * Use `headerBackTitleVisible: false` to hide it.
@@ -288,7 +306,9 @@ export type StackNavigationOptions = StackHeaderOptions &
/** /**
* Function that returns a React Element to display as a overlay for the card. * Function that returns a React Element to display as a overlay for the card.
*/ */
cardOverlay?: (props: { style: StyleProp<ViewStyle> }) => React.ReactNode; cardOverlay?: (props: {
style: Animated.WithAnimatedValue<StyleProp<ViewStyle>>;
}) => React.ReactNode;
/** /**
* Style object for the card in stack. * Style object for the card in stack.
* You can provide a custom background color to use instead of the default background here. * You can provide a custom background color to use instead of the default background here.
@@ -321,11 +341,11 @@ export type StackNavigationOptions = StackHeaderOptions &
*/ */
gestureResponseDistance?: { gestureResponseDistance?: {
/** /**
* Distance for horizontal direction. Defaults to 25. * Distance for vertical direction. Defaults to 135.
*/ */
vertical?: number; vertical?: number;
/** /**
* Distance for vertical direction. Defaults to 135. * Distance for horizontal direction. Defaults to 25.
*/ */
horizontal?: number; horizontal?: number;
}; };
@@ -345,6 +365,13 @@ export type StackNavigationOptions = StackHeaderOptions &
bottom?: number; bottom?: number;
left?: number; left?: number;
}; };
/**
* Whether to detach the previous screen from the view hierarchy to save memory.
* Set it to `false` if you need the previous screen to be seen through the active screen.
* Only applicable if `detachInactiveScreens` isn't set to `false`.
* Defaults to `false` for the last screen when mode='modal', otherwise `true`.
*/
detachPreviousScreen?: boolean;
onTransitionStart?: (props: TransitionCallbackProps) => void; onTransitionStart?: (props: TransitionCallbackProps) => void;
onTransitionEnd?: (props: TransitionCallbackProps) => void; onTransitionEnd?: (props: TransitionCallbackProps) => void;
}; };
@@ -357,6 +384,12 @@ export type StackNavigationConfig = {
* Defaults to `true`. * Defaults to `true`.
*/ */
keyboardHandlingEnabled?: boolean; keyboardHandlingEnabled?: boolean;
/**
* Whether inactive screens should be detached from the view hierarchy to save memory.
* Make sure to call `enableScreens` from `react-native-screens` to make it work.
* Defaults to `true` on Android, depends on the version of `react-native-screens` on iOS.
*/
detachInactiveScreens?: boolean;
}; };
export type StackHeaderLeftButtonProps = { export type StackHeaderLeftButtonProps = {
@@ -423,6 +456,10 @@ export type StackHeaderLeftButtonProps = {
* Accessibility label for the button for screen readers. * Accessibility label for the button for screen readers.
*/ */
accessibilityLabel?: string; accessibilityLabel?: string;
/**
* Style object for the button.
*/
style?: StyleProp<ViewStyle>;
}; };
export type StackHeaderTitleProps = { export type StackHeaderTitleProps = {
@@ -445,7 +482,7 @@ export type StackHeaderTitleProps = {
/** /**
* Style object for the title element. * Style object for the title element.
*/ */
style?: React.ComponentProps<typeof Animated.Text>['style']; style?: Animated.WithAnimatedValue<StyleProp<TextStyle>>;
}; };
export type TransitionSpec = export type TransitionSpec =

View File

@@ -5,7 +5,7 @@ import { BaseButton } from 'react-native-gesture-handler';
const AnimatedBaseButton = Animated.createAnimatedComponent(BaseButton); const AnimatedBaseButton = Animated.createAnimatedComponent(BaseButton);
type Props = React.ComponentProps<typeof BaseButton> & { type Props = React.ComponentProps<typeof BaseButton> & {
activeOpacity: number; pressOpacity: number;
}; };
const useNativeDriver = Platform.OS !== 'web'; const useNativeDriver = Platform.OS !== 'web';
@@ -27,7 +27,7 @@ export default class BorderlessButton extends React.Component<Props> {
overshootClamping: true, overshootClamping: true,
restDisplacementThreshold: 0.01, restDisplacementThreshold: 0.01,
restSpeedThreshold: 0.01, restSpeedThreshold: 0.01,
toValue: active ? this.props.activeOpacity : 1, toValue: active ? this.props.pressOpacity : 1,
useNativeDriver, useNativeDriver,
}).start(); }).start();
} }
@@ -39,7 +39,6 @@ export default class BorderlessButton extends React.Component<Props> {
const { children, style, enabled, ...rest } = this.props; const { children, style, enabled, ...rest } = this.props;
return ( return (
// @ts-expect-error: the Animated.createAnimatedComponent types don't work properly
<AnimatedBaseButton <AnimatedBaseButton
{...rest} {...rest}
onActiveStateChange={this.handleActiveStateChange} onActiveStateChange={this.handleActiveStateChange}

View File

@@ -0,0 +1 @@
export * from './GestureHandlerNative';

View File

@@ -0,0 +1 @@
export * from './GestureHandlerNative';

View File

@@ -47,12 +47,14 @@ const Header = React.memo(function Header(props: StackHeaderProps) {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
const goBack = React.useCallback( const goBack = React.useCallback(
debounce(() => { debounce(() => {
if (navigation.isFirstRouteInParent()) { const key = navigation.isFirstRouteInParent()
// If we're the first route, we're going back to a parent navigator ? // If we're the first route, we're going back to a parent navigator
// So we can't specify a key here // So we need to get the key of the route we're nested in
navigation.dispatch(StackActions.pop()); navigation.dangerouslyGetParent()?.state.key
} else { : scene.route.key;
navigation.dispatch(StackActions.pop({ key: scene.route.key }));
if (key !== undefined) {
navigation.dispatch(StackActions.pop({ key }));
} }
}, 50), }, 50),
[navigation, scene.route.key] [navigation, scene.route.key]

View File

@@ -9,7 +9,7 @@ import {
LayoutChangeEvent, LayoutChangeEvent,
} from 'react-native'; } from 'react-native';
import MaskedView from '../MaskedView'; import MaskedView from '../MaskedView';
import { TouchableItem } from '../TouchableItem'; import TouchableItem from '../TouchableItem';
import useTheme from '../../../utils/useTheme'; import useTheme from '../../../utils/useTheme';
import type { StackHeaderLeftButtonProps } from '../../types'; import type { StackHeaderLeftButtonProps } from '../../types';
@@ -30,6 +30,7 @@ export default function HeaderBackButton({
titleLayout, titleLayout,
truncatedLabel = 'Back', truncatedLabel = 'Back',
accessibilityLabel = label && label !== 'Back' ? `${label}, back` : 'Go back', accessibilityLabel = label && label !== 'Back' ? `${label}, back` : 'Go back',
style,
}: Props) { }: Props) {
const { dark, colors } = useTheme(); const { dark, colors } = useTheme();
@@ -160,7 +161,7 @@ export default function HeaderBackButton({
delayPressIn={0} delayPressIn={0}
onPress={disabled ? undefined : handlePress} onPress={disabled ? undefined : handlePress}
pressColor={pressColorAndroid} pressColor={pressColorAndroid}
style={[styles.container, disabled && styles.disabled]} style={[styles.container, disabled && styles.disabled, style]}
hitSlop={Platform.select({ hitSlop={Platform.select({
ios: undefined, ios: undefined,
default: { top: 16, right: 16, bottom: 16, left: 16 }, default: { top: 16, right: 16, bottom: 16, left: 16 },

View File

@@ -1,5 +1,5 @@
import * as React from 'react'; import * as React from 'react';
import { View, StyleSheet, StyleProp, ViewStyle } from 'react-native'; import { Animated, View, StyleSheet, StyleProp, ViewStyle } from 'react-native';
import { NavigationContext } from 'react-navigation'; import { NavigationContext } from 'react-navigation';
import type { EdgeInsets } from 'react-native-safe-area-context'; import type { EdgeInsets } from 'react-native-safe-area-context';
@@ -10,7 +10,6 @@ import {
forNoAnimation, forNoAnimation,
forSlideRight, forSlideRight,
} from '../../TransitionConfigs/HeaderStyleInterpolators'; } from '../../TransitionConfigs/HeaderStyleInterpolators';
import HeaderShownContext from '../../utils/HeaderShownContext';
import PreviousSceneContext from '../../utils/PreviousSceneContext'; import PreviousSceneContext from '../../utils/PreviousSceneContext';
import type { import type {
Layout, Layout,
@@ -28,7 +27,6 @@ export type Props = {
scenes: (Scene<Route<string>> | undefined)[]; scenes: (Scene<Route<string>> | undefined)[];
getPreviousScene: (props: { getPreviousScene: (props: {
route: Route<string>; route: Route<string>;
index: number;
}) => Scene<Route<string>> | undefined; }) => Scene<Route<string>> | undefined;
getFocusedRoute: () => Route<string>; getFocusedRoute: () => Route<string>;
onContentHeightChange?: (props: { onContentHeightChange?: (props: {
@@ -53,21 +51,17 @@ export default function HeaderContainer({
style, style,
}: Props) { }: Props) {
const focusedRoute = getFocusedRoute(); const focusedRoute = getFocusedRoute();
const isParentHeaderShown = React.useContext(HeaderShownContext);
const parentPreviousScene = React.useContext(PreviousSceneContext); const parentPreviousScene = React.useContext(PreviousSceneContext);
return ( return (
<View pointerEvents="box-none" style={style}> <Animated.View pointerEvents="box-none" style={style}>
{scenes.slice(-3).map((scene, i, self) => { {scenes.slice(-3).map((scene, i, self) => {
if ((mode === 'screen' && i !== self.length - 1) || !scene) { if ((mode === 'screen' && i !== self.length - 1) || !scene) {
return null; return null;
} }
const { const { header, headerShown = true, headerTransparent } =
header, scene.descriptor.options || {};
headerShown = isParentHeaderShown === false,
headerTransparent,
} = scene.descriptor.options || {};
if (!headerShown) { if (!headerShown) {
return null; return null;
@@ -75,21 +69,17 @@ export default function HeaderContainer({
const isFocused = focusedRoute.key === scene.route.key; const isFocused = focusedRoute.key === scene.route.key;
const previous = const previous =
getPreviousScene({ getPreviousScene({ route: scene.route }) ?? parentPreviousScene;
route: scene.route,
index: i,
}) ?? parentPreviousScene;
// If the screen is next to a headerless screen, we need to make the header appear static // If the screen is next to a headerless screen, we need to make the header appear static
// This makes the header look like it's moving with the screen // This makes the header look like it's moving with the screen
const previousScene = self[i - 1]; const previousScene = self[i - 1];
const nextScene = self[i + 1]; const nextScene = self[i + 1];
const { const { headerShown: previousHeaderShown = true } =
headerShown: previousHeaderShown = isParentHeaderShown === false, previousScene?.descriptor.options || {};
} = previousScene?.descriptor.options || {};
const { headerShown: nextHeaderShown = isParentHeaderShown === false } = const { headerShown: nextHeaderShown = true } =
nextScene?.descriptor.options || {}; nextScene?.descriptor.options || {};
const isHeaderStatic = const isHeaderStatic =
@@ -128,11 +118,14 @@ export default function HeaderContainer({
<View <View
onLayout={ onLayout={
onContentHeightChange onContentHeightChange
? (e) => ? (e) => {
const { height } = e.nativeEvent.layout;
onContentHeightChange({ onContentHeightChange({
route: scene.route, route: scene.route,
height: e.nativeEvent.layout.height, height,
}) });
}
: undefined : undefined
} }
pointerEvents={isFocused ? 'box-none' : 'none'} pointerEvents={isFocused ? 'box-none' : 'none'}
@@ -154,7 +147,7 @@ export default function HeaderContainer({
</NavigationContext.Provider> </NavigationContext.Provider>
); );
})} })}
</View> </Animated.View>
); );
} }

View File

@@ -11,6 +11,7 @@ import type { EdgeInsets } from 'react-native-safe-area-context';
import type { NavigationRoute } from 'react-navigation'; import type { NavigationRoute } from 'react-navigation';
import HeaderBackButton from './HeaderBackButton'; import HeaderBackButton from './HeaderBackButton';
import HeaderBackground from './HeaderBackground'; import HeaderBackground from './HeaderBackground';
import HeaderShownContext from '../../utils/HeaderShownContext';
import memoize from '../../utils/memoize'; import memoize from '../../utils/memoize';
import type { import type {
Layout, Layout,
@@ -32,11 +33,6 @@ type Props = StackHeaderOptions & {
styleInterpolator: StackHeaderStyleInterpolator; styleInterpolator: StackHeaderStyleInterpolator;
}; };
type State = {
titleLayout?: Layout;
leftLabelLayout?: Layout;
};
const warnIfHeaderStylesDefined = (styles: Record<string, any>) => { const warnIfHeaderStylesDefined = (styles: Record<string, any>) => {
Object.keys(styles).forEach((styleProp) => { Object.keys(styles).forEach((styleProp) => {
const value = styles[styleProp]; const value = styles[styleProp];
@@ -76,30 +72,35 @@ export const getDefaultHeaderHeight = (
return headerHeight + statusBarHeight; return headerHeight + statusBarHeight;
}; };
export default class HeaderSegment extends React.Component<Props, State> { export default function HeaderSegment(props: Props) {
state: State = {}; const [leftLabelLayout, setLeftLabelLayout] = React.useState<
Layout | undefined
>(undefined);
private handleTitleLayout = (e: LayoutChangeEvent) => { const [titleLayout, setTitleLayout] = React.useState<Layout | undefined>(
undefined
);
const isParentHeaderShown = React.useContext(HeaderShownContext);
const handleTitleLayout = (e: LayoutChangeEvent) => {
const { height, width } = e.nativeEvent.layout; const { height, width } = e.nativeEvent.layout;
this.setState(({ titleLayout }) => { setTitleLayout((titleLayout) => {
if ( if (
titleLayout && titleLayout &&
height === titleLayout.height && height === titleLayout.height &&
width === titleLayout.width width === titleLayout.width
) { ) {
return null; return titleLayout;
} }
return { return { height, width };
titleLayout: { height, width },
};
}); });
}; };
private handleLeftLabelLayout = (e: LayoutChangeEvent) => { const handleLeftLabelLayout = (e: LayoutChangeEvent) => {
const { height, width } = e.nativeEvent.layout; const { height, width } = e.nativeEvent.layout;
const { leftLabelLayout } = this.state;
if ( if (
leftLabelLayout && leftLabelLayout &&
@@ -109,10 +110,10 @@ export default class HeaderSegment extends React.Component<Props, State> {
return; return;
} }
this.setState({ leftLabelLayout: { height, width } }); setLeftLabelLayout({ height, width });
}; };
private getInterpolatedStyle = memoize( const getInterpolatedStyle = memoize(
( (
styleInterpolator: StackHeaderStyleInterpolator, styleInterpolator: StackHeaderStyleInterpolator,
layout: Layout, layout: Layout,
@@ -137,257 +138,253 @@ export default class HeaderSegment extends React.Component<Props, State> {
}) })
); );
render() { const {
const { scene,
scene, layout,
layout, insets,
insets, title: currentTitle,
title: currentTitle, leftLabel: previousTitle,
leftLabel: previousTitle, onGoBack,
onGoBack, headerTitle,
headerTitle, headerTitleAlign = Platform.select({
headerTitleAlign = Platform.select({ ios: 'center',
ios: 'center', default: 'left',
default: 'left', }),
}), headerLeft: left = onGoBack
headerLeft: left = onGoBack ? (props: StackHeaderLeftButtonProps) => <HeaderBackButton {...props} />
? (props: StackHeaderLeftButtonProps) => <HeaderBackButton {...props} /> : undefined,
: undefined, headerTransparent,
headerTransparent, headerTintColor,
headerTintColor, headerBackground,
headerBackground, headerRight: right,
headerRight: right, headerBackImage: backImage,
headerBackImage: backImage, headerBackTitle: leftLabel,
headerBackTitle: leftLabel, headerBackTitleVisible,
headerBackTitleVisible, headerTruncatedBackTitle: truncatedLabel,
headerTruncatedBackTitle: truncatedLabel, headerPressColorAndroid: pressColorAndroid,
headerPressColorAndroid: pressColorAndroid, headerBackAccessibilityLabel: backAccessibilityLabel,
headerBackAllowFontScaling: backAllowFontScaling, headerBackAllowFontScaling: backAllowFontScaling,
headerTitleAllowFontScaling: titleAllowFontScaling, headerTitleAllowFontScaling: titleAllowFontScaling,
headerTitleStyle: customTitleStyle, headerTitleStyle: customTitleStyle,
headerBackTitleStyle: customLeftLabelStyle, headerBackTitleStyle: customLeftLabelStyle,
headerLeftContainerStyle: leftContainerStyle, headerLeftContainerStyle: leftContainerStyle,
headerRightContainerStyle: rightContainerStyle, headerRightContainerStyle: rightContainerStyle,
headerTitleContainerStyle: titleContainerStyle, headerTitleContainerStyle: titleContainerStyle,
headerStyle: customHeaderStyle, headerStyle: customHeaderStyle,
headerStatusBarHeight = insets.top, headerStatusBarHeight = isParentHeaderShown ? 0 : insets.top,
styleInterpolator, styleInterpolator,
} = this.props; } = props;
const { leftLabelLayout, titleLayout } = this.state; const defaultHeight = getDefaultHeaderHeight(layout, headerStatusBarHeight);
const defaultHeight = getDefaultHeaderHeight(layout, headerStatusBarHeight); const {
height = defaultHeight,
minHeight,
maxHeight,
backgroundColor,
borderBottomColor,
borderBottomEndRadius,
borderBottomLeftRadius,
borderBottomRightRadius,
borderBottomStartRadius,
borderBottomWidth,
borderColor,
borderEndColor,
borderEndWidth,
borderLeftColor,
borderLeftWidth,
borderRadius,
borderRightColor,
borderRightWidth,
borderStartColor,
borderStartWidth,
borderStyle,
borderTopColor,
borderTopEndRadius,
borderTopLeftRadius,
borderTopRightRadius,
borderTopStartRadius,
borderTopWidth,
borderWidth,
// @ts-expect-error: web support for shadow
boxShadow,
elevation,
shadowColor,
shadowOffset,
shadowOpacity,
shadowRadius,
opacity,
transform,
...unsafeStyles
} = StyleSheet.flatten(customHeaderStyle || {}) as ViewStyle;
const { if (process.env.NODE_ENV !== 'production') {
height = defaultHeight, warnIfHeaderStylesDefined(unsafeStyles);
minHeight, }
maxHeight,
backgroundColor,
borderBottomColor,
borderBottomEndRadius,
borderBottomLeftRadius,
borderBottomRightRadius,
borderBottomStartRadius,
borderBottomWidth,
borderColor,
borderEndColor,
borderEndWidth,
borderLeftColor,
borderLeftWidth,
borderRadius,
borderRightColor,
borderRightWidth,
borderStartColor,
borderStartWidth,
borderStyle,
borderTopColor,
borderTopEndRadius,
borderTopLeftRadius,
borderTopRightRadius,
borderTopStartRadius,
borderTopWidth,
borderWidth,
// @ts-expect-error: web support for shadow
boxShadow,
elevation,
shadowColor,
shadowOffset,
shadowOpacity,
shadowRadius,
opacity,
transform,
...unsafeStyles
} = StyleSheet.flatten(customHeaderStyle || {}) as ViewStyle;
if (process.env.NODE_ENV !== 'production') { const safeStyles: ViewStyle = {
warnIfHeaderStylesDefined(unsafeStyles); backgroundColor,
borderBottomColor,
borderBottomEndRadius,
borderBottomLeftRadius,
borderBottomRightRadius,
borderBottomStartRadius,
borderBottomWidth,
borderColor,
borderEndColor,
borderEndWidth,
borderLeftColor,
borderLeftWidth,
borderRadius,
borderRightColor,
borderRightWidth,
borderStartColor,
borderStartWidth,
borderStyle,
borderTopColor,
borderTopEndRadius,
borderTopLeftRadius,
borderTopRightRadius,
borderTopStartRadius,
borderTopWidth,
borderWidth,
// @ts-expect-error: boxShadow is only for Web
boxShadow,
elevation,
shadowColor,
shadowOffset,
shadowOpacity,
shadowRadius,
opacity,
transform,
};
// Setting a property to undefined triggers default style
// So we need to filter them out
// Users can use `null` instead
for (const styleProp in safeStyles) {
// @ts-expect-error: typescript wrongly complains that styleProp cannot be used to index safeStyles
if (safeStyles[styleProp] === undefined) {
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete safeStyles[styleProp];
} }
}
const safeStyles = { const {
backgroundColor, titleStyle,
borderBottomColor, leftButtonStyle,
borderBottomEndRadius, leftLabelStyle,
borderBottomLeftRadius, rightButtonStyle,
borderBottomRightRadius, backgroundStyle,
borderBottomStartRadius, } = getInterpolatedStyle(
borderBottomWidth, styleInterpolator,
borderColor, layout,
borderEndColor, scene.progress.current,
borderEndWidth, scene.progress.next,
borderLeftColor, titleLayout,
borderLeftWidth, previousTitle ? leftLabelLayout : undefined,
borderRadius, typeof height === 'number' ? height : defaultHeight
borderRightColor, );
borderRightWidth,
borderStartColor,
borderStartWidth,
borderStyle,
borderTopColor,
borderTopEndRadius,
borderTopLeftRadius,
borderTopRightRadius,
borderTopStartRadius,
borderTopWidth,
borderWidth,
boxShadow,
elevation,
shadowColor,
shadowOffset,
shadowOpacity,
shadowRadius,
opacity,
transform,
};
// Setting a property to undefined triggers default style const leftButton = left
// So we need to filter them out ? left({
// Users can use `null` instead backImage,
for (const styleProp in safeStyles) { pressColorAndroid,
// @ts-expect-error: typescript wrongly complains that styleProp cannot be used to index safeStyles accessibilityLabel: backAccessibilityLabel,
if (safeStyles[styleProp] === undefined) { allowFontScaling: backAllowFontScaling,
// @ts-expect-error onPress: onGoBack,
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete labelVisible: headerBackTitleVisible,
delete safeStyles[styleProp]; label: leftLabel !== undefined ? leftLabel : previousTitle,
} truncatedLabel,
} labelStyle: [leftLabelStyle, customLeftLabelStyle],
onLabelLayout: handleLeftLabelLayout,
screenLayout: layout,
titleLayout,
tintColor: headerTintColor,
canGoBack: Boolean(onGoBack),
})
: null;
const { const rightButton = right ? right({ tintColor: headerTintColor }) : null;
titleStyle,
leftButtonStyle,
leftLabelStyle,
rightButtonStyle,
backgroundStyle,
} = this.getInterpolatedStyle(
styleInterpolator,
layout,
scene.progress.current,
scene.progress.next,
titleLayout,
previousTitle ? leftLabelLayout : undefined,
typeof height === 'number' ? height : defaultHeight
);
const leftButton = left return (
? left({ <React.Fragment>
backImage, <Animated.View
pressColorAndroid, pointerEvents="box-none"
allowFontScaling: backAllowFontScaling, style={[StyleSheet.absoluteFill, { zIndex: 0 }, backgroundStyle]}
onPress: onGoBack, >
labelVisible: headerBackTitleVisible, {headerBackground ? (
label: leftLabel !== undefined ? leftLabel : previousTitle, headerBackground({ style: safeStyles })
truncatedLabel, ) : headerTransparent ? null : (
labelStyle: [leftLabelStyle, customLeftLabelStyle], <HeaderBackground style={safeStyles} />
onLabelLayout: this.handleLeftLabelLayout, )}
screenLayout: layout, </Animated.View>
titleLayout, <Animated.View
tintColor: headerTintColor, pointerEvents="box-none"
canGoBack: Boolean(onGoBack), style={[{ height, minHeight, maxHeight, opacity, transform }]}
}) >
: null; <View pointerEvents="none" style={{ height: headerStatusBarHeight }} />
<View pointerEvents="box-none" style={styles.content}>
const rightButton = right ? right({ tintColor: headerTintColor }) : null; {leftButton ? (
return (
<React.Fragment>
<Animated.View
pointerEvents="box-none"
style={[StyleSheet.absoluteFill, { zIndex: 0 }, backgroundStyle]}
>
{headerBackground ? (
headerBackground({ style: safeStyles })
) : headerTransparent ? null : (
<HeaderBackground style={safeStyles} />
)}
</Animated.View>
<Animated.View
pointerEvents="box-none"
style={[{ height, minHeight, maxHeight, opacity, transform }]}
>
<View
pointerEvents="none"
style={{ height: headerStatusBarHeight }}
/>
<View pointerEvents="box-none" style={styles.content}>
{leftButton ? (
<Animated.View
pointerEvents="box-none"
style={[
styles.left,
{ left: insets.left },
leftButtonStyle,
leftContainerStyle,
]}
>
{leftButton}
</Animated.View>
) : null}
<Animated.View <Animated.View
pointerEvents="box-none" pointerEvents="box-none"
style={[ style={[
headerTitleAlign === 'left' styles.left,
? { { left: insets.left },
position: 'absolute', leftButtonStyle,
left: (leftButton ? 72 : 16) + insets.left, leftContainerStyle,
right: (rightButton ? 72 : 16) + insets.right,
}
: {
marginHorizontal:
(leftButton ? 32 : 16) +
(leftButton && headerBackTitleVisible !== false
? 40
: 0) +
Math.max(insets.left, insets.right),
},
titleStyle,
titleContainerStyle,
]} ]}
> >
{headerTitle({ {leftButton}
children: currentTitle,
onLayout: this.handleTitleLayout,
allowFontScaling: titleAllowFontScaling,
tintColor: headerTintColor,
style: customTitleStyle,
})}
</Animated.View> </Animated.View>
{rightButton ? ( ) : null}
<Animated.View <Animated.View
pointerEvents="box-none" pointerEvents="box-none"
style={[ style={[
styles.right, headerTitleAlign === 'left'
{ right: insets.right }, ? {
rightButtonStyle, position: 'absolute',
rightContainerStyle, left: (leftButton ? 72 : 16) + insets.left,
]} right: (rightButton ? 72 : 16) + insets.right,
> }
{rightButton} : {
</Animated.View> marginHorizontal:
) : null} (leftButton ? 32 : 16) +
</View> (leftButton && headerBackTitleVisible !== false
</Animated.View> ? 40
</React.Fragment> : 0) +
); Math.max(insets.left, insets.right),
} },
titleStyle,
titleContainerStyle,
]}
>
{headerTitle({
children: currentTitle,
onLayout: handleTitleLayout,
allowFontScaling: titleAllowFontScaling,
tintColor: headerTintColor,
style: customTitleStyle,
})}
</Animated.View>
{rightButton ? (
<Animated.View
pointerEvents="box-none"
style={[
styles.right,
{ right: insets.right },
rightButtonStyle,
rightContainerStyle,
]}
>
{rightButton}
</Animated.View>
) : null}
</View>
</Animated.View>
</React.Fragment>
);
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({

View File

@@ -1,10 +1,18 @@
import * as React from 'react'; import * as React from 'react';
import { Animated, StyleSheet, Platform } from 'react-native'; import {
Animated,
StyleSheet,
Platform,
TextProps,
StyleProp,
TextStyle,
} from 'react-native';
import useTheme from '../../../utils/useTheme'; import useTheme from '../../../utils/useTheme';
type Props = Omit<React.ComponentProps<typeof Animated.Text>, 'key'> & { type Props = Omit<TextProps, 'style'> & {
tintColor?: string; tintColor?: string;
children?: string; children?: string;
style?: Animated.WithAnimatedValue<StyleProp<TextStyle>>;
}; };
export default function HeaderTitle({ tintColor, style, ...rest }: Props) { export default function HeaderTitle({ tintColor, style, ...rest }: Props) {
@@ -13,6 +21,7 @@ export default function HeaderTitle({ tintColor, style, ...rest }: Props) {
return ( return (
<Animated.Text <Animated.Text
accessibilityRole="header" accessibilityRole="header"
aria-level="1"
numberOfLines={1} numberOfLines={1}
{...rest} {...rest}
style={[ style={[

View File

@@ -1,15 +1,17 @@
import * as React from 'react'; import * as React from 'react';
import { TextInput, Platform, Keyboard } from 'react-native'; import { TextInput, Keyboard, HostComponent } from 'react-native';
type Props = { type Props = {
enabled: boolean; enabled: boolean;
children: (props: { children: (props: {
onPageChangeStart: () => void; onPageChangeStart: () => void;
onPageChangeConfirm: () => void; onPageChangeConfirm: (force: boolean) => void;
onPageChangeCancel: () => void; onPageChangeCancel: () => void;
}) => React.ReactNode; }) => React.ReactNode;
}; };
type InputRef = React.ElementRef<HostComponent<unknown>> | undefined;
export default class KeyboardManager extends React.Component<Props> { export default class KeyboardManager extends React.Component<Props> {
componentWillUnmount() { componentWillUnmount() {
this.clearKeyboardTimeout(); this.clearKeyboardTimeout();
@@ -17,7 +19,7 @@ export default class KeyboardManager extends React.Component<Props> {
// Numeric id of the previously focused text input // Numeric id of the previously focused text input
// When a gesture didn't change the tab, we can restore the focused input with this // When a gesture didn't change the tab, we can restore the focused input with this
private previouslyFocusedTextInput: number | null = null; private previouslyFocusedTextInput: InputRef = undefined;
private startTimestamp: number = 0; private startTimestamp: number = 0;
private keyboardTimeout: any; private keyboardTimeout: any;
@@ -35,10 +37,9 @@ export default class KeyboardManager extends React.Component<Props> {
this.clearKeyboardTimeout(); this.clearKeyboardTimeout();
// @ts-expect-error: currentlyFocusedInput is pretty new, so not in the type definitions // @ts-expect-error: blurTextInput accepts both number and ref, but types say only ref
const input = TextInput.State.currentlyFocusedInput const input: InputRef = TextInput.State.currentlyFocusedInput
? // @ts-expect-error ? TextInput.State.currentlyFocusedInput()
TextInput.State.currentlyFocusedInput()
: TextInput.State.currentlyFocusedField(); : TextInput.State.currentlyFocusedField();
// When a page change begins, blur the currently focused input // When a page change begins, blur the currently focused input
@@ -51,23 +52,30 @@ export default class KeyboardManager extends React.Component<Props> {
this.startTimestamp = Date.now(); this.startTimestamp = Date.now();
}; };
private handlePageChangeConfirm = () => { private handlePageChangeConfirm = (force: boolean) => {
if (!this.props.enabled) { if (!this.props.enabled) {
return; return;
} }
this.clearKeyboardTimeout(); this.clearKeyboardTimeout();
const input = this.previouslyFocusedTextInput; if (force) {
// Always dismiss input, even if we don't have a ref to it
if (Platform.OS === 'android') { // We might not have the ref if onPageChangeStart was never called
// This can happen if page change was not from a gesture
Keyboard.dismiss(); Keyboard.dismiss();
} else if (input) { } else {
TextInput.State.blurTextInput(input); const input = this.previouslyFocusedTextInput;
if (input) {
// Dismiss the keyboard only if an input was a focused before
// This makes sure we don't dismiss input on going back and focusing an input
TextInput.State.blurTextInput(input);
}
} }
// Cleanup the ID on successful page change // Cleanup the ID on successful page change
this.previouslyFocusedTextInput = null; this.previouslyFocusedTextInput = undefined;
}; };
private handlePageChangeCancel = () => { private handlePageChangeCancel = () => {
@@ -91,11 +99,11 @@ export default class KeyboardManager extends React.Component<Props> {
if (Date.now() - this.startTimestamp < 100) { if (Date.now() - this.startTimestamp < 100) {
this.keyboardTimeout = setTimeout(() => { this.keyboardTimeout = setTimeout(() => {
TextInput.State.focusTextInput(input); TextInput.State.focusTextInput(input);
this.previouslyFocusedTextInput = null; this.previouslyFocusedTextInput = undefined;
}, 100); }, 100);
} else { } else {
TextInput.State.focusTextInput(input); TextInput.State.focusTextInput(input);
this.previouslyFocusedTextInput = null; this.previouslyFocusedTextInput = undefined;
} }
} }
}; };

View File

@@ -0,0 +1 @@
export { default } from './MaskedViewNative';

View File

@@ -0,0 +1 @@
export { default } from './MaskedViewNative';

View File

@@ -1,3 +1,6 @@
/**
* Use a stub for MaskedView on all Platforms that don't support it.
*/
import type * as React from 'react'; import type * as React from 'react';
type Props = { type Props = {

View File

@@ -1,3 +1,6 @@
/**
* The native MaskedView that we explicitly re-export for supported platforms: Android, iOS.
*/
import * as React from 'react'; import * as React from 'react';
import { UIManager } from 'react-native'; import { UIManager } from 'react-native';
@@ -10,6 +13,8 @@ type Props = React.ComponentProps<MaskedViewType> & {
let RNCMaskedView: MaskedViewType | undefined; let RNCMaskedView: MaskedViewType | undefined;
try { try {
// Add try/catch to support usage even if it's not installed, since it's optional.
// Newer versions of Metro will handle it properly.
RNCMaskedView = require('@react-native-community/masked-view').default; RNCMaskedView = require('@react-native-community/masked-view').default;
} catch (e) { } catch (e) {
// Ignore // Ignore

View File

@@ -34,6 +34,9 @@ class WebScreen extends React.Component<
const AnimatedWebScreen = Animated.createAnimatedComponent(WebScreen); const AnimatedWebScreen = Animated.createAnimatedComponent(WebScreen);
// @ts-ignore
export const shouldUseActivityState = Screens?.shouldUseActivityState;
export const MaybeScreenContainer = ({ export const MaybeScreenContainer = ({
enabled, enabled,
...rest ...rest
@@ -41,8 +44,11 @@ export const MaybeScreenContainer = ({
enabled: boolean; enabled: boolean;
children: React.ReactNode; children: React.ReactNode;
}) => { }) => {
if (enabled && Platform.OS !== 'web' && Screens && Screens.screensEnabled()) { if (enabled && Platform.OS !== 'web' && Screens?.screensEnabled()) {
return <Screens.ScreenContainer {...rest} />; return (
// @ts-ignore
<Screens.ScreenContainer enabled={enabled} {...rest} />
);
} }
return <View {...rest} />; return <View {...rest} />;
@@ -54,17 +60,25 @@ export const MaybeScreen = ({
...rest ...rest
}: ViewProps & { }: ViewProps & {
enabled: boolean; enabled: boolean;
active: 0 | 1 | Animated.AnimatedInterpolation; active: 0 | 1 | 2 | Animated.AnimatedInterpolation;
children: React.ReactNode; children: React.ReactNode;
}) => { }) => {
if (enabled && Platform.OS === 'web') { if (enabled && Platform.OS === 'web') {
// @ts-expect-error: the Animated.createAnimatedComponent types don't work properly
return <AnimatedWebScreen active={active} {...rest} />; return <AnimatedWebScreen active={active} {...rest} />;
} }
if (enabled && Screens && Screens.screensEnabled()) { if (enabled && Screens?.screensEnabled()) {
// @ts-expect-error: stackPresentation is incorrectly marked as required if (shouldUseActivityState) {
return <Screens.Screen active={active} {...rest} />; return (
// @ts-expect-error: there was an `active` prop and no `activityState` in older version and stackPresentation was required
<Screens.Screen enabled={enabled} activityState={active} {...rest} />
);
} else {
return (
// @ts-expect-error: there was an `active` prop and no `activityState` in older version and stackPresentation was required
<Screens.Screen enabled={enabled} active={active} {...rest} />
);
}
} }
return <View {...rest} />; return <View {...rest} />;

View File

@@ -41,7 +41,7 @@ type Props = ViewProps & {
gestureDirection: GestureDirection; gestureDirection: GestureDirection;
onOpen: () => void; onOpen: () => void;
onClose: () => void; onClose: () => void;
onTransitionStart?: (props: { closing: boolean }) => void; onTransition?: (props: { closing: boolean; gesture: boolean }) => void;
onGestureBegin?: () => void; onGestureBegin?: () => void;
onGestureCanceled?: () => void; onGestureCanceled?: () => void;
onGestureEnd?: () => void; onGestureEnd?: () => void;
@@ -79,6 +79,15 @@ const GESTURE_RESPONSE_DISTANCE_VERTICAL = 135;
const useNativeDriver = Platform.OS !== 'web'; const useNativeDriver = Platform.OS !== 'web';
const hasOpacityStyle = (style: any) => {
if (style) {
const flattenedStyle = StyleSheet.flatten(style);
return flattenedStyle.opacity != null;
}
return false;
};
export default class Card extends React.Component<Props> { export default class Card extends React.Component<Props> {
static defaultProps = { static defaultProps = {
overlayEnabled: Platform.OS !== 'ios', overlayEnabled: Platform.OS !== 'ios',
@@ -97,6 +106,7 @@ export default class Card extends React.Component<Props> {
componentDidMount() { componentDidMount() {
this.animate({ closing: this.props.closing }); this.animate({ closing: this.props.closing });
this.isCurrentlyMounted = true;
} }
componentDidUpdate(prevProps: Props) { componentDidUpdate(prevProps: Props) {
@@ -115,8 +125,11 @@ export default class Card extends React.Component<Props> {
this.inverted.setValue(getInvertedMultiplier(gestureDirection)); this.inverted.setValue(getInvertedMultiplier(gestureDirection));
} }
const toValue = this.getAnimateToValue(this.props);
if ( if (
this.getAnimateToValue(this.props) !== this.getAnimateToValue(prevProps) this.getAnimateToValue(prevProps) !== toValue ||
this.lastToValue !== toValue
) { ) {
// We need to trigger the animation when route was closed // We need to trigger the animation when route was closed
// Thr route might have been closed by a `POP` action or by a gesture // Thr route might have been closed by a `POP` action or by a gesture
@@ -128,9 +141,12 @@ export default class Card extends React.Component<Props> {
} }
componentWillUnmount() { componentWillUnmount() {
this.isCurrentlyMounted = false;
this.handleEndInteraction(); this.handleEndInteraction();
} }
private isCurrentlyMounted = false;
private isClosing = new Animated.Value(FALSE); private isClosing = new Animated.Value(FALSE);
private inverted = new Animated.Value( private inverted = new Animated.Value(
@@ -148,6 +164,8 @@ export default class Card extends React.Component<Props> {
private pendingGestureCallback: any; private pendingGestureCallback: any;
private lastToValue: number | undefined;
private animate = ({ private animate = ({
closing, closing,
velocity, velocity,
@@ -160,7 +178,7 @@ export default class Card extends React.Component<Props> {
transitionSpec, transitionSpec,
onOpen, onOpen,
onClose, onClose,
onTransitionStart, onTransition,
} = this.props; } = this.props;
const toValue = this.getAnimateToValue({ const toValue = this.getAnimateToValue({
@@ -168,6 +186,8 @@ export default class Card extends React.Component<Props> {
closing, closing,
}); });
this.lastToValue = toValue;
const spec = closing ? transitionSpec.close : transitionSpec.open; const spec = closing ? transitionSpec.close : transitionSpec.open;
const animation = const animation =
@@ -178,7 +198,7 @@ export default class Card extends React.Component<Props> {
clearTimeout(this.pendingGestureCallback); clearTimeout(this.pendingGestureCallback);
onTransitionStart?.({ closing }); onTransition?.({ closing, gesture: velocity !== undefined });
animation(gesture, { animation(gesture, {
...spec.config, ...spec.config,
velocity, velocity,
@@ -196,6 +216,11 @@ export default class Card extends React.Component<Props> {
} else { } else {
onOpen(); onOpen();
} }
if (this.isCurrentlyMounted) {
// Make sure to re-open screen if it wasn't removed
this.forceUpdate();
}
} }
}); });
}; };
@@ -301,10 +326,13 @@ export default class Card extends React.Component<Props> {
if (closing) { if (closing) {
// We call onClose with a delay to make sure that the animation has already started // We call onClose with a delay to make sure that the animation has already started
// This will make sure that the state update caused by this doesn't affect start of animation // This will make sure that the state update caused by this doesn't affect start of animation
this.pendingGestureCallback = (setTimeout( this.pendingGestureCallback = (setTimeout(() => {
onClose, onClose();
32
) as any) as number; // Trigger an update after we dispatch the action to remove the screen
// This will make sure that we check if the screen didn't get removed so we can cancel the animation
this.forceUpdate();
}, 32) as any) as number;
} }
onGestureEnd?.(); onGestureEnd?.();
@@ -489,9 +517,10 @@ export default class Card extends React.Component<Props> {
: undefined; : undefined;
const { backgroundColor } = StyleSheet.flatten(contentStyle || {}); const { backgroundColor } = StyleSheet.flatten(contentStyle || {});
const isTransparent = backgroundColor const isTransparent =
? Color(backgroundColor).alpha() === 0 typeof backgroundColor === 'string'
: false; ? Color(backgroundColor).alpha() === 0
: false;
return ( return (
<CardAnimationContext.Provider value={animationContext}> <CardAnimationContext.Provider value={animationContext}>
@@ -513,6 +542,7 @@ export default class Card extends React.Component<Props> {
</View> </View>
) : null} ) : null}
<Animated.View <Animated.View
needsOffscreenAlphaCompositing={hasOpacityStyle(containerStyle)}
style={[styles.container, containerStyle, customContainerStyle]} style={[styles.container, containerStyle, customContainerStyle]}
pointerEvents="box-none" pointerEvents="box-none"
> >

View File

@@ -27,13 +27,14 @@ type Props = TransitionPreset & {
safeAreaInsetRight: number; safeAreaInsetRight: number;
safeAreaInsetBottom: number; safeAreaInsetBottom: number;
safeAreaInsetLeft: number; safeAreaInsetLeft: number;
cardOverlay?: (props: { style: StyleProp<ViewStyle> }) => React.ReactNode; cardOverlay?: (props: {
style: Animated.WithAnimatedValue<StyleProp<ViewStyle>>;
}) => React.ReactNode;
cardOverlayEnabled?: boolean; cardOverlayEnabled?: boolean;
cardShadowEnabled?: boolean; cardShadowEnabled?: boolean;
cardStyle?: StyleProp<ViewStyle>; cardStyle?: StyleProp<ViewStyle>;
getPreviousScene: (props: { getPreviousScene: (props: {
route: Route<string>; route: Route<string>;
index: number;
}) => Scene<Route<string>> | undefined; }) => Scene<Route<string>> | undefined;
getFocusedRoute: () => Route<string>; getFocusedRoute: () => Route<string>;
renderHeader: (props: HeaderContainerProps) => React.ReactNode; renderHeader: (props: HeaderContainerProps) => React.ReactNode;
@@ -46,8 +47,11 @@ type Props = TransitionPreset & {
) => void; ) => void;
onTransitionEnd?: (props: { route: Route<string> }, closing: boolean) => void; onTransitionEnd?: (props: { route: Route<string> }, closing: boolean) => void;
onPageChangeStart?: () => void; onPageChangeStart?: () => void;
onPageChangeConfirm?: () => void; onPageChangeConfirm?: (force: boolean) => void;
onPageChangeCancel?: () => void; onPageChangeCancel?: () => void;
onGestureStart?: (props: { route: Route<string> }) => void;
onGestureEnd?: (props: { route: Route<string> }) => void;
onGestureCancel?: (props: { route: Route<string> }) => void;
gestureEnabled?: boolean; gestureEnabled?: boolean;
gestureResponseDistance?: { gestureResponseDistance?: {
vertical?: number; vertical?: number;
@@ -63,6 +67,7 @@ type Props = TransitionPreset & {
route: Route<string>; route: Route<string>;
height: number; height: number;
}) => void; }) => void;
isParentHeaderShown: boolean;
}; };
const EPSILON = 0.1; const EPSILON = 0.1;
@@ -90,6 +95,7 @@ function CardContainer({
hasAbsoluteHeader, hasAbsoluteHeader,
headerHeight, headerHeight,
onHeaderHeightChange, onHeaderHeightChange,
isParentHeaderShown,
index, index,
layout, layout,
onCloseRoute, onCloseRoute,
@@ -97,6 +103,9 @@ function CardContainer({
onPageChangeCancel, onPageChangeCancel,
onPageChangeConfirm, onPageChangeConfirm,
onPageChangeStart, onPageChangeStart,
onGestureCancel,
onGestureEnd,
onGestureStart,
onTransitionEnd, onTransitionEnd,
onTransitionStart, onTransitionStart,
renderHeader, renderHeader,
@@ -108,28 +117,58 @@ function CardContainer({
scene, scene,
transitionSpec, transitionSpec,
}: Props) { }: Props) {
React.useEffect(() => {
onPageChangeConfirm?.();
}, [active, onPageChangeConfirm]);
const handleOpen = () => { const handleOpen = () => {
onTransitionEnd?.({ route: scene.route }, false); const { route } = scene;
onOpenRoute({ route: scene.route });
onTransitionEnd?.({ route }, false);
onOpenRoute({ route });
}; };
const handleClose = () => { const handleClose = () => {
onTransitionEnd?.({ route: scene.route }, true); const { route } = scene;
onCloseRoute({ route: scene.route });
onTransitionEnd?.({ route }, true);
onCloseRoute({ route });
}; };
const handleTransitionStart = ({ closing }: { closing: boolean }) => { const handleGestureBegin = () => {
if (active && closing) { const { route } = scene;
onPageChangeConfirm?.();
onPageChangeStart?.();
onGestureStart?.({ route });
};
const handleGestureCanceled = () => {
const { route } = scene;
onPageChangeCancel?.();
onGestureCancel?.({ route });
};
const handleGestureEnd = () => {
const { route } = scene;
onGestureEnd?.({ route });
};
const handleTransition = ({
closing,
gesture,
}: {
closing: boolean;
gesture: boolean;
}) => {
const { route } = scene;
if (!gesture) {
onPageChangeConfirm?.(true);
} else if (active && closing) {
onPageChangeConfirm?.(false);
} else { } else {
onPageChangeCancel?.(); onPageChangeCancel?.();
} }
onTransitionStart?.({ route: scene.route }, closing); onTransitionStart?.({ route }, closing);
}; };
const insets = { const insets = {
@@ -161,9 +200,8 @@ function CardContainer({
}; };
}, [pointerEvents, scene.progress.next]); }, [pointerEvents, scene.progress.next]);
const isParentHeaderShown = React.useContext(HeaderShownContext);
const isCurrentHeaderShown = headerMode !== 'none' && headerShown !== false; const isCurrentHeaderShown = headerMode !== 'none' && headerShown !== false;
const previousScene = getPreviousScene({ route: scene.route, index }); const previousScene = getPreviousScene({ route: scene.route });
return ( return (
<Card <Card
@@ -180,9 +218,10 @@ function CardContainer({
overlay={cardOverlay} overlay={cardOverlay}
overlayEnabled={cardOverlayEnabled} overlayEnabled={cardOverlayEnabled}
shadowEnabled={cardShadowEnabled} shadowEnabled={cardShadowEnabled}
onTransitionStart={handleTransitionStart} onTransition={handleTransition}
onGestureBegin={onPageChangeStart} onGestureBegin={handleGestureBegin}
onGestureCanceled={onPageChangeCancel} onGestureCanceled={handleGestureCanceled}
onGestureEnd={handleGestureEnd}
gestureEnabled={gestureEnabled} gestureEnabled={gestureEnabled}
gestureResponseDistance={gestureResponseDistance} gestureResponseDistance={gestureResponseDistance}
gestureVelocityImpact={gestureVelocityImpact} gestureVelocityImpact={gestureVelocityImpact}
@@ -194,7 +233,14 @@ function CardContainer({
pageOverflowEnabled={headerMode === 'screen' && mode === 'card'} pageOverflowEnabled={headerMode === 'screen' && mode === 'card'}
containerStyle={hasAbsoluteHeader ? { marginTop: headerHeight } : null} containerStyle={hasAbsoluteHeader ? { marginTop: headerHeight } : null}
contentStyle={[{ backgroundColor: colors.background }, cardStyle]} contentStyle={[{ backgroundColor: colors.background }, cardStyle]}
style={StyleSheet.absoluteFill} style={[
{
// This is necessary to avoid unfocused larger pages increasing scroll area
// The issue can be seen on the web when a smaller screen is pushed over a larger one
overflow: active ? undefined : 'hidden',
},
StyleSheet.absoluteFill,
]}
> >
<View style={styles.container}> <View style={styles.container}>
<View style={styles.scene}> <View style={styles.scene}>

View File

@@ -9,7 +9,11 @@ import {
import type { EdgeInsets } from 'react-native-safe-area-context'; import type { EdgeInsets } from 'react-native-safe-area-context';
import type { NavigationState as StackNavigationState } from 'react-navigation'; import type { NavigationState as StackNavigationState } from 'react-navigation';
import { MaybeScreenContainer, MaybeScreen } from '../Screens'; import {
MaybeScreenContainer,
MaybeScreen,
shouldUseActivityState,
} from '../Screens';
import { getDefaultHeaderHeight } from '../Header/HeaderSegment'; import { getDefaultHeaderHeight } from '../Header/HeaderSegment';
import type { Props as HeaderContainerProps } from '../Header/HeaderContainer'; import type { Props as HeaderContainerProps } from '../Header/HeaderContainer';
import CardContainer from './CardContainer'; import CardContainer from './CardContainer';
@@ -19,7 +23,6 @@ import {
} from '../../TransitionConfigs/TransitionPresets'; } from '../../TransitionConfigs/TransitionPresets';
import { forNoAnimation as forNoAnimationHeader } from '../../TransitionConfigs/HeaderStyleInterpolators'; import { forNoAnimation as forNoAnimationHeader } from '../../TransitionConfigs/HeaderStyleInterpolators';
import { forNoAnimation as forNoAnimationCard } from '../../TransitionConfigs/CardStyleInterpolators'; import { forNoAnimation as forNoAnimationCard } from '../../TransitionConfigs/CardStyleInterpolators';
import HeaderShownContext from '../../utils/HeaderShownContext';
import getDistanceForDirection from '../../utils/getDistanceForDirection'; import getDistanceForDirection from '../../utils/getDistanceForDirection';
import type { import type {
Layout, Layout,
@@ -53,14 +56,19 @@ type Props = {
renderHeader: (props: HeaderContainerProps) => React.ReactNode; renderHeader: (props: HeaderContainerProps) => React.ReactNode;
renderScene: (props: { route: Route<string> }) => React.ReactNode; renderScene: (props: { route: Route<string> }) => React.ReactNode;
headerMode: StackHeaderMode; headerMode: StackHeaderMode;
isParentHeaderShown: boolean;
onTransitionStart: ( onTransitionStart: (
props: { route: Route<string> }, props: { route: Route<string> },
closing: boolean closing: boolean
) => void; ) => void;
onTransitionEnd: (props: { route: Route<string> }, closing: boolean) => void; onTransitionEnd: (props: { route: Route<string> }, closing: boolean) => void;
onPageChangeStart?: () => void; onPageChangeStart?: () => void;
onPageChangeConfirm?: () => void; onPageChangeConfirm?: (force: boolean) => void;
onPageChangeCancel?: () => void; onPageChangeCancel?: () => void;
onGestureStart?: (props: { route: Route<string> }) => void;
onGestureEnd?: (props: { route: Route<string> }) => void;
onGestureCancel?: (props: { route: Route<string> }) => void;
detachInactiveScreens?: boolean;
}; };
type State = { type State = {
@@ -74,11 +82,16 @@ type State = {
const EPSILON = 0.01; const EPSILON = 0.01;
const STATE_INACTIVE = 0;
const STATE_TRANSITIONING_OR_BELOW_TOP = 1;
const STATE_ON_TOP = 2;
const FALLBACK_DESCRIPTOR = Object.freeze({ options: {} }); const FALLBACK_DESCRIPTOR = Object.freeze({ options: {} });
const getHeaderHeights = ( const getHeaderHeights = (
routes: Route<string>[], routes: Route<string>[],
insets: EdgeInsets, insets: EdgeInsets,
isParentHeaderShown: boolean,
descriptors: StackDescriptorMap, descriptors: StackDescriptorMap,
layout: Layout, layout: Layout,
previous: Record<string, number> previous: Record<string, number>
@@ -95,7 +108,9 @@ const getHeaderHeights = (
...options.safeAreaInsets, ...options.safeAreaInsets,
}; };
const { headerStatusBarHeight = safeAreaInsets.top } = options; const {
headerStatusBarHeight = isParentHeaderShown ? 0 : safeAreaInsets.top,
} = options;
acc[curr.key] = acc[curr.key] =
typeof height === 'number' typeof height === 'number'
@@ -258,6 +273,7 @@ export default class CardStack extends React.Component<Props, State> {
headerHeights: getHeaderHeights( headerHeights: getHeaderHeights(
props.routes, props.routes,
props.insets, props.insets,
props.isParentHeaderShown,
state.descriptors, state.descriptors,
state.layout, state.layout,
state.headerHeights state.headerHeights
@@ -300,6 +316,7 @@ export default class CardStack extends React.Component<Props, State> {
headerHeights: getHeaderHeights( headerHeights: getHeaderHeights(
props.routes, props.routes,
props.insets, props.insets,
props.isParentHeaderShown,
state.descriptors, state.descriptors,
layout, layout,
state.headerHeights state.headerHeights
@@ -337,31 +354,21 @@ export default class CardStack extends React.Component<Props, State> {
return state.routes[state.index]; return state.routes[state.index];
}; };
private getPreviousScene = ({ private getPreviousScene = ({ route }: { route: Route<string> }) => {
route, const { getPreviousRoute } = this.props;
index, const { scenes } = this.state;
}: {
route: Route<string>;
index: number;
}) => {
const previousRoute = this.props.getPreviousRoute({ route });
let previous: Scene<Route<string>> | undefined; const previousRoute = getPreviousRoute({ route });
if (previousRoute) { if (previousRoute) {
// The previous scene will be shortly before the current scene in the array const previousScene = scenes.find(
// So loop back from current index to avoid looping over the full array (scene) => scene.route.key === previousRoute.key
for (let j = index - 1; j >= 0; j--) { );
const s = this.state.scenes[j];
if (s && s.route.key === previousRoute.key) { return previousScene;
previous = s;
break;
}
}
} }
return previous; return undefined;
}; };
render() { render() {
@@ -378,11 +385,18 @@ export default class CardStack extends React.Component<Props, State> {
renderHeader, renderHeader,
renderScene, renderScene,
headerMode, headerMode,
isParentHeaderShown,
onTransitionStart, onTransitionStart,
onTransitionEnd, onTransitionEnd,
onPageChangeStart, onPageChangeStart,
onPageChangeConfirm, onPageChangeConfirm,
onPageChangeCancel, onPageChangeCancel,
onGestureStart,
onGestureEnd,
onGestureCancel,
// Enable on new versions of `react-native-screens`
// On older versions of `react-native-screens`, there's an issue with screens not being responsive to user interaction.
detachInactiveScreens = Platform.OS === 'web' || shouldUseActivityState,
} = this.props; } = this.props;
const { scenes, layout, gestures, headerHeights } = this.state; const { scenes, layout, gestures, headerHeights } = this.state;
@@ -390,6 +404,7 @@ export default class CardStack extends React.Component<Props, State> {
const focusedRoute = state.routes[state.index]; const focusedRoute = state.routes[state.index];
const focusedDescriptor = descriptors[focusedRoute.key]; const focusedDescriptor = descriptors[focusedRoute.key];
const focusedOptions = focusedDescriptor ? focusedDescriptor.options : {}; const focusedOptions = focusedDescriptor ? focusedDescriptor.options : {};
const focusedHeaderHeight = headerHeights[focusedRoute.key];
let defaultTransitionPreset = let defaultTransitionPreset =
mode === 'modal' ? ModalTransition : DefaultTransition; mode === 'modal' ? ModalTransition : DefaultTransition;
@@ -408,209 +423,247 @@ export default class CardStack extends React.Component<Props, State> {
left = insets.left, left = insets.left,
} = focusedOptions.safeAreaInsets || {}; } = focusedOptions.safeAreaInsets || {};
// Screens is buggy on iOS and web, so we only enable it on Android let activeScreensLimit = 1;
// For modals, usually we want the screen underneath to be visible, so also disable it there
const isScreensEnabled = Platform.OS !== 'ios' && mode !== 'modal'; for (let i = scenes.length - 1; i >= 0; i--) {
const {
// By default, we don't want to detach the previous screen of the active one for modals
detachPreviousScreen = mode === 'modal'
? i !== scenes.length - 1
: true,
} = scenes[i].descriptor.options;
if (detachPreviousScreen === false) {
activeScreensLimit++;
} else {
break;
}
}
const isFloatHeaderAbsolute =
headerMode === 'float'
? this.state.scenes.slice(-2).some((scene) => {
const { descriptor } = scene;
const options = descriptor ? descriptor.options : {};
const { headerTransparent, headerShown = true } = options;
if (headerTransparent || headerShown === false) {
return true;
}
return false;
})
: false;
const floatingHeader =
headerMode === 'float' ? (
<React.Fragment key="header">
{renderHeader({
mode: 'float',
layout,
insets: { top, right, bottom, left },
scenes,
getPreviousScene: this.getPreviousScene,
getFocusedRoute: this.getFocusedRoute,
onContentHeightChange: this.handleHeaderLayout,
gestureDirection:
focusedOptions.gestureDirection !== undefined
? focusedOptions.gestureDirection
: defaultTransitionPreset.gestureDirection,
styleInterpolator:
focusedOptions.headerStyleInterpolator !== undefined
? focusedOptions.headerStyleInterpolator
: defaultTransitionPreset.headerStyleInterpolator,
style: [
styles.floating,
isFloatHeaderAbsolute && [
// Without this, the header buttons won't be touchable on Android when headerTransparent: true
{ height: focusedHeaderHeight },
styles.absolute,
],
],
})}
</React.Fragment>
) : null;
return ( return (
<HeaderShownContext.Consumer> <React.Fragment>
{(isParentHeaderShown) => { {isFloatHeaderAbsolute ? null : floatingHeader}
const isFloatHeaderAbsolute = <MaybeScreenContainer
headerMode === 'float' enabled={detachInactiveScreens}
? this.state.scenes.slice(-2).some((scene) => { style={styles.container}
const { descriptor } = scene; onLayout={this.handleLayout}
const options = descriptor ? descriptor.options : {}; >
const { {routes.map((route, index, self) => {
headerTransparent, const focused = focusedRoute.key === route.key;
headerShown = isParentHeaderShown === false, const gesture = gestures[route.key];
} = options; const scene = scenes[index];
if (headerTransparent || headerShown === false) { // For the screens that shouldn't be active, the value is 0
return true; // For those that should be active, but are not the top screen, the value is 1
} // For those on top of the stack and with interaction enabled, the value is 2
// For the old implementation, it stays the same it was
let isScreenActive: Animated.AnimatedInterpolation | 2 | 1 | 0 = 1;
return false; if (shouldUseActivityState || Platform.OS === 'web') {
}) if (index < self.length - activeScreensLimit - 1) {
: false; // screen should be inactive because it is too deep in the stack
isScreenActive = STATE_INACTIVE;
} else {
const sceneForActivity = scenes[self.length - 1];
const outputValue =
index === self.length - 1
? STATE_ON_TOP // the screen is on top after the transition
: index >= self.length - activeScreensLimit
? STATE_TRANSITIONING_OR_BELOW_TOP // the screen should stay active after the transition, it is not on top but is in activeLimit
: STATE_INACTIVE; // the screen should be active only during the transition, it is at the edge of activeLimit
isScreenActive = sceneForActivity
? sceneForActivity.progress.current.interpolate({
inputRange: [0, 1 - EPSILON, 1],
outputRange: [1, 1, outputValue],
extrapolate: 'clamp',
})
: STATE_TRANSITIONING_OR_BELOW_TOP;
}
} else {
isScreenActive = scene.progress.next
? scene.progress.next.interpolate({
inputRange: [0, 1 - EPSILON, 1],
outputRange: [1, 1, 0],
extrapolate: 'clamp',
})
: 1;
}
const floatingHeader = const {
headerMode === 'float' ? ( safeAreaInsets,
<React.Fragment key="header"> headerShown = true,
{renderHeader({ headerTransparent,
mode: 'float', cardShadowEnabled,
layout, cardOverlayEnabled,
insets: { top, right, bottom, left }, cardOverlay,
scenes, cardStyle,
getPreviousScene: this.getPreviousScene, animationEnabled,
getFocusedRoute: this.getFocusedRoute, gestureResponseDistance,
onContentHeightChange: this.handleHeaderLayout, gestureVelocityImpact,
gestureDirection: gestureDirection = defaultTransitionPreset.gestureDirection,
focusedOptions.gestureDirection !== undefined transitionSpec = defaultTransitionPreset.transitionSpec,
? focusedOptions.gestureDirection cardStyleInterpolator = animationEnabled === false
: defaultTransitionPreset.gestureDirection, ? forNoAnimationCard
styleInterpolator: : defaultTransitionPreset.cardStyleInterpolator,
focusedOptions.headerStyleInterpolator !== undefined headerStyleInterpolator = defaultTransitionPreset.headerStyleInterpolator,
? focusedOptions.headerStyleInterpolator } = scene.descriptor
: defaultTransitionPreset.headerStyleInterpolator, ? scene.descriptor.options
style: [ : ({} as StackNavigationOptions);
styles.floating,
isFloatHeaderAbsolute && styles.absolute,
],
})}
</React.Fragment>
) : null;
return ( let transitionConfig = {
<React.Fragment> gestureDirection,
{isFloatHeaderAbsolute ? null : floatingHeader} transitionSpec,
<MaybeScreenContainer cardStyleInterpolator,
enabled={isScreensEnabled} headerStyleInterpolator,
style={styles.container} };
onLayout={this.handleLayout}
// When a screen is not the last, it should use next screen's transition config
// Many transitions also animate the previous screen, so using 2 different transitions doesn't look right
// For example combining a slide and a modal transition would look wrong otherwise
// With this approach, combining different transition styles in the same navigator mostly looks right
// This will still be broken when 2 transitions have different idle state (e.g. modal presentation),
// but majority of the transitions look alright
if (index !== self.length - 1) {
const nextScene = scenes[index + 1];
if (nextScene) {
const {
animationEnabled,
gestureDirection = defaultTransitionPreset.gestureDirection,
transitionSpec = defaultTransitionPreset.transitionSpec,
cardStyleInterpolator = animationEnabled === false
? forNoAnimationCard
: defaultTransitionPreset.cardStyleInterpolator,
headerStyleInterpolator = defaultTransitionPreset.headerStyleInterpolator,
} = nextScene.descriptor
? nextScene.descriptor.options
: ({} as StackNavigationOptions);
transitionConfig = {
gestureDirection,
transitionSpec,
cardStyleInterpolator,
headerStyleInterpolator,
};
}
}
const {
top: safeAreaInsetTop = insets.top,
right: safeAreaInsetRight = insets.right,
bottom: safeAreaInsetBottom = insets.bottom,
left: safeAreaInsetLeft = insets.left,
} = safeAreaInsets || {};
const headerHeight =
headerMode !== 'none' && headerShown !== false
? headerHeights[route.key]
: 0;
return (
<MaybeScreen
key={route.key}
style={StyleSheet.absoluteFill}
enabled={detachInactiveScreens}
active={isScreenActive}
pointerEvents="box-none"
> >
{routes.map((route, index, self) => { <CardContainer
const focused = focusedRoute.key === route.key; index={index}
const gesture = gestures[route.key]; active={index === self.length - 1}
const scene = scenes[index]; focused={focused}
closing={closingRouteKeys.includes(route.key)}
const isScreenActive = scene.progress.next layout={layout}
? scene.progress.next.interpolate({ gesture={gesture}
inputRange: [0, 1 - EPSILON, 1], scene={scene}
outputRange: [1, 1, 0], safeAreaInsetTop={safeAreaInsetTop}
extrapolate: 'clamp', safeAreaInsetRight={safeAreaInsetRight}
}) safeAreaInsetBottom={safeAreaInsetBottom}
: 1; safeAreaInsetLeft={safeAreaInsetLeft}
cardOverlay={cardOverlay}
const { cardOverlayEnabled={cardOverlayEnabled}
safeAreaInsets, cardShadowEnabled={cardShadowEnabled}
headerShown = isParentHeaderShown === false, cardStyle={cardStyle}
headerTransparent, onPageChangeStart={onPageChangeStart}
cardShadowEnabled, onPageChangeConfirm={onPageChangeConfirm}
cardOverlayEnabled, onPageChangeCancel={onPageChangeCancel}
cardOverlay, onGestureStart={onGestureStart}
cardStyle, onGestureCancel={onGestureCancel}
animationEnabled, onGestureEnd={onGestureEnd}
gestureResponseDistance, gestureResponseDistance={gestureResponseDistance}
gestureVelocityImpact, headerHeight={headerHeight}
gestureDirection = defaultTransitionPreset.gestureDirection, isParentHeaderShown={isParentHeaderShown}
transitionSpec = defaultTransitionPreset.transitionSpec, onHeaderHeightChange={this.handleHeaderLayout}
cardStyleInterpolator = animationEnabled === false getPreviousScene={this.getPreviousScene}
? forNoAnimationCard getFocusedRoute={this.getFocusedRoute}
: defaultTransitionPreset.cardStyleInterpolator, mode={mode}
headerStyleInterpolator = defaultTransitionPreset.headerStyleInterpolator, headerMode={headerMode}
} = scene.descriptor headerShown={headerShown}
? scene.descriptor.options hasAbsoluteHeader={
: ({} as StackNavigationOptions); isFloatHeaderAbsolute && !headerTransparent
let transitionConfig = {
gestureDirection,
transitionSpec,
cardStyleInterpolator,
headerStyleInterpolator,
};
// When a screen is not the last, it should use next screen's transition config
// Many transitions also animate the previous screen, so using 2 different transitions doesn't look right
// For example combining a slide and a modal transition would look wrong otherwise
// With this approach, combining different transition styles in the same navigator mostly looks right
// This will still be broken when 2 transitions have different idle state (e.g. modal presentation),
// but majority of the transitions look alright
if (index !== self.length - 1) {
const nextScene = scenes[index + 1];
if (nextScene) {
const {
animationEnabled,
gestureDirection = defaultTransitionPreset.gestureDirection,
transitionSpec = defaultTransitionPreset.transitionSpec,
cardStyleInterpolator = animationEnabled === false
? forNoAnimationCard
: defaultTransitionPreset.cardStyleInterpolator,
headerStyleInterpolator = defaultTransitionPreset.headerStyleInterpolator,
} = nextScene.descriptor
? nextScene.descriptor.options
: ({} as StackNavigationOptions);
transitionConfig = {
gestureDirection,
transitionSpec,
cardStyleInterpolator,
headerStyleInterpolator,
};
}
} }
renderHeader={renderHeader}
const { renderScene={renderScene}
top: safeAreaInsetTop = insets.top, onOpenRoute={onOpenRoute}
right: safeAreaInsetRight = insets.right, onCloseRoute={onCloseRoute}
bottom: safeAreaInsetBottom = insets.bottom, onTransitionStart={onTransitionStart}
left: safeAreaInsetLeft = insets.left, onTransitionEnd={onTransitionEnd}
} = safeAreaInsets || {}; gestureEnabled={index !== 0 && getGesturesEnabled({ route })}
gestureVelocityImpact={gestureVelocityImpact}
const headerHeight = {...transitionConfig}
headerMode !== 'none' && headerShown !== false />
? headerHeights[route.key] </MaybeScreen>
: 0; );
})}
return ( </MaybeScreenContainer>
<MaybeScreen {isFloatHeaderAbsolute ? floatingHeader : null}
key={route.key} </React.Fragment>
style={StyleSheet.absoluteFill}
enabled={isScreensEnabled}
active={isScreenActive}
pointerEvents="box-none"
>
<CardContainer
index={index}
active={index === self.length - 1}
focused={focused}
closing={closingRouteKeys.includes(route.key)}
layout={layout}
gesture={gesture}
scene={scene}
safeAreaInsetTop={safeAreaInsetTop}
safeAreaInsetRight={safeAreaInsetRight}
safeAreaInsetBottom={safeAreaInsetBottom}
safeAreaInsetLeft={safeAreaInsetLeft}
cardOverlay={cardOverlay}
cardOverlayEnabled={cardOverlayEnabled}
cardShadowEnabled={cardShadowEnabled}
cardStyle={cardStyle}
onPageChangeStart={onPageChangeStart}
onPageChangeConfirm={onPageChangeConfirm}
onPageChangeCancel={onPageChangeCancel}
gestureResponseDistance={gestureResponseDistance}
headerHeight={headerHeight}
onHeaderHeightChange={this.handleHeaderLayout}
getPreviousScene={this.getPreviousScene}
getFocusedRoute={this.getFocusedRoute}
mode={mode}
headerMode={headerMode}
headerShown={headerShown}
hasAbsoluteHeader={
isFloatHeaderAbsolute && !headerTransparent
}
renderHeader={renderHeader}
renderScene={renderScene}
onOpenRoute={onOpenRoute}
onCloseRoute={onCloseRoute}
onTransitionStart={onTransitionStart}
onTransitionEnd={onTransitionEnd}
gestureEnabled={
index !== 0 && getGesturesEnabled({ route })
}
gestureVelocityImpact={gestureVelocityImpact}
{...transitionConfig}
/>
</MaybeScreen>
);
})}
</MaybeScreenContainer>
{isFloatHeaderAbsolute ? floatingHeader : null}
</React.Fragment>
);
}}
</HeaderShownContext.Consumer>
); );
} }
} }

View File

@@ -21,6 +21,7 @@ import type {
StackNavigationConfig, StackNavigationConfig,
StackDescriptorMap, StackDescriptorMap,
} from '../../types'; } from '../../types';
import HeaderShownContext from '../../utils/HeaderShownContext';
type Props = StackNavigationConfig & { type Props = StackNavigationConfig & {
state: StackNavigationState; state: StackNavigationState;
@@ -430,7 +431,19 @@ export default class StackView extends React.Component<Props, State> {
const descriptor = const descriptor =
descriptors[route.key] || this.state.descriptors[route.key]; descriptors[route.key] || this.state.descriptors[route.key];
descriptor?.options.onTransitionEnd?.({ closing }); descriptor?.options.onTransitionStart?.({ closing });
};
private handleGestureStart = () => {
// Do nothing
};
private handleGestureEnd = () => {
// Do nothing
};
private handleGestureCancel = () => {
// Do nothing
}; };
render() { render() {
@@ -463,26 +476,34 @@ export default class StackView extends React.Component<Props, State> {
{(insets) => ( {(insets) => (
<KeyboardManager enabled={keyboardHandlingEnabled !== false}> <KeyboardManager enabled={keyboardHandlingEnabled !== false}>
{(props) => ( {(props) => (
<CardStack <HeaderShownContext.Consumer>
mode={mode} {(isParentHeaderShown) => (
insets={insets as EdgeInsets} <CardStack
getPreviousRoute={this.getPreviousRoute} mode={mode}
getGesturesEnabled={this.getGesturesEnabled} insets={insets as EdgeInsets}
routes={routes} isParentHeaderShown={isParentHeaderShown}
openingRouteKeys={openingRouteKeys} getPreviousRoute={this.getPreviousRoute}
closingRouteKeys={closingRouteKeys} getGesturesEnabled={this.getGesturesEnabled}
onOpenRoute={this.handleOpenRoute} routes={routes}
onCloseRoute={this.handleCloseRoute} openingRouteKeys={openingRouteKeys}
onTransitionStart={this.handleTransitionStart} closingRouteKeys={closingRouteKeys}
onTransitionEnd={this.handleTransitionEnd} onOpenRoute={this.handleOpenRoute}
renderHeader={this.renderHeader} onCloseRoute={this.handleCloseRoute}
renderScene={this.renderScene} onTransitionStart={this.handleTransitionStart}
headerMode={headerMode} onTransitionEnd={this.handleTransitionEnd}
state={state} renderHeader={this.renderHeader}
descriptors={descriptors} renderScene={this.renderScene}
{...rest} headerMode={headerMode}
{...props} state={state}
/> descriptors={descriptors}
onGestureStart={this.handleGestureStart}
onGestureEnd={this.handleGestureEnd}
onGestureCancel={this.handleGestureCancel}
{...rest}
{...props}
/>
)}
</HeaderShownContext.Consumer>
)} )}
</KeyboardManager> </KeyboardManager>
)} )}

View File

@@ -0,0 +1,50 @@
import * as React from 'react';
import { Animated, Platform } from 'react-native';
import { BaseButton } from 'react-native-gesture-handler';
const AnimatedBaseButton = Animated.createAnimatedComponent(BaseButton);
type Props = React.ComponentProps<typeof BaseButton> & {
pressOpacity: number;
};
const useNativeDriver = Platform.OS !== 'web';
export default class TouchableItem extends React.Component<Props> {
static defaultProps = {
activeOpacity: 0.3,
borderless: true,
enabled: true,
};
private opacity = new Animated.Value(1);
private handleActiveStateChange = (active: boolean) => {
Animated.spring(this.opacity, {
stiffness: 1000,
damping: 500,
mass: 3,
overshootClamping: true,
restDisplacementThreshold: 0.01,
restSpeedThreshold: 0.01,
toValue: active ? this.props.pressOpacity : 1,
useNativeDriver,
}).start();
this.props.onActiveStateChange?.(active);
};
render() {
const { children, style, enabled, ...rest } = this.props;
return (
<AnimatedBaseButton
{...rest}
onActiveStateChange={this.handleActiveStateChange}
style={[style, enabled && { opacity: this.opacity }]}
>
{children}
</AnimatedBaseButton>
);
}
}

View File

@@ -1,81 +0,0 @@
/**
* TouchableItem renders a touchable that looks native on both iOS and Android.
*
* It provides an abstraction on top of TouchableNativeFeedback and
* TouchableOpacity.
*
* On iOS you can pass the props of TouchableOpacity, on Android pass the props
* of TouchableNativeFeedback.
*/
import * as React from 'react';
import {
Platform,
TouchableNativeFeedback,
TouchableOpacity,
View,
ViewProps,
} from 'react-native';
import BorderlessButton from './BorderlessButton';
export type Props = ViewProps & {
pressColor: string;
disabled?: boolean;
borderless?: boolean;
delayPressIn?: number;
onPress?: () => void;
children: React.ReactNode;
};
const ANDROID_VERSION_LOLLIPOP = 21;
export class TouchableItem extends React.Component<Props> {
static defaultProps = {
borderless: false,
pressColor: 'rgba(0, 0, 0, .32)',
};
render() {
/*
* TouchableNativeFeedback.Ripple causes a crash on old Android versions,
* therefore only enable it on Android Lollipop and above.
*
* All touchables on Android should have the ripple effect according to
* platform design guidelines.
* We need to pass the background prop to specify a borderless ripple effect.
*/
if (
Platform.OS === 'android' &&
Platform.Version >= ANDROID_VERSION_LOLLIPOP
) {
const { style, pressColor, borderless, children, ...rest } = this.props;
return (
<TouchableNativeFeedback
{...rest}
useForeground={TouchableNativeFeedback.canUseNativeForeground()}
background={TouchableNativeFeedback.Ripple(pressColor, borderless)}
>
<View style={style}>{React.Children.only(children)}</View>
</TouchableNativeFeedback>
);
} else if (Platform.OS === 'ios') {
return (
<BorderlessButton
hitSlop={{ top: 10, bottom: 10, right: 10, left: 10 }}
disallowInterruption
enabled={!this.props.disabled}
{...this.props}
>
{this.props.children}
</BorderlessButton>
);
} else {
return (
<TouchableOpacity {...this.props}>
{this.props.children}
</TouchableOpacity>
);
}
}
}

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