Compare commits

..

28 Commits

Author SHA1 Message Date
satyajit.happy
44020452fb chore: publish
- @react-navigation/core@5.0.0-alpha.8
 - @react-navigation/stack@5.0.0-alpha.15
2019-09-04 11:56:16 +02:00
satyajit.happy
ceaf18edd6 chore: remove commented out code 2019-09-04 11:55:37 +02:00
satyajit.happy
faaf855717 refactor: separate navigation and route context 2019-09-04 11:54:20 +02:00
satyajit.happy
196cce0803 feat: add approximate android Q transition 2019-09-04 11:36:00 +02:00
satyajit.happy
a022860317 chore: publish
- @react-navigation/stack@5.0.0-alpha.14
2019-09-03 16:43:26 +02:00
satyajit.happy
167d58ce27 fix: change order of attaching nodes in card exec 2019-09-03 16:41:11 +02:00
Michal Osadnik
798a905d0a chore: publish
- @react-navigation/stack@5.0.0-alpha.13
2019-09-01 16:56:21 +01:00
Michal Osadnik
aa6313c0e9 feat: useForeground if possible in stack header backButton 2019-09-01 16:56:00 +01:00
Michal Osadnik
2563924f53 chore: publish
- @react-navigation/stack@5.0.0-alpha.12
2019-09-01 15:43:59 +01:00
Michal Osadnik
55ec815247 fix: stack with gesture enabled 2019-09-01 12:46:55 +01:00
satyajit.happy
c7a79a62fa fix: defer running the animation to next frame 2019-09-01 12:43:03 +02:00
Michal Osadnik
5c6e85cec8 chore: publish
- @react-navigation/stack@5.0.0-alpha.11
2019-09-01 02:17:06 +01:00
Michal Osadnik
3f853d458f feat: optimizations in stack 2019-09-01 02:09:48 +01:00
satyajit.happy
06b3e6bda7 chore: publish
- @react-navigation/core@5.0.0-alpha.7
 - @react-navigation/example@5.0.0-alpha.6
 - @react-navigation/native@5.0.0-alpha.7
2019-08-31 23:23:10 +02:00
satyajit.happy
3c840bbae3 fix: fix navigation object changing too often 2019-08-31 23:21:27 +02:00
satyajit.happy
d4ad9d48f9 refactor: make descriptor.options a getter 2019-08-31 23:10:30 +02:00
satyajit.happy
a0e9784d98 chore: publish
- @react-navigation/core@5.0.0-alpha.6
 - @react-navigation/example@5.0.0-alpha.5
 - @react-navigation/native@5.0.0-alpha.6
2019-08-31 23:01:28 +02:00
satyajit.happy
eff0c0464f feat: support function in screenOptions 2019-08-31 23:00:27 +02:00
satyajit.happy
fe9ba2bf71 refactor: rename NativeContainer -> NavigationNativeContainer 2019-08-31 21:02:48 +02:00
Michał Osadnik
b0a3756d18 feat: add useRoute (#89) 2019-08-31 15:56:04 +01:00
satyajit.happy
4e0ebb05f9 chore: publish
- @react-navigation/bottom-tabs@5.0.0-alpha.7
 - @react-navigation/drawer@5.0.0-alpha.8
 - @react-navigation/example@5.0.0-alpha.4
 - @react-navigation/material-bottom-tabs@5.0.0-alpha.7
 - @react-navigation/material-top-tabs@5.0.0-alpha.7
 - @react-navigation/routers@5.0.0-alpha.7
 - @react-navigation/stack@5.0.0-alpha.10
2019-08-31 10:22:57 +02:00
satyajit.happy
bf0b408238 refactor: change signature of interpolation props 2019-08-31 10:21:36 +02:00
Satyajit Sahoo
1b2983eaa9 fix: handle route names change when all routes are removed (#86) 2019-08-30 19:15:54 +01:00
satyajit.happy
b38ee1c162 chore: publish
- @react-navigation/core@5.0.0-alpha.5
 - @react-navigation/drawer@5.0.0-alpha.7
 - @react-navigation/stack@5.0.0-alpha.9
2019-08-30 15:34:34 +02:00
satyajit.happy
fdc24d2523 fix: rename contentContainerStyle to sceneContainerStyle for drawer 2019-08-30 15:30:18 +02:00
satyajit.happy
6a8242c31a fix: properly set animated node on gestureEnabled change 2019-08-29 19:55:42 +02:00
satyajit.happy
3ad2e6ebcf fix: change interpolated style when idle to avoid messing up reanimated 2019-08-29 16:12:22 +02:00
satyajit.happy
5c8d183d68 chore: rename BaseActions -> CommonActions 2019-08-29 13:10:36 +02:00
46 changed files with 1254 additions and 359 deletions

View File

@@ -3,6 +3,14 @@
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.
# [5.0.0-alpha.7](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/bottom-tabs@5.0.0-alpha.6...@react-navigation/bottom-tabs@5.0.0-alpha.7) (2019-08-31)
**Note:** Version bump only for package @react-navigation/bottom-tabs
# [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/bottom-tabs@5.0.0-alpha.5...@react-navigation/bottom-tabs@5.0.0-alpha.6) (2019-08-29) # [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/bottom-tabs@5.0.0-alpha.5...@react-navigation/bottom-tabs@5.0.0-alpha.6) (2019-08-29)

View File

@@ -10,7 +10,7 @@
"android", "android",
"tab" "tab"
], ],
"version": "5.0.0-alpha.6", "version": "5.0.0-alpha.7",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",
@@ -33,7 +33,7 @@
"clean": "del lib" "clean": "del lib"
}, },
"dependencies": { "dependencies": {
"@react-navigation/routers": "^5.0.0-alpha.6", "@react-navigation/routers": "^5.0.0-alpha.7",
"react-native-safe-area-view": "^0.14.6" "react-native-safe-area-view": "^0.14.6"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -3,6 +3,51 @@
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.
# [5.0.0-alpha.8](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/core@5.0.0-alpha.7...@react-navigation/core@5.0.0-alpha.8) (2019-09-04)
**Note:** Version bump only for package @react-navigation/core
# [5.0.0-alpha.7](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/core@5.0.0-alpha.5...@react-navigation/core@5.0.0-alpha.7) (2019-08-31)
### Bug Fixes
* fix navigation object changing too often ([3c840bb](https://github.com/react-navigation/navigation-ex/commit/3c840bb))
### Features
* add useRoute ([#89](https://github.com/react-navigation/navigation-ex/issues/89)) ([b0a3756](https://github.com/react-navigation/navigation-ex/commit/b0a3756))
* support function in screenOptions ([eff0c04](https://github.com/react-navigation/navigation-ex/commit/eff0c04))
# [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/core@5.0.0-alpha.5...@react-navigation/core@5.0.0-alpha.6) (2019-08-31)
### Features
* add useRoute ([#89](https://github.com/react-navigation/navigation-ex/issues/89)) ([b0a3756](https://github.com/react-navigation/navigation-ex/commit/b0a3756))
* support function in screenOptions ([eff0c04](https://github.com/react-navigation/navigation-ex/commit/eff0c04))
# [5.0.0-alpha.5](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/core@5.0.0-alpha.4...@react-navigation/core@5.0.0-alpha.5) (2019-08-30)
**Note:** Version bump only for package @react-navigation/core
# [5.0.0-alpha.4](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/core@5.0.0-alpha.3...@react-navigation/core@5.0.0-alpha.4) (2019-08-29) # [5.0.0-alpha.4](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/core@5.0.0-alpha.3...@react-navigation/core@5.0.0-alpha.4) (2019-08-29)

View File

@@ -6,7 +6,7 @@
"react-native", "react-native",
"react-navigation" "react-navigation"
], ],
"version": "5.0.0-alpha.4", "version": "5.0.0-alpha.8",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",

View File

@@ -0,0 +1,11 @@
import * as React from 'react';
import { Route } from './types';
/**
* Context which holds the route prop for a screen.
*/
const NavigationContext = React.createContext<Route<string> | undefined>(
undefined
);
export default NavigationContext;

View File

@@ -1,6 +1,7 @@
import * as React from 'react'; import * as React from 'react';
import { NavigationStateContext } from './NavigationContainer'; import { NavigationStateContext } from './NavigationContainer';
import NavigationContext from './NavigationContext'; import NavigationContext from './NavigationContext';
import NavigationRouteContext from './NavigationRouteContext';
import StaticContainer from './StaticContainer'; import StaticContainer from './StaticContainer';
import EnsureSingleNavigator from './EnsureSingleNavigator'; import EnsureSingleNavigator from './EnsureSingleNavigator';
import { import {
@@ -56,7 +57,7 @@ export default function SceneView<
), ),
}); });
}, },
[getState, route, setState] [getState, route.key, setState]
); );
const context = React.useMemo( const context = React.useMemo(
@@ -78,6 +79,7 @@ export default function SceneView<
return ( return (
<NavigationContext.Provider value={navigation}> <NavigationContext.Provider value={navigation}>
<NavigationRouteContext.Provider value={route}>
<NavigationStateContext.Provider value={context}> <NavigationStateContext.Provider value={context}>
<EnsureSingleNavigator> <EnsureSingleNavigator>
<StaticContainer <StaticContainer
@@ -95,6 +97,7 @@ export default function SceneView<
</StaticContainer> </StaticContainer>
</EnsureSingleNavigator> </EnsureSingleNavigator>
</NavigationStateContext.Provider> </NavigationStateContext.Provider>
</NavigationRouteContext.Provider>
</NavigationContext.Provider> </NavigationContext.Provider>
); );
} }

View File

@@ -58,6 +58,315 @@ it('sets options with options prop as an object', () => {
`); `);
}); });
it('sets options with options prop as a fuction', () => {
const TestNavigator = (props: any) => {
const { state, descriptors } = useNavigationBuilder<
NavigationState,
any,
{ title?: string },
any
>(MockRouter, props);
const { render, options } = descriptors[state.routes[state.index].key];
return (
<main>
<h1>{options.title}</h1>
<div>{render()}</div>
</main>
);
};
const TestScreen = (): any => 'Test screen';
const root = render(
<NavigationContainer>
<TestNavigator>
<Screen
name="foo"
component={TestScreen}
options={({ route }: any) => ({ title: route.params.author })}
initialParams={{ author: 'Jane' }}
/>
<Screen name="bar" component={jest.fn()} />
</TestNavigator>
</NavigationContainer>
);
expect(root).toMatchInlineSnapshot(`
<main>
<h1>
Jane
</h1>
<div>
Test screen
</div>
</main>
`);
});
it('sets options with screenOptions prop as an object', () => {
const TestNavigator = (props: any) => {
const { state, descriptors } = useNavigationBuilder<
NavigationState,
any,
{ title?: string },
any
>(MockRouter, props);
return (
<>
{state.routes.map(route => {
const { render, options } = descriptors[route.key];
return (
<main key={route.key}>
<h1>{options.title}</h1>
<div>{render()}</div>
</main>
);
})}
</>
);
};
const TestScreenA = (): any => 'Test screen A';
const TestScreenB = (): any => 'Test screen B';
const root = render(
<NavigationContainer>
<TestNavigator screenOptions={{ title: 'Hello world' }}>
<Screen name="foo" component={TestScreenA} />
<Screen name="bar" component={TestScreenB} />
</TestNavigator>
</NavigationContainer>
);
expect(root).toMatchInlineSnapshot(`
Array [
<main>
<h1>
Hello world
</h1>
<div>
Test screen A
</div>
</main>,
<main>
<h1>
Hello world
</h1>
<div>
Test screen B
</div>
</main>,
]
`);
});
it('sets options with screenOptions prop as a fuction', () => {
const TestNavigator = (props: any) => {
const { state, descriptors } = useNavigationBuilder<
NavigationState,
any,
{ title?: string },
any
>(MockRouter, props);
return (
<>
{state.routes.map(route => {
const { render, options } = descriptors[route.key];
return (
<main key={route.key}>
<h1>{options.title}</h1>
<div>{render()}</div>
</main>
);
})}
</>
);
};
const TestScreenA = (): any => 'Test screen A';
const TestScreenB = (): any => 'Test screen B';
const root = render(
<NavigationContainer>
<TestNavigator
screenOptions={({ route }: any) => ({
title: `${route.name}: ${route.params.author || route.params.fruit}`,
})}
>
<Screen
name="foo"
component={TestScreenA}
initialParams={{ author: 'Jane' }}
/>
<Screen
name="bar"
component={TestScreenB}
initialParams={{ fruit: 'Apple' }}
/>
</TestNavigator>
</NavigationContainer>
);
expect(root).toMatchInlineSnapshot(`
Array [
<main>
<h1>
foo: Jane
</h1>
<div>
Test screen A
</div>
</main>,
<main>
<h1>
bar: Apple
</h1>
<div>
Test screen B
</div>
</main>,
]
`);
});
it('sets initial options with setOptions', () => {
const TestNavigator = (props: any) => {
const { state, descriptors } = useNavigationBuilder<
NavigationState,
any,
{
title?: string;
color?: string;
},
any
>(MockRouter, props);
const { render, options } = descriptors[state.routes[state.index].key];
return (
<main>
<h1 color={options.color}>{options.title}</h1>
<div>{render()}</div>
</main>
);
};
const TestScreen = ({ navigation }: any): any => {
navigation.setOptions({
title: 'Hello world',
});
return 'Test screen';
};
const root = render(
<NavigationContainer>
<TestNavigator>
<Screen name="foo" options={{ color: 'blue' }}>
{props => <TestScreen {...props} />}
</Screen>
<Screen name="bar" component={jest.fn()} />
</TestNavigator>
</NavigationContainer>
);
expect(root).toMatchInlineSnapshot(`
<main>
<h1
color="blue"
>
Hello world
</h1>
<div>
Test screen
</div>
</main>
`);
});
it('updates options with setOptions', () => {
const TestNavigator = (props: any) => {
const { state, descriptors } = useNavigationBuilder<
NavigationState,
any,
any,
any
>(MockRouter, props);
const { render, options } = descriptors[state.routes[state.index].key];
return (
<main>
<h1 color={options.color}>{options.title}</h1>
<p>{options.description}</p>
<caption>{options.author}</caption>
<div>{render()}</div>
</main>
);
};
const TestScreen = ({ navigation }: any): any => {
navigation.setOptions({
title: 'Hello world',
description: 'Something here',
});
React.useEffect(() => {
const timer = setTimeout(() =>
navigation.setOptions({
title: 'Hello again',
author: 'Jane',
})
);
return () => clearTimeout(timer);
});
return 'Test screen';
};
const element = (
<NavigationContainer>
<TestNavigator>
<Screen name="foo" options={{ color: 'blue' }}>
{props => <TestScreen {...props} />}
</Screen>
<Screen name="bar" component={jest.fn()} />
</TestNavigator>
</NavigationContainer>
);
const root = render(element);
act(() => jest.runAllTimers());
root.update(element);
expect(root).toMatchInlineSnapshot(`
<main>
<h1
color="blue"
>
Hello again
</h1>
<p>
Something here
</p>
<caption>
Jane
</caption>
<div>
Test screen
</div>
</main>
`);
});
it("returns correct value for canGoBack when it's not overridden", () => { it("returns correct value for canGoBack when it's not overridden", () => {
const TestNavigator = (props: any) => { const TestNavigator = (props: any) => {
const { state, descriptors } = useNavigationBuilder< const { state, descriptors } = useNavigationBuilder<
@@ -295,180 +604,3 @@ it('returns true for canGoBack when parent router handles GO_BACK', () => {
expect(result).toBe(false); expect(result).toBe(false);
}); });
it('sets options with options prop as a fuction', () => {
const TestNavigator = (props: any) => {
const { state, descriptors } = useNavigationBuilder<
NavigationState,
any,
{ title?: string },
any
>(MockRouter, props);
const { render, options } = descriptors[state.routes[state.index].key];
return (
<main>
<h1>{options.title}</h1>
<div>{render()}</div>
</main>
);
};
const TestScreen = (): any => 'Test screen';
const root = render(
<NavigationContainer>
<TestNavigator>
<Screen
name="foo"
component={TestScreen}
options={({ route }: any) => ({ title: route.params.author })}
initialParams={{ author: 'Jane' }}
/>
<Screen name="bar" component={jest.fn()} />
</TestNavigator>
</NavigationContainer>
);
expect(root).toMatchInlineSnapshot(`
<main>
<h1>
Jane
</h1>
<div>
Test screen
</div>
</main>
`);
});
it('sets initial options with setOptions', () => {
const TestNavigator = (props: any) => {
const { state, descriptors } = useNavigationBuilder<
NavigationState,
any,
{
title?: string;
color?: string;
},
any
>(MockRouter, props);
const { render, options } = descriptors[state.routes[state.index].key];
return (
<main>
<h1 color={options.color}>{options.title}</h1>
<div>{render()}</div>
</main>
);
};
const TestScreen = ({ navigation }: any): any => {
navigation.setOptions({
title: 'Hello world',
});
return 'Test screen';
};
const root = render(
<NavigationContainer>
<TestNavigator>
<Screen name="foo" options={{ color: 'blue' }}>
{props => <TestScreen {...props} />}
</Screen>
<Screen name="bar" component={jest.fn()} />
</TestNavigator>
</NavigationContainer>
);
expect(root).toMatchInlineSnapshot(`
<main>
<h1
color="blue"
>
Hello world
</h1>
<div>
Test screen
</div>
</main>
`);
});
it('updates options with setOptions', () => {
const TestNavigator = (props: any) => {
const { state, descriptors } = useNavigationBuilder<
NavigationState,
any,
any,
any
>(MockRouter, props);
const { render, options } = descriptors[state.routes[state.index].key];
return (
<main>
<h1 color={options.color}>{options.title}</h1>
<p>{options.description}</p>
<caption>{options.author}</caption>
<div>{render()}</div>
</main>
);
};
const TestScreen = ({ navigation }: any): any => {
navigation.setOptions({
title: 'Hello world',
description: 'Something here',
});
React.useEffect(() => {
const timer = setTimeout(() =>
navigation.setOptions({
title: 'Hello again',
author: 'Jane',
})
);
return () => clearTimeout(timer);
});
return 'Test screen';
};
const element = (
<NavigationContainer>
<TestNavigator>
<Screen name="foo" options={{ color: 'blue' }}>
{props => <TestScreen {...props} />}
</Screen>
<Screen name="bar" component={jest.fn()} />
</TestNavigator>
</NavigationContainer>
);
const root = render(element);
act(() => jest.runAllTimers());
root.update(element);
expect(root).toMatchInlineSnapshot(`
<main>
<h1
color="blue"
>
Hello again
</h1>
<p>
Something here
</p>
<caption>
Jane
</caption>
<div>
Test screen
</div>
</main>
`);
});

View File

@@ -0,0 +1,34 @@
import * as React from 'react';
import { render } from 'react-native-testing-library';
import useNavigationBuilder from '../useNavigationBuilder';
import useRoute from '../useRoute';
import NavigationContainer from '../NavigationContainer';
import Screen from '../Screen';
import MockRouter from './__fixtures__/MockRouter';
import { RouteProp } from '../types';
it('gets route prop from context', () => {
expect.assertions(1);
const TestNavigator = (props: any): any => {
const { state, descriptors } = useNavigationBuilder(MockRouter, props);
return state.routes.map(route => descriptors[route.key].render());
};
const Test = () => {
const route = useRoute<RouteProp<{ sample: { x: string } }, 'sample'>>();
expect(route && route.params && route.params.x).toEqual(1);
return null;
};
render(
<NavigationContainer>
<TestNavigator>
<Screen name="foo" component={Test} initialParams={{ x: 1 }} />
</TestNavigator>
</NavigationContainer>
);
});

View File

@@ -7,9 +7,11 @@ export { default as NavigationContainer } from './NavigationContainer';
export { default as createNavigator } from './createNavigator'; export { default as createNavigator } from './createNavigator';
export { default as NavigationContext } from './NavigationContext'; export { default as NavigationContext } from './NavigationContext';
export { default as NavigationRouteContext } from './NavigationRouteContext';
export { default as useNavigationBuilder } from './useNavigationBuilder'; export { default as useNavigationBuilder } from './useNavigationBuilder';
export { default as useNavigation } from './useNavigation'; export { default as useNavigation } from './useNavigation';
export { default as useRoute } from './useRoute';
export { default as useFocusEffect } from './useFocusEffect'; export { default as useFocusEffect } from './useFocusEffect';
export { default as useIsFocused } from './useIsFocused'; export { default as useIsFocused } from './useIsFocused';

View File

@@ -96,7 +96,12 @@ export type DefaultNavigatorOptions<
/** /**
* Default options for all screens under this navigator. * Default options for all screens under this navigator.
*/ */
screenOptions?: ScreenOptions; screenOptions?:
| ScreenOptions
| ((props: {
route: RouteProp<ParamListBase, string>;
navigation: any;
}) => ScreenOptions);
}; };
export type RouterFactory< export type RouterFactory<
@@ -534,11 +539,24 @@ export type TypedNavigator<
* Navigator component which manages the child screens. * Navigator component which manages the child screens.
*/ */
Navigator: React.ComponentType< Navigator: React.ComponentType<
React.ComponentProps<Navigator> & { Omit<
React.ComponentProps<Navigator>,
'initialRouteName' | 'screenOptions'
> & {
/** /**
* Route to focus on initial render. * Name of the route to focus by on initial render.
* If not specified, usually the first route is used.
*/ */
initialRouteName?: keyof ParamList; initialRouteName?: keyof ParamList;
/**
* Default options for all screens under this navigator.
*/
screenOptions?:
| ScreenOptions
| ((props: {
route: RouteProp<ParamList, keyof ParamList>;
navigation: any;
}) => ScreenOptions);
} }
>; >;
/** /**

View File

@@ -13,6 +13,7 @@ import {
NavigationState, NavigationState,
ParamListBase, ParamListBase,
RouteConfig, RouteConfig,
RouteProp,
Router, Router,
} from './types'; } from './types';
@@ -20,7 +21,12 @@ type Options<ScreenOptions extends object> = {
state: NavigationState; state: NavigationState;
screens: { [key: string]: RouteConfig<ParamListBase, string, ScreenOptions> }; screens: { [key: string]: RouteConfig<ParamListBase, string, ScreenOptions> };
navigation: NavigationHelpers<ParamListBase>; navigation: NavigationHelpers<ParamListBase>;
screenOptions?: ScreenOptions; screenOptions?:
| ScreenOptions
| ((props: {
route: RouteProp<ParamListBase, string>;
navigation: any;
}) => ScreenOptions);
onAction: ( onAction: (
action: NavigationAction, action: NavigationAction,
visitedNavigators?: Set<string> visitedNavigators?: Set<string>
@@ -93,13 +99,15 @@ export default function useDescriptors<
return state.routes.reduce( return state.routes.reduce(
(acc, route) => { (acc, route) => {
const screen = screens[route.name]; const screen = screens[route.name];
const navigation = navigations[route.key];
acc[route.key] = { acc[route.key] = {
navigation,
render() { render() {
return ( return (
<NavigationBuilderContext.Provider key={route.key} value={context}> <NavigationBuilderContext.Provider key={route.key} value={context}>
<SceneView <SceneView
navigation={navigations[route.key]} navigation={navigation}
route={route} route={route}
screen={screen} screen={screen}
getState={getState} getState={getState}
@@ -108,22 +116,30 @@ export default function useDescriptors<
</NavigationBuilderContext.Provider> </NavigationBuilderContext.Provider>
); );
}, },
options: { get options() {
return {
// The default `screenOptions` passed to the navigator // The default `screenOptions` passed to the navigator
...screenOptions, ...(typeof screenOptions === 'object' || screenOptions == null
? screenOptions
: screenOptions({
// @ts-ignore
route,
navigation,
})),
// The `options` prop passed to `Screen` elements // The `options` prop passed to `Screen` elements
...(typeof screen.options === 'object' || screen.options == null ...(typeof screen.options === 'object' || screen.options == null
? screen.options ? screen.options
: screen.options({ : screen.options({
// @ts-ignore // @ts-ignore
route, route,
navigation: navigations[route.key], navigation,
})), })),
// The options set via `navigation.setOptions` // The options set via `navigation.setOptions`
...options[route.key], ...options[route.key],
},
navigation: navigations[route.key],
}; };
},
};
return acc; return acc;
}, },
{} as { {} as {

View File

@@ -0,0 +1,22 @@
import * as React from 'react';
import NavigationRouteContext from './NavigationRouteContext';
import { ParamListBase, RouteProp } from './types';
/**
* Hook to access the route prop of the parent screen anywhere.
*
* @returns Route prop of the parent screen.
*/
export default function useRoute<
T extends RouteProp<ParamListBase, string>
>(): T {
const route = React.useContext(NavigationRouteContext);
if (route === undefined) {
throw new Error(
"We couldn't find a route object. Is your component inside a navigator?"
);
}
return route as T;
}

View File

@@ -3,6 +3,25 @@
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.
# [5.0.0-alpha.8](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/drawer@5.0.0-alpha.7...@react-navigation/drawer@5.0.0-alpha.8) (2019-08-31)
**Note:** Version bump only for package @react-navigation/drawer
# [5.0.0-alpha.7](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/drawer@5.0.0-alpha.6...@react-navigation/drawer@5.0.0-alpha.7) (2019-08-30)
### Bug Fixes
* rename contentContainerStyle to sceneContainerStyle for drawer ([fdc24d2](https://github.com/react-navigation/navigation-ex/commit/fdc24d2))
# [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/drawer@5.0.0-alpha.5...@react-navigation/drawer@5.0.0-alpha.6) (2019-08-29) # [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/drawer@5.0.0-alpha.5...@react-navigation/drawer@5.0.0-alpha.6) (2019-08-29)
**Note:** Version bump only for package @react-navigation/drawer **Note:** Version bump only for package @react-navigation/drawer

View File

@@ -11,7 +11,7 @@
"material", "material",
"drawer" "drawer"
], ],
"version": "5.0.0-alpha.6", "version": "5.0.0-alpha.8",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",
@@ -34,7 +34,7 @@
"clean": "del lib" "clean": "del lib"
}, },
"dependencies": { "dependencies": {
"@react-navigation/routers": "^5.0.0-alpha.6", "@react-navigation/routers": "^5.0.0-alpha.7",
"react-native-safe-area-view": "^0.14.6" "react-native-safe-area-view": "^0.14.6"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -75,7 +75,7 @@ export type DrawerNavigationConfig = {
lazy: boolean; lazy: boolean;
/** /**
* Whether a screen should be unmounted when navigating away from it. * Whether a screen should be unmounted when navigating away from it.
* Defaults to `false`.. * Defaults to `false`.
*/ */
unmountInactiveRoutes?: boolean; unmountInactiveRoutes?: boolean;
/** /**
@@ -87,7 +87,10 @@ export type DrawerNavigationConfig = {
* Options for the content component which will be passed as props. * Options for the content component which will be passed as props.
*/ */
contentOptions?: object; contentOptions?: object;
contentContainerStyle?: StyleProp<ViewStyle>; /**
* Style object for the component wrapping the screen content.
*/
sceneContainerStyle?: StyleProp<ViewStyle>;
style?: StyleProp<ViewStyle>; style?: StyleProp<ViewStyle>;
}; };

View File

@@ -88,7 +88,7 @@ type Props = {
statusBarAnimation: 'slide' | 'none' | 'fade'; statusBarAnimation: 'slide' | 'none' | 'fade';
overlayStyle?: StyleProp<ViewStyle>; overlayStyle?: StyleProp<ViewStyle>;
drawerStyle?: StyleProp<ViewStyle>; drawerStyle?: StyleProp<ViewStyle>;
contentContainerStyle?: StyleProp<ViewStyle>; sceneContainerStyle?: StyleProp<ViewStyle>;
renderDrawerContent: Renderer; renderDrawerContent: Renderer;
renderSceneContent: Renderer; renderSceneContent: Renderer;
gestureHandlerProps?: React.ComponentProps<typeof PanGestureHandler>; gestureHandlerProps?: React.ComponentProps<typeof PanGestureHandler>;
@@ -484,7 +484,7 @@ export default class DrawerView extends React.PureComponent<Props> {
drawerPosition, drawerPosition,
drawerType, drawerType,
swipeEdgeWidth, swipeEdgeWidth,
contentContainerStyle, sceneContainerStyle,
drawerStyle, drawerStyle,
overlayStyle, overlayStyle,
onGestureRef, onGestureRef,
@@ -534,7 +534,7 @@ export default class DrawerView extends React.PureComponent<Props> {
{ {
transform: [{ translateX: contentTranslateX }], transform: [{ translateX: contentTranslateX }],
}, },
contentContainerStyle as any, sceneContainerStyle as any,
]} ]}
> >
{renderSceneContent({ progress: this.progress })} {renderSceneContent({ progress: this.progress })}

View File

@@ -190,7 +190,7 @@ export default class DrawerView extends React.PureComponent<Props, State> {
drawerPosition, drawerPosition,
drawerBackgroundColor, drawerBackgroundColor,
overlayColor, overlayColor,
contentContainerStyle, sceneContainerStyle,
edgeWidth, edgeWidth,
minSwipeDistance, minSwipeDistance,
hideStatusBar, hideStatusBar,
@@ -222,7 +222,7 @@ export default class DrawerView extends React.PureComponent<Props, State> {
gestureHandlerProps={gestureHandlerProps} gestureHandlerProps={gestureHandlerProps}
drawerType={drawerType} drawerType={drawerType}
drawerPosition={drawerPosition} drawerPosition={drawerPosition}
contentContainerStyle={contentContainerStyle} sceneContainerStyle={sceneContainerStyle}
drawerStyle={{ drawerStyle={{
backgroundColor: drawerBackgroundColor || 'white', backgroundColor: drawerBackgroundColor || 'white',
width: this.state.drawerWidth, width: this.state.drawerWidth,

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.
# [5.0.0-alpha.6](https://github.com/satya164/navigation-ex/compare/@react-navigation/example@5.0.0-alpha.4...@react-navigation/example@5.0.0-alpha.6) (2019-08-31)
**Note:** Version bump only for package @react-navigation/example
# [5.0.0-alpha.5](https://github.com/satya164/navigation-ex/compare/@react-navigation/example@5.0.0-alpha.4...@react-navigation/example@5.0.0-alpha.5) (2019-08-31)
**Note:** Version bump only for package @react-navigation/example
# [5.0.0-alpha.4](https://github.com/satya164/navigation-ex/compare/@react-navigation/example@5.0.0-alpha.3...@react-navigation/example@5.0.0-alpha.4) (2019-08-31)
### Bug Fixes
* handle route names change when all routes are removed ([#86](https://github.com/satya164/navigation-ex/issues/86)) ([1b2983e](https://github.com/satya164/navigation-ex/commit/1b2983e))
# [5.0.0-alpha.3](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/example@5.0.0-alpha.2...@react-navigation/example@5.0.0-alpha.3) (2019-08-29) # [5.0.0-alpha.3](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/example@5.0.0-alpha.2...@react-navigation/example@5.0.0-alpha.3) (2019-08-29)

View File

@@ -1,7 +1,7 @@
{ {
"name": "@react-navigation/example", "name": "@react-navigation/example",
"description": "Demo app to showcase various functionality of React Navigation", "description": "Demo app to showcase various functionality of React Navigation",
"version": "5.0.0-alpha.3", "version": "5.0.0-alpha.6",
"private": true, "private": true,
"workspaces": { "workspaces": {
"nohoist": [ "nohoist": [

View File

@@ -0,0 +1,128 @@
import * as React from 'react';
import { View, TextInput, ActivityIndicator, StyleSheet } from 'react-native';
import { Title, Button } from 'react-native-paper';
import { ParamListBase } from '@react-navigation/core';
import {
createStackNavigator,
HeaderBackButton,
StackNavigationProp,
} from '@react-navigation/stack';
type AuthStackParams = {
splash: undefined;
home: undefined;
'sign-in': undefined;
};
const SplashScreen = () => (
<View style={styles.content}>
<ActivityIndicator />
</View>
);
const SignInScreen = ({
setUserToken,
}: {
setUserToken: (token: string) => void;
}) => {
return (
<View style={styles.content}>
<TextInput placeholder="Username" style={styles.input} />
<TextInput placeholder="Password" secureTextEntry style={styles.input} />
<Button
mode="contained"
onPress={() => setUserToken('token')}
style={styles.button}
>
Sign in
</Button>
</View>
);
};
const HomeScreen = ({
setUserToken,
}: {
setUserToken: (token: undefined) => void;
}) => {
return (
<View style={styles.content}>
<Title style={styles.text}>Signed in successfully 🎉</Title>
<Button onPress={() => setUserToken(undefined)} style={styles.button}>
Sign out
</Button>
</View>
);
};
const SimpleStack = createStackNavigator<AuthStackParams>();
type Props = {
navigation: StackNavigationProp<ParamListBase>;
};
export default function SimpleStackScreen({ navigation }: Props) {
const [isLoading, setIsLoading] = React.useState(true);
const [userToken, setUserToken] = React.useState<string | undefined>(
undefined
);
React.useEffect(() => {
const timer = setTimeout(() => setIsLoading(false), 1000);
return () => clearTimeout(timer);
}, []);
navigation.setOptions({
header: null,
});
return (
<SimpleStack.Navigator
screenOptions={{
headerLeft: () => (
<HeaderBackButton onPress={() => navigation.goBack()} />
),
}}
>
{isLoading ? (
<SimpleStack.Screen
name="splash"
component={SplashScreen}
options={{ title: `Auth Flow` }}
/>
) : userToken === undefined ? (
<SimpleStack.Screen name="sign-in" options={{ title: `Sign in` }}>
{() => <SignInScreen setUserToken={setUserToken} />}
</SimpleStack.Screen>
) : (
<SimpleStack.Screen name="home" options={{ title: 'Home' }}>
{() => <HomeScreen setUserToken={setUserToken} />}
</SimpleStack.Screen>
)}
</SimpleStack.Navigator>
);
}
const styles = StyleSheet.create({
content: {
flex: 1,
padding: 16,
justifyContent: 'center',
},
input: {
margin: 8,
padding: 10,
backgroundColor: 'white',
borderRadius: 3,
borderWidth: StyleSheet.hairlineWidth,
borderColor: 'rgba(0, 0, 0, 0.08)',
},
button: {
margin: 8,
},
text: {
textAlign: 'center',
margin: 8,
},
});

View File

@@ -8,7 +8,10 @@ import {
getStateFromPath, getStateFromPath,
NavigationContainerRef, NavigationContainerRef,
} from '@react-navigation/core'; } from '@react-navigation/core';
import { useLinking, NativeContainer } from '@react-navigation/native'; import {
useLinking,
NavigationNativeContainer,
} from '@react-navigation/native';
import { import {
createDrawerNavigator, createDrawerNavigator,
DrawerNavigationProp, DrawerNavigationProp,
@@ -23,6 +26,7 @@ import SimpleStackScreen from './Screens/SimpleStack';
import BottomTabsScreen from './Screens/BottomTabs'; import BottomTabsScreen from './Screens/BottomTabs';
import MaterialTopTabsScreen from './Screens/MaterialTopTabs'; import MaterialTopTabsScreen from './Screens/MaterialTopTabs';
import MaterialBottomTabs from './Screens/MaterialBottomTabs'; import MaterialBottomTabs from './Screens/MaterialBottomTabs';
import AuthFlow from './Screens/AuthFlow';
YellowBox.ignoreWarnings(['Require cycle:', 'Warning: Async Storage']); YellowBox.ignoreWarnings(['Require cycle:', 'Warning: Async Storage']);
@@ -47,6 +51,10 @@ const SCREENS = {
title: 'Material Bottom Tabs', title: 'Material Bottom Tabs',
component: MaterialBottomTabs, component: MaterialBottomTabs,
}, },
'auth-flow': {
title: 'Auth Flow',
component: AuthFlow,
},
}; };
const Drawer = createDrawerNavigator<RootDrawerParamList>(); const Drawer = createDrawerNavigator<RootDrawerParamList>();
@@ -113,7 +121,7 @@ export default function App() {
} }
return ( return (
<NativeContainer <NavigationNativeContainer
ref={containerRef} ref={containerRef}
initialState={initialState} initialState={initialState}
onStateChange={state => onStateChange={state =>
@@ -172,6 +180,6 @@ export default function App() {
)} )}
</Drawer.Screen> </Drawer.Screen>
</Drawer.Navigator> </Drawer.Navigator>
</NativeContainer> </NavigationNativeContainer>
); );
} }

View File

@@ -3,6 +3,14 @@
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.
# [5.0.0-alpha.7](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/material-bottom-tabs@5.0.0-alpha.6...@react-navigation/material-bottom-tabs@5.0.0-alpha.7) (2019-08-31)
**Note:** Version bump only for package @react-navigation/material-bottom-tabs
# [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/material-bottom-tabs@5.0.0-alpha.5...@react-navigation/material-bottom-tabs@5.0.0-alpha.6) (2019-08-29) # [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/material-bottom-tabs@5.0.0-alpha.5...@react-navigation/material-bottom-tabs@5.0.0-alpha.6) (2019-08-29)

View File

@@ -11,7 +11,7 @@
"material", "material",
"tab" "tab"
], ],
"version": "5.0.0-alpha.6", "version": "5.0.0-alpha.7",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",
@@ -34,7 +34,7 @@
"clean": "del lib" "clean": "del lib"
}, },
"dependencies": { "dependencies": {
"@react-navigation/routers": "^5.0.0-alpha.6" "@react-navigation/routers": "^5.0.0-alpha.7"
}, },
"devDependencies": { "devDependencies": {
"@react-native-community/bob": "^0.7.0", "@react-native-community/bob": "^0.7.0",

View File

@@ -3,6 +3,14 @@
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.
# [5.0.0-alpha.7](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/material-top-tabs@5.0.0-alpha.6...@react-navigation/material-top-tabs@5.0.0-alpha.7) (2019-08-31)
**Note:** Version bump only for package @react-navigation/material-top-tabs
# [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/material-top-tabs@5.0.0-alpha.5...@react-navigation/material-top-tabs@5.0.0-alpha.6) (2019-08-29) # [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/material-top-tabs@5.0.0-alpha.5...@react-navigation/material-top-tabs@5.0.0-alpha.6) (2019-08-29)

View File

@@ -11,7 +11,7 @@
"material", "material",
"tab" "tab"
], ],
"version": "5.0.0-alpha.6", "version": "5.0.0-alpha.7",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",
@@ -34,7 +34,7 @@
"clean": "del lib" "clean": "del lib"
}, },
"dependencies": { "dependencies": {
"@react-navigation/routers": "^5.0.0-alpha.6" "@react-navigation/routers": "^5.0.0-alpha.7"
}, },
"devDependencies": { "devDependencies": {
"@react-native-community/bob": "^0.7.0", "@react-native-community/bob": "^0.7.0",

View File

@@ -125,7 +125,7 @@ export type MaterialTopTabNavigationConfig = Partial<
* *
* This view is usually only shown for a split second. Keep it lightweight. * This view is usually only shown for a split second. Keep it lightweight.
* *
* By default, this renders null.. * By default, this renders null.
*/ */
lazyPlaceholderComponent?: React.ComponentType<{ route: Route<string> }>; lazyPlaceholderComponent?: React.ComponentType<{ route: Route<string> }>;
/** /**

View File

@@ -3,6 +3,22 @@
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.
# [5.0.0-alpha.7](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/native@5.0.0-alpha.5...@react-navigation/native@5.0.0-alpha.7) (2019-08-31)
**Note:** Version bump only for package @react-navigation/native
# [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/native@5.0.0-alpha.5...@react-navigation/native@5.0.0-alpha.6) (2019-08-31)
**Note:** Version bump only for package @react-navigation/native
# [5.0.0-alpha.5](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/native@5.0.0-alpha.4...@react-navigation/native@5.0.0-alpha.5) (2019-08-29) # [5.0.0-alpha.5](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/native@5.0.0-alpha.4...@react-navigation/native@5.0.0-alpha.5) (2019-08-29)

View File

@@ -7,7 +7,7 @@
"ios", "ios",
"android" "android"
], ],
"version": "5.0.0-alpha.5", "version": "5.0.0-alpha.7",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",

View File

@@ -16,14 +16,14 @@ import useBackButton from './useBackButton';
* @param props.children Child elements to render the content. * @param props.children Child elements to render the content.
* @param props.ref Ref object which refers to the navigation object containing helper methods. * @param props.ref Ref object which refers to the navigation object containing helper methods.
*/ */
const NavigationNativeContainer = React.forwardRef(function NativeContainer(
const NativeContainer = React.forwardRef(function NativeContainer(
props: NavigationContainerProps, props: NavigationContainerProps,
ref: React.Ref<NavigationContainerRef> ref: React.Ref<NavigationContainerRef>
) { ) {
const refContainer = React.useRef<NavigationContainerRef>(null); const refContainer = React.useRef<NavigationContainerRef>(null);
useBackButton(refContainer); useBackButton(refContainer);
React.useImperativeHandle(ref, () => refContainer.current); React.useImperativeHandle(ref, () => refContainer.current);
return ( return (
@@ -35,4 +35,4 @@ const NativeContainer = React.forwardRef(function NativeContainer(
); );
}); });
export default NativeContainer; export default NavigationNativeContainer;

View File

@@ -1,4 +1,7 @@
export { default as NativeContainer } from './NativeContainer'; export {
default as NavigationNativeContainer,
} from './NavigationNativeContainer';
export { default as useBackButton } from './useBackButton'; export { default as useBackButton } from './useBackButton';
export { default as useLinking } from './useLinking'; export { default as useLinking } from './useLinking';
export { default as useScrollToTop } from './useScrollToTop'; export { default as useScrollToTop } from './useScrollToTop';

View File

@@ -3,6 +3,17 @@
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.
# [5.0.0-alpha.7](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/routers@5.0.0-alpha.6...@react-navigation/routers@5.0.0-alpha.7) (2019-08-31)
### Bug Fixes
* handle route names change when all routes are removed ([#86](https://github.com/react-navigation/navigation-ex/issues/86)) ([1b2983e](https://github.com/react-navigation/navigation-ex/commit/1b2983e))
# [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/routers@5.0.0-alpha.5...@react-navigation/routers@5.0.0-alpha.6) (2019-08-29) # [5.0.0-alpha.6](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/routers@5.0.0-alpha.5...@react-navigation/routers@5.0.0-alpha.6) (2019-08-29)

View File

@@ -138,7 +138,7 @@ it('gets state on route names change', () => {
expect( expect(
router.getStateForRouteNamesChange( router.getStateForRouteNamesChange(
{ {
index: 0, index: 2,
key: 'stack-test', key: 'stack-test',
routeNames: ['bar', 'baz', 'qux'], routeNames: ['bar', 'baz', 'qux'],
routes: [ routes: [
@@ -157,7 +157,7 @@ it('gets state on route names change', () => {
} }
) )
).toEqual({ ).toEqual({
index: 0, index: 1,
key: 'stack-test', key: 'stack-test',
routeNames: ['qux', 'baz', 'foo', 'fiz'], routeNames: ['qux', 'baz', 'foo', 'fiz'],
routes: [ routes: [
@@ -166,6 +166,64 @@ it('gets state on route names change', () => {
], ],
stale: false, stale: false,
}); });
expect(
router.getStateForRouteNamesChange(
{
index: 1,
key: 'stack-test',
routeNames: ['foo', 'bar'],
routes: [
{ key: 'foo-test', name: 'foo' },
{ key: 'bar-test', name: 'bar' },
],
stale: false,
},
{
routeNames: ['baz', 'qux'],
routeParamList: {
baz: { name: 'John' },
},
}
)
).toEqual({
index: 0,
key: 'stack-test',
routeNames: ['baz', 'qux'],
routes: [{ key: 'baz-test', name: 'baz', params: { name: 'John' } }],
stale: false,
});
});
it('gets state on route names change with initialRouteName', () => {
const router = StackRouter({ initialRouteName: 'qux' });
expect(
router.getStateForRouteNamesChange(
{
index: 1,
key: 'stack-test',
routeNames: ['foo', 'bar'],
routes: [
{ key: 'foo-test', name: 'foo' },
{ key: 'bar-test', name: 'bar' },
],
stale: false,
},
{
routeNames: ['baz', 'qux'],
routeParamList: {
baz: { name: 'John' },
},
}
)
).toEqual({
index: 0,
key: 'stack-test',
routeNames: ['baz', 'qux'],
routes: [{ key: 'qux-test', name: 'qux' }],
stale: false,
});
}); });
it('handles navigate action', () => { it('handles navigate action', () => {

View File

@@ -6,7 +6,7 @@
"react-native", "react-native",
"react-navigation" "react-navigation"
], ],
"version": "5.0.0-alpha.6", "version": "5.0.0-alpha.7",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",

View File

@@ -114,11 +114,25 @@ export default function StackRouter(options: StackRouterOptions) {
}; };
}, },
getStateForRouteNamesChange(state, { routeNames }) { getStateForRouteNamesChange(state, { routeNames, routeParamList }) {
const routes = state.routes.filter(route => const routes = state.routes.filter(route =>
routeNames.includes(route.name) routeNames.includes(route.name)
); );
if (routes.length === 0) {
const initialRouteName =
options.initialRouteName !== undefined &&
routeNames.includes(options.initialRouteName)
? options.initialRouteName
: routeNames[0];
routes.push({
key: `${initialRouteName}-${shortid()}`,
name: initialRouteName,
params: routeParamList[initialRouteName],
});
}
return { return {
...state, ...state,
routeNames, routeNames,

View File

@@ -3,6 +3,82 @@
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.
# [5.0.0-alpha.15](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/stack@5.0.0-alpha.14...@react-navigation/stack@5.0.0-alpha.15) (2019-09-04)
### Features
* add approximate android Q transition ([196cce0](https://github.com/react-navigation/navigation-ex/commit/196cce0))
# [5.0.0-alpha.14](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/stack@5.0.0-alpha.13...@react-navigation/stack@5.0.0-alpha.14) (2019-09-03)
### Bug Fixes
* change order of attaching nodes in card exec ([167d58c](https://github.com/react-navigation/navigation-ex/commit/167d58c))
# [5.0.0-alpha.13](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/stack@5.0.0-alpha.12...@react-navigation/stack@5.0.0-alpha.13) (2019-09-01)
### Features
* useForeground if possible in stack header backButton ([aa6313c](https://github.com/react-navigation/navigation-ex/commit/aa6313c))
# [5.0.0-alpha.12](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/stack@5.0.0-alpha.11...@react-navigation/stack@5.0.0-alpha.12) (2019-09-01)
### Bug Fixes
* defer running the animation to next frame ([c7a79a6](https://github.com/react-navigation/navigation-ex/commit/c7a79a6))
* stack with gesture enabled ([55ec815](https://github.com/react-navigation/navigation-ex/commit/55ec815))
# [5.0.0-alpha.11](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/stack@5.0.0-alpha.10...@react-navigation/stack@5.0.0-alpha.11) (2019-09-01)
### Features
* optimizations in stack ([3f853d4](https://github.com/react-navigation/navigation-ex/commit/3f853d4))
# [5.0.0-alpha.10](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/stack@5.0.0-alpha.9...@react-navigation/stack@5.0.0-alpha.10) (2019-08-31)
**Note:** Version bump only for package @react-navigation/stack
# [5.0.0-alpha.9](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/stack@5.0.0-alpha.8...@react-navigation/stack@5.0.0-alpha.9) (2019-08-30)
### Bug Fixes
* change interpolated style when idle to avoid messing up reanimated ([3ad2e6e](https://github.com/react-navigation/navigation-ex/commit/3ad2e6e))
* properly set animated node on gestureEnabled change ([6a8242c](https://github.com/react-navigation/navigation-ex/commit/6a8242c))
# [5.0.0-alpha.8](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/stack@5.0.0-alpha.7...@react-navigation/stack@5.0.0-alpha.8) (2019-08-29) # [5.0.0-alpha.8](https://github.com/react-navigation/navigation-ex/compare/@react-navigation/stack@5.0.0-alpha.7...@react-navigation/stack@5.0.0-alpha.8) (2019-08-29)

View File

@@ -10,7 +10,7 @@
"android", "android",
"stack" "stack"
], ],
"version": "5.0.0-alpha.8", "version": "5.0.0-alpha.15",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",
@@ -33,7 +33,7 @@
"clean": "del lib" "clean": "del lib"
}, },
"dependencies": { "dependencies": {
"@react-navigation/routers": "^5.0.0-alpha.6", "@react-navigation/routers": "^5.0.0-alpha.7",
"react-native-safe-area-view": "^0.14.6" "react-native-safe-area-view": "^0.14.6"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -9,15 +9,16 @@ const { cond, add, multiply, interpolate } = Animated;
* Standard iOS-style slide in from the right. * Standard iOS-style slide in from the right.
*/ */
export function forHorizontalIOS({ export function forHorizontalIOS({
progress: { current, next }, current,
next,
layouts: { screen }, layouts: { screen },
}: CardInterpolationProps): CardInterpolatedStyle { }: CardInterpolationProps): CardInterpolatedStyle {
const translateFocused = interpolate(current, { const translateFocused = interpolate(current.progress, {
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [I18nManager.isRTL ? -screen.width : screen.width, 0], outputRange: [I18nManager.isRTL ? -screen.width : screen.width, 0],
}); });
const translateUnfocused = next const translateUnfocused = next
? interpolate(next, { ? interpolate(next.progress, {
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [ outputRange: [
0, 0,
@@ -26,12 +27,12 @@ export function forHorizontalIOS({
}) })
: 0; : 0;
const overlayOpacity = interpolate(current, { const overlayOpacity = interpolate(current.progress, {
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [0, 0.07], outputRange: [0, 0.07],
}); });
const shadowOpacity = interpolate(current, { const shadowOpacity = interpolate(current.progress, {
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [0, 0.3], outputRange: [0, 0.3],
}); });
@@ -54,10 +55,10 @@ export function forHorizontalIOS({
* Standard iOS-style slide in from the bottom (used for modals). * Standard iOS-style slide in from the bottom (used for modals).
*/ */
export function forVerticalIOS({ export function forVerticalIOS({
progress: { current }, current,
layouts: { screen }, layouts: { screen },
}: CardInterpolationProps): CardInterpolatedStyle { }: CardInterpolationProps): CardInterpolatedStyle {
const translateY = interpolate(current, { const translateY = interpolate(current.progress, {
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [screen.height, 0], outputRange: [screen.height, 0],
}); });
@@ -77,14 +78,15 @@ export function forVerticalIOS({
*/ */
export function forModalPresentationIOS({ export function forModalPresentationIOS({
index, index,
progress: { current, next }, current,
next,
layouts: { screen }, layouts: { screen },
}: CardInterpolationProps): CardInterpolatedStyle { }: CardInterpolationProps): CardInterpolatedStyle {
const topOffset = 10; const topOffset = 10;
const statusBarHeight = getStatusBarHeight(screen.width > screen.height); const statusBarHeight = getStatusBarHeight(screen.width > screen.height);
const aspectRatio = screen.height / screen.width; const aspectRatio = screen.height / screen.width;
const progress = add(current, next ? next : 0); const progress = add(current.progress, next ? next.progress : 0);
const translateY = interpolate(progress, { const translateY = interpolate(progress, {
inputRange: [0, 1, 2], inputRange: [0, 1, 2],
@@ -129,19 +131,19 @@ export function forModalPresentationIOS({
* Standard Android-style fade in from the bottom for Android Oreo. * Standard Android-style fade in from the bottom for Android Oreo.
*/ */
export function forFadeFromBottomAndroid({ export function forFadeFromBottomAndroid({
progress: { current }, current,
layouts: { screen }, layouts: { screen },
closing, closing,
}: CardInterpolationProps): CardInterpolatedStyle { }: CardInterpolationProps): CardInterpolatedStyle {
const translateY = interpolate(current, { const translateY = interpolate(current.progress, {
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [multiply(screen.height, 0.08), 0], outputRange: [multiply(screen.height, 0.08), 0],
}); });
const opacity = cond( const opacity = cond(
closing, closing,
current, current.progress,
interpolate(current, { interpolate(current.progress, {
inputRange: [0, 0.5, 0.9, 1], inputRange: [0, 0.5, 0.9, 1],
outputRange: [0, 0.25, 0.7, 1], outputRange: [0, 0.25, 0.7, 1],
}) })
@@ -159,24 +161,25 @@ export function forFadeFromBottomAndroid({
* Standard Android-style reveal from the bottom for Android Pie. * Standard Android-style reveal from the bottom for Android Pie.
*/ */
export function forRevealFromBottomAndroid({ export function forRevealFromBottomAndroid({
progress: { current, next }, current,
next,
layouts: { screen }, layouts: { screen },
}: CardInterpolationProps): CardInterpolatedStyle { }: CardInterpolationProps): CardInterpolatedStyle {
const containerTranslateY = interpolate(current, { const containerTranslateY = interpolate(current.progress, {
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [screen.height, 0], outputRange: [screen.height, 0],
}); });
const cardTranslateYFocused = interpolate(current, { const cardTranslateYFocused = interpolate(current.progress, {
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [multiply(screen.height, 95.9 / 100, -1), 0], outputRange: [multiply(screen.height, 95.9 / 100, -1), 0],
}); });
const cardTranslateYUnfocused = next const cardTranslateYUnfocused = next
? interpolate(next, { ? interpolate(next.progress, {
inputRange: [0, 1], inputRange: [0, 1],
outputRange: [0, multiply(screen.height, 2 / 100, -1)], outputRange: [0, multiply(screen.height, 2 / 100, -1)],
}) })
: 0; : 0;
const overlayOpacity = interpolate(current, { const overlayOpacity = interpolate(current.progress, {
inputRange: [0, 0.36, 1], inputRange: [0, 0.36, 1],
outputRange: [0, 0.1, 0.1], outputRange: [0, 0.1, 0.1],
}); });
@@ -195,3 +198,34 @@ export function forRevealFromBottomAndroid({
overlayStyle: { opacity: overlayOpacity }, overlayStyle: { opacity: overlayOpacity },
}; };
} }
/**
* Standard Android-style reveal from the bottom for Android Q.
* TODO: Update this with correct values when AOSP is updated.
*/
export function forScaleFromCenterAndroid({
current,
next,
}: CardInterpolationProps): CardInterpolatedStyle {
const cardOpacityFocused = interpolate(current.progress, {
inputRange: [0, 0.5, 1],
outputRange: [0, 1, 1],
});
const cardScaleFocused = interpolate(current.progress, {
inputRange: [0, 1],
outputRange: [0.9, 1],
});
const cardScaleUnFocused = next
? interpolate(next.progress, {
inputRange: [0, 1],
outputRange: [1, 1.1],
})
: 1;
return {
containerStyle: {
opacity: cardOpacityFocused,
transform: [{ scale: cardScaleFocused }, { scale: cardScaleUnFocused }],
},
};
}

View File

@@ -8,7 +8,8 @@ const { interpolate, add } = Animated;
* Standard UIKit style animation for the header where the title fades into the back button label. * Standard UIKit style animation for the header where the title fades into the back button label.
*/ */
export function forUIKit({ export function forUIKit({
progress: { current, next }, current,
next,
layouts, layouts,
}: HeaderInterpolationProps): HeaderInterpolatedStyle { }: HeaderInterpolationProps): HeaderInterpolatedStyle {
const defaultOffset = 100; const defaultOffset = 100;
@@ -30,7 +31,7 @@ export function forUIKit({
// The back title also animates in from this position // The back title also animates in from this position
const rightOffset = layouts.screen.width / 4; const rightOffset = layouts.screen.width / 4;
const progress = add(current, next ? next : 0); const progress = add(current.progress, next ? next.progress : 0);
return { return {
leftButtonStyle: { leftButtonStyle: {
@@ -92,9 +93,10 @@ export function forUIKit({
* Simple fade animation for the header elements. * Simple fade animation for the header elements.
*/ */
export function forFade({ export function forFade({
progress: { current, next }, current,
next,
}: HeaderInterpolationProps): HeaderInterpolatedStyle { }: HeaderInterpolationProps): HeaderInterpolatedStyle {
const progress = add(current, next ? next : 0); const progress = add(current.progress, next ? next.progress : 0);
const opacity = interpolate(progress, { const opacity = interpolate(progress, {
inputRange: [0, 1, 2], inputRange: [0, 1, 2],
outputRange: [0, 1, 0], outputRange: [0, 1, 0],
@@ -112,10 +114,11 @@ export function forFade({
* Simple translate animation to translate the header along with the sliding screen. * Simple translate animation to translate the header along with the sliding screen.
*/ */
export function forStatic({ export function forStatic({
progress: { current, next }, current,
next,
layouts: { screen }, layouts: { screen },
}: HeaderInterpolationProps): HeaderInterpolatedStyle { }: HeaderInterpolationProps): HeaderInterpolatedStyle {
const progress = add(current, next ? next : 0); const progress = add(current.progress, next ? next.progress : 0);
const translateX = interpolate(progress, { const translateX = interpolate(progress, {
inputRange: [0, 1, 2], inputRange: [0, 1, 2],
outputRange: I18nManager.isRTL outputRange: I18nManager.isRTL

View File

@@ -1,6 +1,7 @@
import { import {
forHorizontalIOS, forHorizontalIOS,
forVerticalIOS, forVerticalIOS,
forScaleFromCenterAndroid,
forRevealFromBottomAndroid, forRevealFromBottomAndroid,
forFadeFromBottomAndroid, forFadeFromBottomAndroid,
forModalPresentationIOS, forModalPresentationIOS,
@@ -8,6 +9,7 @@ import {
import { forNoAnimation, forFade } from './HeaderStyleInterpolators'; import { forNoAnimation, forFade } from './HeaderStyleInterpolators';
import { import {
TransitionIOSSpec, TransitionIOSSpec,
ScaleFromCenterAndroidSpec,
RevealFromBottomAndroidSpec, RevealFromBottomAndroidSpec,
FadeOutToBottomAndroidSpec, FadeOutToBottomAndroidSpec,
FadeInFromBottomAndroidSpec, FadeInFromBottomAndroidSpec,
@@ -70,7 +72,7 @@ export const FadeFromBottomAndroid: TransitionPreset = {
}; };
/** /**
* Standard Android navigation transition when opening or closing an Activity on Android >= 9 (Pie). * Standard Android navigation transition when opening or closing an Activity on Android 9 (Pie).
*/ */
export const RevealFromBottomAndroid: TransitionPreset = { export const RevealFromBottomAndroid: TransitionPreset = {
gestureDirection: 'vertical', gestureDirection: 'vertical',
@@ -82,6 +84,19 @@ export const RevealFromBottomAndroid: TransitionPreset = {
headerStyleInterpolator: forNoAnimation, headerStyleInterpolator: forNoAnimation,
}; };
/**
* Standard Android navigation transition when opening or closing an Activity on Android 10 (Q).
*/
export const ScaleFromCenterAndroid: TransitionPreset = {
gestureDirection: 'horizontal',
transitionSpec: {
open: ScaleFromCenterAndroidSpec,
close: ScaleFromCenterAndroidSpec,
},
cardStyleInterpolator: forScaleFromCenterAndroid,
headerStyleInterpolator: forNoAnimation,
};
/** /**
* Default navigation transition for the current platform. * Default navigation transition for the current platform.
*/ */

View File

@@ -53,3 +53,15 @@ export const RevealFromBottomAndroidSpec: TransitionSpec = {
easing: Easing.bezier(0.35, 0.45, 0, 1), easing: Easing.bezier(0.35, 0.45, 0, 1),
}, },
}; };
/**
* Approximate configuration for activity open animation from Android Q.
* TODO: Update this with correct values when AOSP is updated.
*/
export const ScaleFromCenterAndroidSpec: TransitionSpec = {
animation: 'timing',
config: {
duration: 425,
easing: Easing.bezier(0.35, 0.45, 0, 1),
},
};

View File

@@ -409,24 +409,29 @@ export type TransitionSpec =
| { animation: 'timing'; config: TimingConfig }; | { animation: 'timing'; config: TimingConfig };
export type CardInterpolationProps = { export type CardInterpolationProps = {
/**
* Values for the current screen.
*/
current: {
/**
* Animated node representing the progress value of the current screen.
*/
progress: Animated.Node<number>;
};
/**
* Values for the current screen the screen after this one in the stack.
* This can be `undefined` in case the screen animating is the last one.
*/
next?: {
/**
* Animated node representing the progress value of the next screen.
*/
progress: Animated.Node<number>;
};
/** /**
* The index of the card in the stack. * The index of the card in the stack.
*/ */
index: number; index: number;
/**
* Animated nodes representing the progress of the animation.
*/
progress: {
/**
* Progress value of the current screen.
*/
current: Animated.Node<number>;
/**
* Progress value for the screen after this one in the stack.
* This can be `undefined` in case the screen animating is the last one.
*/
next?: Animated.Node<number>;
};
/** /**
* Animated node representing whether the card is closing. * Animated node representing whether the card is closing.
*/ */
@@ -467,18 +472,23 @@ export type CardStyleInterpolator = (
export type HeaderInterpolationProps = { export type HeaderInterpolationProps = {
/** /**
* Animated nodes representing the progress of the animation. * Values for the current screen (the screen which owns this header).
*/ */
progress: { current: {
/** /**
* Progress value of the current screen (the screen which owns this header). * Animated node representing the progress value of the current screen.
*/ */
current: Animated.Node<number>; progress: Animated.Node<number>;
};
/** /**
* Progress value for the screen after this one in the stack. * Values for the current screen the screen after this one in the stack.
* This can be `undefined` in case the screen animating is the last one. * This can be `undefined` in case the screen animating is the last one.
*/ */
next?: Animated.Node<number>; next?: {
/**
* Animated node representing the progress value of the next screen.
*/
progress: Animated.Node<number>;
}; };
/** /**
* Layout measurements for various items we use for animation. * Layout measurements for various items we use for animation.

View File

@@ -121,10 +121,8 @@ export default class HeaderSegment extends React.Component<Props, State> {
leftLabelLayout: Layout | undefined leftLabelLayout: Layout | undefined
) => ) =>
styleInterpolator({ styleInterpolator({
progress: { current: { progress: current },
current, next: next && { progress: next },
next,
},
layouts: { layouts: {
screen: layout, screen: layout,
title: titleLayout, title: titleLayout,

View File

@@ -13,7 +13,13 @@ import {
PanGestureHandler, PanGestureHandler,
State as GestureState, State as GestureState,
} from 'react-native-gesture-handler'; } from 'react-native-gesture-handler';
import { TransitionSpec, CardStyleInterpolator, Layout } from '../../types'; import {
TransitionSpec,
CardStyleInterpolator,
Layout,
SpringConfig,
TimingConfig,
} from '../../types';
import memoize from '../../utils/memoize'; import memoize from '../../utils/memoize';
import StackGestureContext from '../../utils/StackGestureContext'; import StackGestureContext from '../../utils/StackGestureContext';
import PointerEventsView from './PointerEventsView'; import PointerEventsView from './PointerEventsView';
@@ -50,12 +56,31 @@ type Props = ViewProps & {
contentStyle?: StyleProp<ViewStyle>; contentStyle?: StyleProp<ViewStyle>;
}; };
type AnimatedSpringConfig = {
damping: Animated.Value<number>;
mass: Animated.Value<number>;
stiffness: Animated.Value<number>;
restSpeedThreshold: Animated.Value<number>;
restDisplacementThreshold: Animated.Value<number>;
overshootClamping: Animated.Value<boolean>;
};
export type AnimatedTimingConfig = {
duration: Animated.Value<number>;
easing: Animated.EasingFunction;
};
type Binary = 0 | 1; type Binary = 0 | 1;
const TRUE = 1; const TRUE = 1;
const TRUE_NODE = new Animated.Value(TRUE);
const FALSE = 0; const FALSE = 0;
const NOOP = 0; const FALSE_NODE = new Animated.Value(FALSE);
const NOOP_NODE = FALSE_NODE;
const UNSET = -1; const UNSET = -1;
const UNSET_NODE = new Animated.Value(UNSET);
const MINUS_ONE_NODE = UNSET_NODE;
const DIRECTION_VERTICAL = -1; const DIRECTION_VERTICAL = -1;
const DIRECTION_HORIZONTAL = 1; const DIRECTION_HORIZONTAL = 1;
@@ -110,7 +135,7 @@ if (Animated.proc) {
damping: Animated.Adaptable<number>, damping: Animated.Adaptable<number>,
mass: Animated.Adaptable<number>, mass: Animated.Adaptable<number>,
stiffness: Animated.Adaptable<number>, stiffness: Animated.Adaptable<number>,
overshootClamping: Animated.Adaptable<number>, overshootClamping: Animated.Adaptable<boolean>,
restSpeedThreshold: Animated.Adaptable<number>, restSpeedThreshold: Animated.Adaptable<number>,
restDisplacementThreshold: Animated.Adaptable<number>, restDisplacementThreshold: Animated.Adaptable<number>,
clock: Animated.Clock clock: Animated.Clock
@@ -174,6 +199,30 @@ if (Animated.proc) {
}; };
} }
function transformSpringConfigToAnimatedValues(
config: SpringConfig
): AnimatedSpringConfig {
return {
damping: new Animated.Value(config.damping),
stiffness: new Animated.Value(config.stiffness),
mass: new Animated.Value(config.mass),
restDisplacementThreshold: new Animated.Value(
config.restDisplacementThreshold
),
restSpeedThreshold: new Animated.Value(config.restSpeedThreshold),
overshootClamping: new Animated.Value(config.overshootClamping),
};
}
function transformTimingConfigToAnimatedValues(
config: TimingConfig
): AnimatedTimingConfig {
return {
duration: new Animated.Value(config.duration),
easing: config.easing,
};
}
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',
@@ -202,7 +251,13 @@ export default class Card extends React.Component<Props> {
} }
if (closing !== prevProps.closing) { if (closing !== prevProps.closing) {
this.isClosing.setValue(closing ? TRUE : FALSE); // If the style updates during render, setting the value here doesn't work
// We need to defer it a bit so the animation starts properly
requestAnimationFrame(() =>
requestAnimationFrame(() =>
this.isClosing.setValue(closing ? TRUE : FALSE)
)
);
} }
} }
@@ -240,14 +295,34 @@ export default class Card extends React.Component<Props> {
height: new Value(this.props.layout.height), height: new Value(this.props.layout.height),
}; };
openingSpecConfig =
this.props.transitionSpec.open.animation === 'timing'
? transformTimingConfigToAnimatedValues(
this.props.transitionSpec.open.config
)
: transformSpringConfigToAnimatedValues(
this.props.transitionSpec.open.config
);
closingSpecConfig =
this.props.transitionSpec.close.animation === 'timing'
? transformTimingConfigToAnimatedValues(
this.props.transitionSpec.close.config
)
: transformSpringConfigToAnimatedValues(
this.props.transitionSpec.close.config
);
private distance = cond( private distance = cond(
eq(this.direction, DIRECTION_VERTICAL), eq(this.direction, DIRECTION_VERTICAL),
this.layout.height, this.layout.height,
this.layout.width this.layout.width
); );
private gestureUntraversed = new Value(0);
private gesture = new Value(0); private gesture = new Value(0);
private offset = new Value(0); private offset = new Value(0);
private velocityUntraversed = new Value(0);
private velocity = new Value(0); private velocity = new Value(0);
private gestureState = new Value(0); private gestureState = new Value(0);
@@ -267,11 +342,22 @@ export default class Card extends React.Component<Props> {
finished: new Value(FALSE), finished: new Value(FALSE),
}; };
private handleTransitionEnd = () => {
this.isRunningAnimation = false;
this.interpolatedStyle = this.getInterpolatedStyle(
this.props.styleInterpolator,
this.props.index,
this.props.current,
this.props.next,
this.props.layout
);
};
private runTransition = (isVisible: Binary | Animated.Node<number>) => { private runTransition = (isVisible: Binary | Animated.Node<number>) => {
const { open: openingSpec, close: closingSpec } = this.props.transitionSpec; const { open: openingSpec, close: closingSpec } = this.props.transitionSpec;
return cond(eq(this.props.current, isVisible), NOOP, [ return cond(eq(this.props.current, isVisible), NOOP_NODE, [
cond(clockRunning(this.clock), NOOP, [ cond(clockRunning(this.clock), NOOP_NODE, [
// Animation wasn't running before // Animation wasn't running before
// Set the initial values and start the clock // Set the initial values and start the clock
set(this.toValue, isVisible), set(this.toValue, isVisible),
@@ -280,13 +366,17 @@ export default class Card extends React.Component<Props> {
set( set(
this.transitionVelocity, this.transitionVelocity,
multiply( multiply(
cond(this.distance, divide(this.velocity, this.distance), 0), cond(
this.distance,
divide(this.velocity, this.distance),
FALSE_NODE
),
-1 -1
) )
), ),
set(this.frameTime, 0), set(this.frameTime, FALSE_NODE),
set(this.transitionState.time, 0), set(this.transitionState.time, FALSE_NODE),
set(this.transitionState.finished, FALSE), set(this.transitionState.finished, FALSE_NODE),
set(this.isVisible, isVisible), set(this.isVisible, isVisible),
startClock(this.clock), startClock(this.clock),
call([this.isVisible], ([value]: ReadonlyArray<Binary>) => { call([this.isVisible], ([value]: ReadonlyArray<Binary>) => {
@@ -297,41 +387,57 @@ export default class Card extends React.Component<Props> {
}), }),
]), ]),
cond( cond(
eq(isVisible, 1), eq(isVisible, TRUE_NODE),
openingSpec.animation === 'spring' openingSpec.animation === 'spring'
? memoizedSpring( ? memoizedSpring(
this.clock, this.clock,
{ ...this.transitionState, velocity: this.transitionVelocity }, { ...this.transitionState, velocity: this.transitionVelocity },
{ ...openingSpec.config, toValue: this.toValue } // @ts-ignore
{
...(this.openingSpecConfig as AnimatedSpringConfig),
toValue: this.toValue,
}
) )
: timing( : timing(
this.clock, this.clock,
{ ...this.transitionState, frameTime: this.frameTime }, { ...this.transitionState, frameTime: this.frameTime },
{ ...openingSpec.config, toValue: this.toValue } {
...(this.openingSpecConfig as AnimatedTimingConfig),
toValue: this.toValue,
}
), ),
closingSpec.animation === 'spring' closingSpec.animation === 'spring'
? memoizedSpring( ? memoizedSpring(
this.clock, this.clock,
{ ...this.transitionState, velocity: this.transitionVelocity }, { ...this.transitionState, velocity: this.transitionVelocity },
{ ...closingSpec.config, toValue: this.toValue } // @ts-ignore
{
...(this.closingSpecConfig as AnimatedSpringConfig),
toValue: this.toValue,
}
) )
: timing( : timing(
this.clock, this.clock,
{ ...this.transitionState, frameTime: this.frameTime }, { ...this.transitionState, frameTime: this.frameTime },
{ ...closingSpec.config, toValue: this.toValue } {
...(this.closingSpecConfig as AnimatedTimingConfig),
toValue: this.toValue,
}
) )
), ),
cond(this.transitionState.finished, [ cond(this.transitionState.finished, [
// Reset values // Reset values
set(this.isSwipeGesture, FALSE), set(this.isSwipeGesture, FALSE_NODE),
set(this.gesture, 0), set(this.gesture, FALSE_NODE),
set(this.velocity, 0), set(this.velocity, FALSE_NODE),
// When the animation finishes, stop the clock // When the animation finishes, stop the clock
stopClock(this.clock), stopClock(this.clock),
call([this.isVisible], ([value]: ReadonlyArray<Binary>) => { call([this.isVisible], ([value]: ReadonlyArray<Binary>) => {
const isOpen = Boolean(value); const isOpen = Boolean(value);
const { onOpen, onClose } = this.props; const { onOpen, onClose } = this.props;
this.isRunningAnimation = false;
this.handleTransitionEnd();
if (isOpen) { if (isOpen) {
onOpen(true); onOpen(true);
} else { } else {
@@ -347,34 +453,58 @@ export default class Card extends React.Component<Props> {
multiply(this.velocity, SWIPE_VELOCITY_IMPACT) multiply(this.velocity, SWIPE_VELOCITY_IMPACT)
); );
private exec = block([ private exec = [
set(
this.gesture,
multiply(
this.gestureUntraversed,
I18nManager.isRTL ? MINUS_ONE_NODE : TRUE_NODE
)
),
set(
this.velocity,
multiply(
this.velocityUntraversed,
I18nManager.isRTL ? MINUS_ONE_NODE : TRUE_NODE
)
),
onChange( onChange(
this.isClosing, this.isClosing,
cond(this.isClosing, set(this.nextIsVisible, FALSE)) cond(this.isClosing, set(this.nextIsVisible, FALSE_NODE))
), ),
onChange( onChange(
this.nextIsVisible, this.nextIsVisible,
cond(neq(this.nextIsVisible, UNSET), [ cond(neq(this.nextIsVisible, UNSET_NODE), [
// Stop any running animations // Stop any running animations
cond(clockRunning(this.clock), [ cond(clockRunning(this.clock), [
call([], () => (this.isRunningAnimation = false)), call([], this.handleTransitionEnd),
stopClock(this.clock), stopClock(this.clock),
]), ]),
set(this.gesture, 0), set(this.gesture, FALSE_NODE),
// Update the index to trigger the transition // Update the index to trigger the transition
set(this.isVisible, this.nextIsVisible), set(this.isVisible, this.nextIsVisible),
set(this.nextIsVisible, UNSET), set(this.nextIsVisible, UNSET_NODE),
]) ])
), ),
];
private changeVisiblityExec = onChange(
this.isVisible,
call([this.isVisible], ([isVisible]) => (this.isVisibleValue = isVisible))
);
private execNoGesture = block([
...this.exec,
this.runTransition(this.isVisible),
onChange( onChange(
this.isVisible, this.isVisible,
call([this.isVisible], ([isVisible]) => (this.isVisibleValue = isVisible)) call([this.isVisible], ([isVisible]) => (this.isVisibleValue = isVisible))
), ),
this.changeVisiblityExec,
]); ]);
private execNoGesture = this.runTransition(this.isVisible);
private execWithGesture = block([ private execWithGesture = block([
...this.exec,
onChange( onChange(
this.isSwiping, this.isSwiping,
call( call(
@@ -401,11 +531,11 @@ export default class Card extends React.Component<Props> {
cond( cond(
eq(this.gestureState, GestureState.ACTIVE), eq(this.gestureState, GestureState.ACTIVE),
[ [
cond(this.isSwiping, NOOP, [ cond(this.isSwiping, NOOP_NODE, [
// We weren't dragging before, set it to true // We weren't dragging before, set it to true
set(this.isSwipeCancelled, FALSE), set(this.isSwipeCancelled, FALSE_NODE),
set(this.isSwiping, TRUE), set(this.isSwiping, TRUE_NODE),
set(this.isSwipeGesture, TRUE), set(this.isSwipeGesture, TRUE_NODE),
// Also update the drag offset to the last position // Also update the drag offset to the last position
set(this.offset, this.props.current), set(this.offset, this.props.current),
]), ]),
@@ -416,11 +546,15 @@ export default class Card extends React.Component<Props> {
max( max(
sub( sub(
this.offset, this.offset,
cond(this.distance, divide(this.gesture, this.distance), 1) cond(
this.distance,
divide(this.gesture, this.distance),
TRUE_NODE
)
), ),
0 FALSE_NODE
), ),
1 TRUE_NODE
) )
), ),
// Stop animations while we're dragging // Stop animations while we're dragging
@@ -443,7 +577,7 @@ export default class Card extends React.Component<Props> {
this.isSwipeCancelled, this.isSwipeCancelled,
eq(this.gestureState, GestureState.CANCELLED) eq(this.gestureState, GestureState.CANCELLED)
), ),
set(this.isSwiping, FALSE), set(this.isSwiping, FALSE_NODE),
this.runTransition( this.runTransition(
cond( cond(
greaterThan( greaterThan(
@@ -452,26 +586,29 @@ export default class Card extends React.Component<Props> {
), ),
cond( cond(
lessThan( lessThan(
cond(eq(this.velocity, 0), this.gesture, this.velocity), cond(
0 eq(this.velocity, FALSE_NODE),
this.gesture,
this.velocity
), ),
TRUE, FALSE_NODE
FALSE ),
TRUE_NODE,
FALSE_NODE
), ),
this.isVisible this.isVisible
) )
), ),
] ]
), ),
this.changeVisiblityExec,
]); ]);
private handleGestureEventHorizontal = Animated.event([ private handleGestureEventHorizontal = Animated.event([
{ {
nativeEvent: { nativeEvent: {
translationX: (x: Animated.Adaptable<number>) => translationX: this.gestureUntraversed,
set(this.gesture, multiply(x, I18nManager.isRTL ? -1 : 1)), velocityX: this.velocityUntraversed,
velocityX: (x: Animated.Adaptable<number>) =>
set(this.velocity, multiply(x, I18nManager.isRTL ? -1 : 1)),
state: this.gestureState, state: this.gestureState,
}, },
}, },
@@ -500,10 +637,8 @@ export default class Card extends React.Component<Props> {
) => ) =>
styleInterpolator({ styleInterpolator({
index, index,
progress: { current: { progress: current },
current, next: next && { progress: next },
next,
},
closing: this.isClosing, closing: this.isClosing,
layouts: { layouts: {
screen: layout, screen: layout,
@@ -511,6 +646,18 @@ export default class Card extends React.Component<Props> {
}) })
); );
// Keep track of the style in a property to avoid changing the animated node when deps change
// The style shouldn't change in the middle of the animation and should refer to what was there at the start of it
// Which will be the last value when just before the render which started the animation
// We need to make sure to update this when the running animation ends
private interpolatedStyle = this.getInterpolatedStyle(
this.props.styleInterpolator,
this.props.index,
this.props.current,
this.props.next,
this.props.layout
);
private gestureActivationCriteria() { private gestureActivationCriteria() {
const { layout, gestureDirection, gestureResponseDistance } = this.props; const { layout, gestureDirection, gestureResponseDistance } = this.props;
@@ -551,35 +698,39 @@ export default class Card extends React.Component<Props> {
render() { render() {
const { const {
index,
active, active,
transparent, transparent,
layout, styleInterpolator,
index,
current, current,
next, next,
layout,
overlayEnabled, overlayEnabled,
shadowEnabled, shadowEnabled,
gestureEnabled, gestureEnabled,
gestureDirection, gestureDirection,
children, children,
styleInterpolator,
containerStyle: customContainerStyle, containerStyle: customContainerStyle,
contentStyle, contentStyle,
...rest ...rest
} = this.props; } = this.props;
const { if (!this.isRunningAnimation) {
containerStyle, this.interpolatedStyle = this.getInterpolatedStyle(
cardStyle,
overlayStyle,
shadowStyle,
} = this.getInterpolatedStyle(
styleInterpolator, styleInterpolator,
index, index,
current, current,
next, next,
layout layout
); );
}
const {
containerStyle,
cardStyle,
overlayStyle,
shadowStyle,
} = this.interpolatedStyle;
const handleGestureEvent = gestureEnabled const handleGestureEvent = gestureEnabled
? gestureDirection === 'vertical' ? gestureDirection === 'vertical'
@@ -590,8 +741,8 @@ export default class Card extends React.Component<Props> {
return ( return (
<StackGestureContext.Provider value={this.gestureRef}> <StackGestureContext.Provider value={this.gestureRef}>
<View pointerEvents="box-none" {...rest}> <View pointerEvents="box-none" {...rest}>
<Animated.Code exec={this.exec} />
<Animated.Code <Animated.Code
key={gestureEnabled ? 'gesture-code' : 'no-gesture-code'}
exec={gestureEnabled ? this.execWithGesture : this.execNoGesture} exec={gestureEnabled ? this.execWithGesture : this.execNoGesture}
/> />
{overlayEnabled && overlayStyle ? ( {overlayEnabled && overlayStyle ? (

View File

@@ -167,11 +167,14 @@ export default class Stack extends React.Component<Props, State> {
: undefined; : undefined;
const next = nextRoute ? progress[nextRoute.key] : undefined; const next = nextRoute ? progress[nextRoute.key] : undefined;
const oldScene = state.scenes[index];
const scene = { const scene = {
route, route,
previous: previousRoute, previous: previousRoute,
descriptor: descriptor:
props.descriptors[route.key] || state.descriptors[route.key], props.descriptors[route.key] ||
state.descriptors[route.key] ||
(oldScene ? oldScene.descriptor : { options: {} }),
progress: { progress: {
current, current,
next, next,
@@ -179,8 +182,6 @@ export default class Stack extends React.Component<Props, State> {
}, },
}; };
const oldScene = state.scenes[index];
if ( if (
oldScene && oldScene &&
scene.route === oldScene.route && scene.route === oldScene.route &&

View File

@@ -52,6 +52,7 @@ export default class TouchableItem extends React.Component<Props> {
return ( return (
<TouchableNativeFeedback <TouchableNativeFeedback
{...rest} {...rest}
useForeground={TouchableNativeFeedback.canUseNativeForeground()}
background={TouchableNativeFeedback.Ripple(pressColor, borderless)} background={TouchableNativeFeedback.Ripple(pressColor, borderless)}
> >
<View style={style}>{React.Children.only(children)}</View> <View style={style}>{React.Children.only(children)}</View>