Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flow state in navigation state #16

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions packages/example/src/FlowNavigatorExample.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,23 @@ export const FlowNavigatorExample = () => {
);
}

const initialDisabledRoutes = [
'Step31',
...(hasToPassStep4 ? [] : ['Step4']),
];
const initialFormState = {
myValue31: false,
myValue4: hasToPassStep4,
};

type FormState = typeof initialFormState;

const config = {
Step31: (formState: FormState) => formState.myValue31,
Step4: (formState: FormState) => formState.myValue4,
};

return (
<FlowNavigator.Navigator
screenOptions={{headerShown: false}}
initialDisabledRoutes={initialDisabledRoutes}>
config={config}
initialFormState={initialFormState}>
<FlowNavigator.Screen name="Step1" component={Step1Page} />
<FlowNavigator.Screen name="Step2" component={Step2Navigator} />
<FlowNavigator.Group>
Expand Down
6 changes: 4 additions & 2 deletions packages/example/src/steps/Step2/Step2-2Page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import {FlowInfos} from '../FlowInfos';
import {FlowStackParamList} from '../../FlowNavigatorExample';

export const Step22Page = () => {
const {goBack, goToNextStep, enableRoute} =
const {goBack, goToNextStep, setStoreState} =
useNavigation<FlowNavigationProp<FlowStackParamList>>();

const onNextPress = async () => {
enableRoute('Step31');
setStoreState({
myValue31: true,
});
goToNextStep();
};

Expand Down
3 changes: 1 addition & 2 deletions packages/example/src/steps/Step3/Step3-2Page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import {FlowInfos} from '../FlowInfos';
import {ParamListBase, useNavigation} from '@react-navigation/native';

export const Step32Page = () => {
const {goToPreviousStep, goToNextStep, disableRoute} =
const {goToPreviousStep, goToNextStep} =
useNavigation<FlowNavigationProp<ParamListBase>>();

const onNextPress = () => {
goToNextStep();
disableRoute('Step32');
};

return (
Expand Down
12 changes: 6 additions & 6 deletions packages/example/src/steps/Step4/Step4Page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@ import {FlowNavigationProp} from '@bam.tech/flow-navigator';
import {Button, StyleSheet, Text, View} from 'react-native';
import {FlowInfos} from '../FlowInfos';
import {ParamListBase, useNavigation} from '@react-navigation/native';
import {useQueryClient, useMutation} from '@tanstack/react-query';
import {useMutation} from '@tanstack/react-query';
import {postPassedStep4} from '../../queries/hasToPassStep4';

export const Step4Page = () => {
const {goToPreviousStep, goToNextStep, disableRoute} =
const {goToPreviousStep, goToNextStep, setStoreState} =
useNavigation<FlowNavigationProp<ParamListBase>>();

const queryClient = useQueryClient();
const {mutate: setHasToPassStep2ToOff} = useMutation(
['postHasToPassStep4'],
postPassedStep4,
{
onSuccess: () => {
queryClient.invalidateQueries(['hasToPassStep4']);
onSuccess: value => {
goToNextStep();
disableRoute('Step4');
setStoreState({
Copy link
Contributor Author

@charlotteisambert charlotteisambert Jan 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remarque : Cette api requiert un peu de synchro à la mano

On retrouve le même problème qu'avec xstate et react-navigation, de devoir synchroniser des données. Ca me semble pas dramatique, même la première api avait ce type de synchro, c'était un state au lieu d'être ce helper simplement

myValue4: value,
});
},
},
);
Expand Down
10 changes: 7 additions & 3 deletions packages/lib/src/navigators/createFlowNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import {
useNavigation,
useNavigationBuilder,
} from "@react-navigation/native";
import { NativeStackNavigationEventMap, NativeStackView } from "@react-navigation/native-stack";
import {
NativeStackNavigationEventMap,
NativeStackView,
} from "@react-navigation/native-stack";
import {
FlowActionHelpers,
FlowRouterOptions,
Expand All @@ -26,7 +29,8 @@ function FlowNavigator({
children,
screenListeners,
screenOptions,
initialDisabledRoutes,
config,
initialFormState,
...rest
}: FlowNavigatorProps) {
const parentNavigation = useNavigation();
Expand All @@ -42,7 +46,7 @@ function FlowNavigator({
FlowActionHelpers<ParamListBase>,
FlowNavigationOptions,
FlowNavigationEventMap
>(buildFlowRouter(quitFlow, initialDisabledRoutes), {
>(buildFlowRouter(quitFlow, { config, initialFormState }), {
id,
initialRouteName,
children,
Expand Down
100 changes: 56 additions & 44 deletions packages/lib/src/routers/FlowRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,15 @@ import {
StackRouter,
StackRouterOptions,
} from "@react-navigation/native";
import { FlowNavigationState } from "../types/types";
import { Config, FlowNavigationState, FormState } from "../types/types";

export type FlowRouterOptions = StackRouterOptions;

export type FlowActionHelpers<ParamList extends ParamListBase> = {
goToNextStep(): void;
goToPreviousStep(): void;
quitFlow(): void;
enableRoute(routeName: Extract<keyof ParamList, string>): void;
disableRoute(routeName: Extract<keyof ParamList, string>): void;
setStoreState(formState: FormState): void;
} & StackActionHelpers<ParamList>;

export type FlowActionType =
Expand All @@ -34,19 +33,19 @@ export type FlowActionType =
source?: string;
}
| {
type: "ENABLE_ROUTE";
type: "SET_STORE_STATE";
source?: string;
payload: { routeName: Extract<keyof ParamListBase, string> };
}
| {
type: "DISABLE_ROUTE";
source?: string;
payload: { routeName: Extract<keyof ParamListBase, string> };
payload: { formState: Object };
};


export const buildFlowRouter =
(quitFlowHelper: () => void, initialDisabledRoutes: string[]) =>
(
quitFlowHelper: () => void,
{
config,
initialFormState,
}: { config: Config<ParamListBase>; initialFormState: FormState }
) =>
(
options: FlowRouterOptions
): Router<
Expand All @@ -63,14 +62,24 @@ export const buildFlowRouter =

getInitialState(params) {
const { routeNames } = params;

const disabledRouteNames = Object.entries(config)
.filter(([_, isRouteNameEnabledCb]) => {
return !isRouteNameEnabledCb(initialFormState);
})
.map(([routeName]) => routeName);

const availableRoutes = routeNames.filter(
(routeName) =>
!initialDisabledRoutes.find((disabledRoute) => disabledRoute === routeName)
!disabledRouteNames.find(
(disabledRoute) => disabledRoute === routeName
)
);

return {
...router.getInitialState(params),
availableRoutes,
formState: initialFormState,
};
},

Expand Down Expand Up @@ -120,40 +129,46 @@ export const buildFlowRouter =

return state;

case "ENABLE_ROUTE":
const notOrdonnedAvailableRoutes = [
...state.availableRoutes,
action.payload.routeName,
];
case "SET_STORE_STATE":
const newFormState = {
...state.formState,
...action.payload.formState,
};

const newAvailableRoutes = state.routeNames.filter((routeName: string) =>
notOrdonnedAvailableRoutes.find(
(newAvailableRoute) => routeName === newAvailableRoute
)
const disabledRouteNames = Object.entries(config)
.filter(([_, isRouteNameEnabledCb]) => {
return !isRouteNameEnabledCb(newFormState);
})
.map(([routeName]) => routeName);

const availableRoutes = state.routeNames.filter(
(routeName) =>
!disabledRouteNames.find(
(disabledRoute) => disabledRoute === routeName
)
);

return {
...state,
availableRoutes: newAvailableRoutes,
};

case "DISABLE_ROUTE":
// TODO: maybe use getStateForRouteNamesChange
const currentRouteName = state.routes[state.routes.length - 1];
const builtRemovedRoute = disabledRouteNames.filter(
(disabledRoute) =>
state.routes.some((route) => route.name === disabledRoute)
);

const filteredRoutes = state.routes.filter(
(route) => route.name !== action.payload.routeName
const newRoutes = state.routes.filter(
(route) =>
!builtRemovedRoute.some(
(builtRemovedRoute) => builtRemovedRoute === route.name
)
);

return {
...state,
availableRoutes: state.availableRoutes.filter(
(routeName: string) => routeName !== action.payload.routeName
),
routes: filteredRoutes,
index: filteredRoutes.findIndex(
(routeName) => routeName === currentRouteName
),
formState: {
...state.formState,
...action.payload.formState,
},
index: state.index - builtRemovedRoute.length,
availableRoutes,
routes: newRoutes,
};

default:
Expand All @@ -171,11 +186,8 @@ export const buildFlowRouter =
quitFlow: () => {
return { type: "QUIT_FLOW" };
},
enableRoute: (routeName) => {
return { type: "ENABLE_ROUTE", payload: {routeName} };
},
disableRoute: (routeName) => {
return { type: "DISABLE_ROUTE", payload: {routeName} };
setStoreState: (formState) => {
return { type: "SET_STORE_STATE", payload: { formState } };
},
},
};
Expand Down
10 changes: 9 additions & 1 deletion packages/lib/src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,16 @@ export type FlowNavigationProp<
export type FlowNavigationState<ParamList extends ParamListBase> =
NavigationState<ParamList> & {
availableRoutes: Extract<keyof ParamList, string>[];
formState: FormState;
// type: "flow"; : TODO add flow type and key
};

export type Config<ParamList = ParamListBase> = {
[k in Partial<keyof ParamList>]: (formState: FormState) => boolean;
};

export type FormState = Object;

export type FlowNavigatorProps = DefaultNavigatorOptions<
ParamListBase,
FlowNavigationState<ParamListBase>,
Expand All @@ -55,7 +62,8 @@ export type FlowNavigatorProps = DefaultNavigatorOptions<
> &
StackRouterOptions &
NativeStackNavigationConfig & {
initialDisabledRoutes: Extract<keyof ParamListBase, string>[];
config: Config<ParamListBase>;
initialFormState: FormState;
};

export type FlowStackNavigationOptions = NativeStackNavigationOptions & {
Expand Down