Files
harukin-expo-dev-env 19b280a467 feat: implement startup icon font preloading and improve loading checks in AppContainer
refactor: simplify CarouselTypeChanger by removing redundant onPressIn handlers
fix: enhance MenuLED memoization for better performance
refactor: optimize EachData component with useMemo for derived values
fix: improve error handling in TrainPosition data fetching
refactor: streamline AddressText component's API call with abort controller
refactor: update Menu component to manage selected station state more effectively
2026-09-13 15:09:37 +09:00

441 lines
15 KiB
TypeScript

import React, { useRef, useState, useEffect, useCallback, useMemo, FC } from "react";
import { Platform, View, ScrollView, LayoutAnimation, InteractionManager, StatusBar, useWindowDimensions } from "react-native";
import Constants from "expo-constants";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
configureReanimatedLogger,
ReanimatedLogLevel,
} from "react-native-reanimated";
import { useThemeColors } from "@/lib/theme";
import { useResponsive } from "@/lib/responsive";
import { MenuLED } from "@/components/Menu/MenuLED";
import { TitleBar } from "@/components/Menu/TitleBar";
import { FixedContentBottom } from "@/components/Menu/FixedContentBottom";
import { MenuMap } from "@/components/Menu/MenuMap";
import { lineList, stationIDPair } from "@/lib/getStationList";
import { useFavoriteStation } from "@/stateBox/useFavoriteStation";
import { useNavigation, useIsFocused } from "@react-navigation/native";
import { useStationList } from "@/stateBox/useStationList";
import { TopMenuButton } from "@/components/Menu/TopMenuButton";
import { JRSTraInfoBox } from "@/components/Menu/JRSTraInfoBox";
import { CarouselBox } from "@/components/Menu/Carousel/CarouselBox";
import { CarouselTypeChanger } from "@/components/Menu/Carousel/CarouselTypeChanger";
import { StationListLoadingState } from "@/components/Menu/Carousel/StationListLoadingState";
import { useUserPosition } from "@/stateBox/useUserPosition";
import { AS } from "@/storageControl";
import { STORAGE_KEYS } from "@/constants";
import { lineList_LineWebID } from "@/lib/getStationList";
import { StationProps } from "@/lib/CommonTypes";
import { StationSource } from "@/types";
import { telemetry } from "@/lib/observability/telemetry";
import { getMenuStationGroups, getNearbyStationGroups } from "@/lib/menuStationSelectors";
import { getFavoriteStationKey } from "@/lib/favoriteStationUtils";
const MemoizedCarouselBox = React.memo(CarouselBox);
const MemoizedTopMenuButton = React.memo(TopMenuButton);
const MemoizedJRSTraInfoBox = React.memo(JRSTraInfoBox);
const MemoizedFixedContentBottom = React.memo(FixedContentBottom);
const topMenuRuntimeTelemetry = telemetry.scope("topMenu.runtime");
const getMenuStationKey = (stationGroup: StationProps[] | undefined) =>
getFavoriteStationKey(stationGroup);
configureReanimatedLogger({
level: ReanimatedLogLevel.error, // Set the log level to error
strict: true, // Reanimated runs in strict mode by default
});
type props = {
scrollRef: React.RefObject<ScrollView>;
mapHeight: number;
MapFullHeight: number;
mapMode: boolean;
setMapMode: React.Dispatch<React.SetStateAction<boolean>>;
};
export const Menu: FC<props> = (props) => {
const { scrollRef, mapHeight, MapFullHeight, mapMode, setMapMode } = props;
const { navigate } = useNavigation();
const { colors, isDark } = useThemeColors();
const isMenuFocused = useIsFocused();
const { width } = useWindowDimensions();
const { verticalScale } = useResponsive();
const mapScrollOffset = verticalScale(80);
const mapPaddingBottom = verticalScale(120);
const insets = useSafeAreaInsets();
const { favoriteStation, isFavoriteStationReady } = useFavoriteStation();
const { originalStationList, getStationDataFromNameBase } = useStationList();
const [stationSource, _setStationSource] = useState<StationSource>({ type: "position" });
const [isHeavyContentReady, setIsHeavyContentReady] = useState(Platform.OS !== "android");
// 時刻表βの遅延レンダリング(画面遷移アニメーション完了後に描画)
const [ledReady, setLedReady] = useState(Platform.OS !== "android");
useEffect(() => {
if (Platform.OS !== "android") {
setIsHeavyContentReady(true);
setLedReady(true);
return;
}
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
if (!isMenuFocused) {
if (!isHeavyContentReady) return;
topMenuRuntimeTelemetry.breadcrumb({
message: "top menu heavy content preserved on blur",
data: { mapMode },
});
return () => {
cancelled = true;
};
}
if (isHeavyContentReady && ledReady) {
return () => {
cancelled = true;
};
}
topMenuRuntimeTelemetry.breadcrumb({
message: "top menu heavy content activation scheduled",
data: { mapMode },
});
const handle = InteractionManager.runAfterInteractions(() => {
timer = setTimeout(() => {
if (cancelled) return;
topMenuRuntimeTelemetry.breadcrumb({
message: "top menu heavy content activated",
data: { mapMode },
});
setIsHeavyContentReady(true);
setLedReady(true);
}, 60);
});
return () => {
cancelled = true;
handle.cancel();
if (timer) clearTimeout(timer);
};
}, [isHeavyContentReady, isMenuFocused, ledReady, mapMode]);
useEffect(() => {
telemetry.context("top_menu_runtime", {
focused: isMenuFocused,
mapMode,
heavyContentReady: isHeavyContentReady,
ledReady,
});
}, [isHeavyContentReady, isMenuFocused, ledReady, mapMode]);
// 検索モードを閉じたときに戻るソースを記憶
const prevNonSearchTypeRef = useRef<"position" | "favorite">("position");
const hasUserChangedStationSourceRef = useRef(false);
// stationSource を更新するラッパー(position/favorite に切り替えた際に戻り先を記録)
const setStationSource = useCallback((source: StationSource) => {
hasUserChangedStationSourceRef.current = true;
if (source.type !== "search") prevNonSearchTypeRef.current = source.type;
_setStationSource(source);
}, []);
// 検索モードを閉じて直前の position/favorite に戻る
const closeSearch = useCallback(() => {
setStationSource({ type: prevNonSearchTypeRef.current });
}, [setStationSource]);
useEffect(() => {
let cancelled = false;
AS.getItem(STORAGE_KEYS.STATION_LIST_MODE)
.then((res) => {
// 起動直後にユーザーが操作した場合、古い保存値で選択を巻き戻さない。
if (cancelled || hasUserChangedStationSourceRef.current) return;
if (res === "position" || res === "favorite") {
_setStationSource({ type: res });
}
})
.catch(() => {});
return () => {
cancelled = true;
};
}, []);
const returnToTop = useCallback(
(bool = true) => {
scrollRef?.current.scrollTo({
y: mapHeight > mapScrollOffset ? mapHeight - mapScrollOffset : 0,
animated: bool,
});
},
[mapHeight, mapScrollOffset, scrollRef],
);
const goToMap = useCallback(() => {
scrollRef?.current.scrollTo({
y: 0,
animated: true,
});
}, [scrollRef]);
useEffect(() => {
setTimeout(() => {
returnToTop(false);
}, 10);
}, [mapHeight]);
const [scrollStartPosition, setScrollStartPosition] = useState(0);
const onScrollBeginDrag = (e) => {
LayoutAnimation.configureNext({
duration: 300,
create: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
});
setScrollStartPosition(e.nativeEvent.contentOffset.y);
setMapMode(false);
};
//現在地基準の駅名標リストアップ機能
const { position, locationStatus } = useUserPosition();
const isPositionLoading =
Platform.OS !== "web" &&
(locationStatus === null || (locationStatus === true && !position));
const [nearPositionStation, setNearPositionStation] = useState<
StationProps[][]
>([]); //第三要素
useEffect(() => {
if (!position || !originalStationList) return;
setNearPositionStation(
getNearbyStationGroups({
coordinates: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
},
originalStationList,
lineNames: lineList,
}),
);
}, [position, originalStationList]);
const [listIndex, setListIndex] = useState(0);
const stationSourceTypeRef = useRef(stationSource.type);
const openStationSearch = useCallback(() => {
setMapMode(false);
goToMap();
setStationSource({ type: "search", query: "", lineId: undefined });
}, [goToMap, setMapMode, setStationSource]);
// listUpStation を useMemo で派生(useLayoutEffect + setState を排除)
// stationSource が変わるたびに再計算。input も query として統合済みなので
// テキスト入力のたびに正しくリストが更新される(旧来のバグを修正)。
const listUpStation = useMemo<StationProps[][]>(
() =>
getMenuStationGroups({
stationSource,
originalStationList,
nearbyPositionStations: nearPositionStation,
favoriteStations: favoriteStation,
findStationsByName: getStationDataFromNameBase,
lineWebIds: lineList_LineWebID,
stationIds: stationIDPair,
}),
[
stationSource,
nearPositionStation,
favoriteStation,
originalStationList,
getStationDataFromNameBase,
],
);
const [selectedStationKey, setSelectedStationKey] = useState<string | undefined>();
const isStationSourceChanging =
stationSourceTypeRef.current !== stationSource.type;
const activeListIndex = useMemo(() => {
if (listIndex < 0) return listIndex;
if (isStationSourceChanging) return 0;
if (selectedStationKey) {
const selectedIndex = listUpStation.findIndex(
(stationGroup) => getMenuStationKey(stationGroup) === selectedStationKey,
);
if (selectedIndex >= 0) return selectedIndex;
}
if (listUpStation.length === 0) return 0;
return Math.min(Math.max(listIndex, 0), listUpStation.length - 1);
}, [isStationSourceChanging, listIndex, listUpStation, selectedStationKey]);
const setSelectedStation = useCallback(
(index: number) => {
setListIndex(index);
if (index < 0) return; // ソートモード中は選択駅を保持する
setSelectedStationKey(getMenuStationKey(listUpStation[index]));
},
[listUpStation],
);
// 一覧が再生成されても、駅の順番ではなく選択駅を優先して位置を復元する。
useEffect(() => {
const sourceChanged = stationSourceTypeRef.current !== stationSource.type;
stationSourceTypeRef.current = stationSource.type;
if (sourceChanged) {
setListIndex(0);
setSelectedStationKey(getMenuStationKey(listUpStation[0]));
return;
}
if (listIndex < 0) return; // ソートモード中(未選択状態)は無視
if (listUpStation.length === 0) {
setListIndex(0);
setSelectedStationKey(undefined);
return;
}
if (selectedStationKey) {
const selectedIndex = listUpStation.findIndex(
(stationGroup) => getMenuStationKey(stationGroup) === selectedStationKey,
);
if (selectedIndex >= 0) {
if (selectedIndex !== listIndex) setListIndex(selectedIndex);
return;
}
}
const nextIndex = Math.min(Math.max(listIndex, 0), listUpStation.length - 1);
if (nextIndex !== listIndex) {
setMapMode(false);
setListIndex(nextIndex);
}
setSelectedStationKey(getMenuStationKey(listUpStation[nextIndex]));
}, [listIndex, listUpStation, selectedStationKey, setMapMode, stationSource.type]);
return (
<View
style={{
height: "100%",
backgroundColor: colors.background,
paddingTop: Platform.OS === "web" ? 0 : insets.top,
}}
>
{isMenuFocused && (
<StatusBar
barStyle={isDark ? "light-content" : "dark-content"}
translucent
/>
)}
{!mapMode ? <TitleBar /> : <></>}
<ScrollView
ref={scrollRef}
snapToStart={false}
snapToEnd={false}
decelerationRate={"normal"}
snapToOffsets={[mapHeight - mapScrollOffset]}
onScrollBeginDrag={onScrollBeginDrag}
onScrollEndDrag={(e) => {
if (e.nativeEvent.contentOffset.y < mapHeight - mapScrollOffset) {
if (scrollStartPosition > e.nativeEvent.contentOffset.y) {
goToMap();
} else {
returnToTop();
}
}
}}
>
<MenuMap
mapHeight={mapHeight}
mapFullHeight={MapFullHeight}
mapMode={mapMode}
backgroundColor={colors.background}
isDark={isDark}
isHeavyContentReady={isHeavyContentReady}
listIndex={activeListIndex}
listUpStation={listUpStation}
position={position}
mapPaddingTop={mapScrollOffset}
mapPaddingBottom={mapPaddingBottom}
setMapMode={setMapMode}
setListIndex={setSelectedStation}
onGoToMap={goToMap}
onReturnToTop={returnToTop}
/>
{!mapMode && (
<CarouselTypeChanger
{...{
locationStatus,
position,
stationSource,
setStationSource,
closeSearch,
setSelectedCurrentStation: setSelectedStation,
mapMode,
setMapMode,
}}
/>
)}
{stationSource.type === "favorite" && !isFavoriteStationReady ? (
<View
style={{
width: "100%",
paddingTop: 10,
alignItems: "center",
}}
>
<StationListLoadingState
width={width}
message="お気に入りを読み込み中…"
/>
</View>
) : (
Object.keys(originalStationList).length !== 0 &&
isHeavyContentReady && (
<>
<MemoizedCarouselBox
{...{
originalStationList,
onOpenSearch: openStationSearch,
listUpStation,
nearPositionStation,
setListIndex: setSelectedStation,
listIndex: activeListIndex,
navigate,
isFavoriteLoading: !isFavoriteStationReady,
isPositionLoading,
stationSource,
}}
/>
{listUpStation[activeListIndex] && ledReady && (
<MenuLED station={listUpStation[activeListIndex]} />
)}
</>
)
)}
<MemoizedTopMenuButton />
<MemoizedJRSTraInfoBox />
<MemoizedFixedContentBottom navigate={navigate} />
</ScrollView>
{mapMode && (
<CarouselTypeChanger
{...{
locationStatus,
position,
stationSource,
setStationSource,
closeSearch,
setSelectedCurrentStation: setSelectedStation,
mapMode,
setMapMode,
}}
/>
)}
</View>
);
};