48 lines
1.6 KiB
TypeScript
48 lines
1.6 KiB
TypeScript
import { createNavigationContainerRef, StackActions } from "@react-navigation/native";
|
|
|
|
export const rootNavigationRef = createNavigationContainerRef<any>();
|
|
|
|
/** positions タブの Stack.Navigator navigation を登録するグローバルref */
|
|
export const positionsStackNavRef: { current: any } = { current: null };
|
|
|
|
/**
|
|
* 遷移先タブのネストスタックを一度 popToTop してからナビゲートする。
|
|
* ウィジェットや外部リンクからの遷移時に、既存の開いている画面を閉じてから目的の画面へ移動するために使用する。
|
|
*/
|
|
export function stackAwareNavigate(tabName: string, params?: any) {
|
|
if (!rootNavigationRef.isReady()) return;
|
|
|
|
const doNavigate = () => {
|
|
if (params !== undefined) {
|
|
rootNavigationRef.navigate(tabName, params);
|
|
} else {
|
|
rootNavigationRef.navigate(tabName as any);
|
|
}
|
|
};
|
|
|
|
// positions タブは直接 stackNavRef を使って確実に popToTop する
|
|
if (tabName === "positions" && positionsStackNavRef.current) {
|
|
const stackNav = positionsStackNavRef.current;
|
|
if ((stackNav.getState()?.index ?? 0) > 0) {
|
|
stackNav.popToTop();
|
|
setTimeout(doNavigate, 350);
|
|
} else {
|
|
doNavigate();
|
|
}
|
|
return;
|
|
}
|
|
|
|
const state = rootNavigationRef.getState();
|
|
const tabRoute = state?.routes?.find((r: any) => r.name === tabName);
|
|
if (tabRoute?.state && (tabRoute.state.index ?? 0) > 0) {
|
|
rootNavigationRef.dispatch({
|
|
...StackActions.popToTop(),
|
|
target: tabRoute.state.key,
|
|
});
|
|
// popToTop のアニメーション完了後に navigate を実行
|
|
setTimeout(doNavigate, 350);
|
|
} else {
|
|
doNavigate();
|
|
}
|
|
}
|