feat: 앱을 날씨각 웹(weather.o2o.kr)을 띄우는 웹뷰 셸로 전환 (안드로이드) — 전체 화면 웹뷰·뒤로 가기·실패 화면, 구글 로그인·위치·공유 브리지, 앱 링크(assetlinks·인텐트 필터)·nalssigak:// 링크 열기, 안전 영역은 웹이 처리하도록 패딩 없음. 푸시·iOS 는 제외, expo-file-system 추가
This commit is contained in:
1 parent
2a94ebe85b
commit
a228fcf560
8 files changed
+288
-46
No files matched your search
@@ -0,0 +1,135 @@
|
||||
import Constants from 'expo-constants';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ActivityIndicator, BackHandler, Linking, Pressable, View } from 'react-native';
|
||||
import { WebView, type WebViewMessageEvent, type WebViewNavigation } from 'react-native-webview';
|
||||
|
||||
import { Text } from '@/components/text';
|
||||
import { SITE_URL } from '@/lib/site';
|
||||
import { handleRequest, parseRequest, replyScript } from '@/lib/web-bridge';
|
||||
|
||||
const SITE_ORIGIN = new URL(SITE_URL).origin;
|
||||
|
||||
/** 웹 첫 화면(하늘색)과 맞춰, 웹이 뜨기 전에 흰 화면이 비치지 않게 한다 */
|
||||
const BG = '#d6ebff';
|
||||
|
||||
/** 웹이 앱 안인지 알아보는 표시. 웹뷰 기본 user agent 뒤에 붙는다 (예: NalssigakApp/1.1.0) */
|
||||
const APP_UA = `NalssigakApp/${Constants.expoConfig?.version ?? '0'}`;
|
||||
|
||||
/** 앱 링크(https://weather.o2o.kr/…)와 앱 주소(nalssigak://today/…)를 사이트 주소로 바꾼다. 날씨각 주소가 아니면 null */
|
||||
function toSiteUrl(link: string): string | null {
|
||||
const scheme = /^nalssigak:\/\/(.*)$/.exec(link);
|
||||
const url = scheme ? `${SITE_URL}/${scheme[1]}` : link;
|
||||
try {
|
||||
return new URL(url).origin === SITE_ORIGIN ? url : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function LoadFailed({ onRetry }: { onRetry: () => void }) {
|
||||
return (
|
||||
<View className="absolute inset-0 items-center justify-center px-6" style={{ backgroundColor: BG }}>
|
||||
<Text className="text-center text-[15px] font-bold text-ink2">날씨를 불러오지 못했어요. 인터넷 연결을 확인하고 다시 시도해 주세요.</Text>
|
||||
<Pressable onPress={onRetry} accessibilityRole="button" className="mt-5 rounded-full bg-white px-6 py-3">
|
||||
<Text className="text-[15px] font-extrabold text-[#28304a]">다시 불러오기</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 날씨각 웹(weather.o2o.kr)을 전체 화면으로 띄우는 앱 껍데기.
|
||||
* 화면은 모두 웹이 그리고, 앱은 뒤로 가기·불러오기 실패 화면만 맡는다.
|
||||
* 웹뷰는 상태바·내비게이션 바 아래까지 꽉 채운다: 웹이 env(safe-area-inset-*)로 위아래 여백을 직접 두므로 앱이 또 패딩을 주면 이중 여백이 생긴다.
|
||||
* 날씨각 사이트 밖 주소(tel:, mailto:, 다른 사이트)는 웹뷰 라이브러리가 휴대폰 앱·브라우저로 넘긴다 (originWhitelist).
|
||||
*/
|
||||
export function WebShell({ onReady }: { onReady: () => void }) {
|
||||
const webView = useRef<WebView>(null);
|
||||
const canGoBack = useRef(false);
|
||||
const ready = useRef(false);
|
||||
// 불러오기 실패·웹뷰 프로세스 종료 뒤 다시 시도하려고 웹뷰를 새로 띄운다
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
// 링크로 열렸으면 그 주소로, 아니면 홈으로 시작한다. 첫 주소를 알기 전에는 웹뷰를 띄우지 않는다
|
||||
const [startUri, setStartUri] = useState<string | null>(null);
|
||||
|
||||
// 웹이 한 번 뜨거나(성공·실패) 앱 시작 화면을 걷는다
|
||||
const markReady = useCallback(() => {
|
||||
if (ready.current) return;
|
||||
ready.current = true;
|
||||
onReady();
|
||||
}, [onReady]);
|
||||
|
||||
// 웹 안에서 이동한 기록이 있으면 안드로이드 뒤로 가기는 앱을 닫지 않고 웹 뒤로 간다
|
||||
useEffect(() => {
|
||||
const sub = BackHandler.addEventListener('hardwareBackPress', () => {
|
||||
if (!canGoBack.current) return false;
|
||||
webView.current?.goBack();
|
||||
return true;
|
||||
});
|
||||
return () => sub.remove();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
Linking.getInitialURL().then(
|
||||
(link) => alive && setStartUri((link && toSiteUrl(link)) ?? SITE_URL),
|
||||
(e: unknown) => {
|
||||
console.warn('[shell] 처음 링크를 읽지 못함', e);
|
||||
if (alive) setStartUri(SITE_URL);
|
||||
},
|
||||
);
|
||||
// 앱이 떠 있는 동안 링크를 누르면 지금 화면에서 그 주소로 옮겨 간다
|
||||
const sub = Linking.addEventListener('url', ({ url }) => {
|
||||
const target = toSiteUrl(url);
|
||||
if (target) webView.current?.injectJavaScript(`location.assign(${JSON.stringify(target)}); true;`);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
sub.remove();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const retry = useCallback(() => setAttempt((n) => n + 1), []);
|
||||
const onNavigationStateChange = useCallback((nav: WebViewNavigation) => {
|
||||
canGoBack.current = nav.canGoBack;
|
||||
}, []);
|
||||
|
||||
// 날씨각 사이트에서 온 요청만 처리한다 (다른 주소의 페이지가 로그인 같은 네이티브 기능을 부르지 못하게)
|
||||
const onMessage = useCallback((e: WebViewMessageEvent) => {
|
||||
let origin: string;
|
||||
try {
|
||||
origin = new URL(e.nativeEvent.url).origin;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (origin !== SITE_ORIGIN) return;
|
||||
const req = parseRequest(e.nativeEvent.data);
|
||||
if (!req) return;
|
||||
void handleRequest(req).then((reply) => webView.current?.injectJavaScript(replyScript(reply)));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<View className="flex-1" style={{ backgroundColor: BG }}>
|
||||
{startUri && (
|
||||
<WebView
|
||||
key={attempt}
|
||||
ref={webView}
|
||||
source={{ uri: startUri }}
|
||||
originWhitelist={[SITE_ORIGIN]}
|
||||
applicationNameForUserAgent={APP_UA}
|
||||
onNavigationStateChange={onNavigationStateChange}
|
||||
onMessage={onMessage}
|
||||
onLoadEnd={markReady}
|
||||
onRenderProcessGone={retry}
|
||||
renderError={() => <LoadFailed onRetry={retry} />}
|
||||
renderLoading={() => <ActivityIndicator style={{ position: 'absolute', top: '45%', alignSelf: 'center' }} />}
|
||||
startInLoadingState
|
||||
setSupportMultipleWindows={false}
|
||||
overScrollMode="never"
|
||||
bounces={false}
|
||||
style={{ backgroundColor: BG }}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user