feat: 앱 쇼츠·구름 합치기 게임 — 오늘 피드 쇼츠 줄, /shorts 위아래로 넘겨 보기(유튜브 플레이어를 사이트 주소 기준 웹뷰로, 앞뒤 미리 받기, 눌러 소리), /game 은 웹 게임을 웹뷰로 띄우고 앱 지역·로그인을 넘김(react-native-webview) (GA shorts_open·shorts_view·shorts_sound)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
skkimandClaude committed 2026-11-04 17:42:32 +09:00
1 parent 5a88b08a44
commit 697c4bfb20
9 files changed
+332 -1

No files matched your search

+1 -1
View File
@@ -78,7 +78,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
- 앱도 같은 이벤트 이름·값으로 `track()`을 부른다 (`mobile/src/lib/analytics.ts`). 모든 이벤트에 `platform: 'app'`이 붙는다.
- **아직 GA4로 보내지 않는다 (2026-11-04).** Firebase Analytics(`google-services.json`)를 붙이면 앱 시작 때 `setAnalyticsSender`로 보내는 함수를 단다. 그 전까지 `track()`은 아무것도 보내지 않는다. 개발 빌드(`__DEV__`)는 붙인 뒤에도 보내지 않는다.
- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`).
- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음).
- 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다.
## GA4 설정
+1
View File
@@ -38,6 +38,7 @@
"react-native-svg": "15.15.4",
"react-native-view-shot": "5.1.0",
"react-native-web": "~0.21.0",
"react-native-webview": "13.16.1",
"react-native-worklets": "0.10.1",
"tailwindcss": "^4.3.3",
"uniwind": "^1.12.2"
+2
View File
@@ -9,6 +9,7 @@ import { RefreshControl, ScrollView, View, type LayoutRectangle } from 'react-na
import { MyGakRow } from '@/components/my-gak/my-gak';
import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card';
import { ShortsRail } from '@/components/shorts/rail';
import { Composer, TalkPost } from '@/components/talk/talk';
import { GakCard } from '@/components/today/gak-card';
import { Hero } from '@/components/today/hero';
@@ -99,6 +100,7 @@ export default function TodayScreen() {
onScroll={(e) => seen.onScroll(e.nativeEvent.contentOffset.y, e.nativeEvent.layoutMeasurement.height)}
>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<ShortsRail />
<Composer />
<MyGakRow />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
+85
View File
@@ -0,0 +1,85 @@
import { getAccessToken } from '@nalssigak/shared/api/auth';
import { router } from 'expo-router';
import { useRef, useState } from 'react';
import { ActivityIndicator, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
import { ScreenHeader } from '@/components/screen-header';
import { Text } from '@/components/text';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
/**
* 웹 페이지가 뜨기 전에 넣는 스크립트: 앱의 지역·로그인을 웹 저장소에 옮기고,
* 게임 화면을 떠나는 이동(뒤로 버튼)과 '로그인하면 …' 버튼은 앱으로 알린다 (웹 구글 로그인은 앱 안 웹뷰에서 막힌다).
* 갱신 토큰은 넘기지 않는다: 웹이 갱신하면 앱이 가진 갱신 토큰이 쓸모없어질 수 있다.
*/
function bridge(region: unknown, token: string | null) {
return `(function () {
try {
localStorage.setItem('nalssigak.b.region', ${JSON.stringify(JSON.stringify(region))});
${token ? `localStorage.setItem('nalssigak.accessToken', ${JSON.stringify(token)});` : `localStorage.removeItem('nalssigak.accessToken');`}
localStorage.removeItem('nalssigak.refreshToken');
} catch (e) {}
var post = function (t) { window.ReactNativeWebView.postMessage(t); };
var check = function () { if (location.pathname !== '/game') post('leave'); };
var push = history.pushState, replace = history.replaceState;
history.pushState = function () { push.apply(this, arguments); check(); };
history.replaceState = function () { replace.apply(this, arguments); check(); };
window.addEventListener('popstate', check);
document.addEventListener('click', function (e) {
var b = e.target && e.target.closest && e.target.closest('button');
if (b && b.textContent && b.textContent.trim().indexOf('로그인') === 0) { e.preventDefault(); e.stopPropagation(); post('login'); }
}, true);
})();
true;`;
}
/** 구름 합치기 게임: 웹 /game 을 그대로 띄운다 (물리 엔진·캔버스라 웹과 같은 화면, 사용자 결정 11/04) */
export default function GameScreen() {
const { region } = useRegion();
const { loggedIn } = useAuth();
const { open } = useSheet();
const { top, bottom } = useSafeAreaInsets();
const [failed, setFailed] = useState(false);
const left = useRef(false);
const onMessage = (e: WebViewMessageEvent) => {
if (e.nativeEvent.data === 'leave' && !left.current) {
left.current = true;
if (router.canGoBack()) router.back();
else router.replace('/');
}
if (e.nativeEvent.data === 'login') open({ type: 'login' });
};
if (failed)
return (
<View className="flex-1">
<ScreenHeader title="구름 합치기" />
<Text className="mx-6 mt-10 text-center text-[15px] font-bold text-ink2">게임을 불러오지 못했어요. 인터넷 연결을 확인하고 다시 들어와 주세요.</Text>
</View>
);
return (
<View className="flex-1 bg-[#cfe9ff]" style={{ paddingTop: top, paddingBottom: bottom }}>
{/* 로그인하면 토큰을 다시 넣어야 해서 로그인 여부로 새로 띄운다 */}
<WebView
key={`${region.code}:${loggedIn}`}
source={{ uri: `${SITE_URL}/game` }}
injectedJavaScriptBeforeContentLoaded={bridge(region, getAccessToken())}
onMessage={onMessage}
onError={() => setFailed(true)}
startInLoadingState
renderLoading={() => <ActivityIndicator style={{ position: 'absolute', top: '45%', alignSelf: 'center' }} />}
overScrollMode="never"
bounces={false}
setSupportMultipleWindows={false}
style={{ backgroundColor: 'transparent' }}
/>
</View>
);
}
+127
View File
@@ -0,0 +1,127 @@
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { ShortItem } from '@nalssigak/shared/api/client/types.gen';
import { useQuery } from '@tanstack/react-query';
import { Image } from 'expo-image';
import { router, useLocalSearchParams } from 'expo-router';
import { useEffect, useRef, useState } from 'react';
import { FlatList, Pressable, View, type ViewToken } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg';
import { ShortPlayer, type PlayerHandle } from '@/components/shorts/player';
import { thumb } from '@/components/shorts/rail';
import { Text } from '@/components/text';
import { track } from '@/lib/analytics';
const BAR = 48;
/** 쇼츠 화면: 그 영상부터 위아래로 넘겨 본다. 보이는 영상과 앞뒤만 소리 없이 미리 띄우고, 누르면 소리 켜기·끄기 (웹 ShortsPage) */
export default function ShortsScreen() {
const { id } = useLocalSearchParams<{ id?: string }>();
const q = useQuery(listShortsOptions());
const { top, bottom } = useSafeAreaInsets();
// 처음 들어온 영상만 시작점으로 쓴다
const [firstId] = useState(id);
const listed = q.data?.items ?? [];
const items: ShortItem[] = firstId && listed.length && !listed.some((s) => s.id === firstId) ? [{ id: firstId, title: '' }, ...listed] : listed;
const start = Math.max(0, items.findIndex((s) => s.id === firstId));
const [at, setAt] = useState(start);
const [sound, setSound] = useState(false);
const [ready, setReady] = useState<ReadonlySet<number>>(new Set());
const [box, setBox] = useState({ w: 0, h: 0 });
const players = useRef(new Map<number, PlayerHandle>());
const soundRef = useRef(false);
const atRef = useRef(start);
useEffect(() => {
if (firstId) track('shorts_open', { video_id: firstId });
}, [firstId]);
// 넘어온 영상만 처음부터 다시 틀고 소리를 맞춘다. 앞뒤는 소리만 끈다 (멈추면 유튜브 버튼이 떠서 멈추지 않는다)
useEffect(() => {
for (const [i, p] of players.current) {
if (i === at) {
p.command('seekTo', [0, true]);
p.command(soundRef.current ? 'unMute' : 'mute');
p.command('playVideo');
} else p.command('mute');
}
}, [at]);
// FlatList 는 이 함수가 바뀌면 안 되어 처음 한 번만 만든다
const [onViewable] = useState(() => ({ viewableItems }: { viewableItems: ViewToken<ShortItem>[] }) => {
const i = viewableItems[0]?.index;
if (i == null || i === atRef.current) return;
atRef.current = i;
setAt(i);
const s = viewableItems[0].item;
track('shorts_view', { video_id: s.id, index: i });
});
const toggleSound = () => {
const on = !soundRef.current;
soundRef.current = on;
setSound(on);
track('shorts_sound', { on });
players.current.get(at)?.command(on ? 'unMute' : 'mute');
};
const close = () => (router.canGoBack() ? router.back() : router.replace('/'));
// 9:16 을 칸 안에 맞춘다
const w = Math.min(box.w, (box.h * 9) / 16);
const h = (w * 16) / 9;
return (
<View className="flex-1 bg-[#1d2233]" style={{ paddingTop: top, paddingBottom: bottom }}>
{!!items[at] && <Image source={{ uri: thumb(items[at].id) }} style={{ position: 'absolute', inset: 0, opacity: 0.7, transform: [{ scale: 1.25 }] }} blurRadius={40} contentFit="cover" />}
<View className="absolute inset-0 bg-black/35" />
<View className="flex-row items-center justify-between px-3" style={{ height: BAR }}>
<Pressable onPress={close} hitSlop={8} accessibilityRole="button" accessibilityLabel="닫기" className="size-9 items-center justify-center rounded-full bg-white/15">
<Svg viewBox="0 0 24 24" width={18} height={18} fill="none" stroke="#fff" strokeWidth={2.4} strokeLinecap="round">
<Path d="M6 6l12 12M18 6L6 18" />
</Svg>
</Pressable>
<Pressable onPress={toggleSound} accessibilityRole="button" accessibilityState={{ selected: sound }} className="h-9 justify-center rounded-full bg-white/15 px-3.5">
<Text className="text-[13px] font-bold text-white">{sound ? '소리 끄기' : '소리 켜기'}</Text>
</Pressable>
</View>
<View className="flex-1" onLayout={(e) => setBox({ w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height })}>
{box.h > 0 && items.length > 0 && (
<FlatList
data={items}
keyExtractor={(s) => s.id}
pagingEnabled
showsVerticalScrollIndicator={false}
initialScrollIndex={start}
getItemLayout={(_, i) => ({ length: box.h, offset: box.h * i, index: i })}
onViewableItemsChanged={onViewable}
viewabilityConfig={{ itemVisiblePercentThreshold: 60 }}
windowSize={3}
renderItem={({ item: s, index: i }) => (
<View style={{ height: box.h }} className="items-center justify-center">
<View style={{ width: w, height: h }}>
<Image source={{ uri: thumb(s.id) }} style={{ position: 'absolute', inset: 0 }} contentFit="cover" />
{/* 릴스처럼 앞뒤 영상을 소리 없이 미리 받아 둔다. 첫 장면 전엔 표지가 보이게 숨긴다 */}
{Math.abs(i - at) <= 1 && (
<View pointerEvents="none" style={{ position: 'absolute', inset: 0, opacity: ready.has(i) ? 1 : 0 }}>
<ShortPlayer
id={s.id}
ref={(p) => {
if (p) players.current.set(i, p);
else players.current.delete(i);
}}
onPlaying={() => setReady((r) => (r.has(i) ? r : new Set(r).add(i)))}
/>
</View>
)}
{/* 누르면 소리 켜기·끄기, 위아래로 밀면 목록이 넘어간다 */}
<Pressable onPress={toggleSound} accessibilityLabel={sound ? '소리 끄기' : '소리 켜기'} style={{ position: 'absolute', inset: 0 }} />
</View>
</View>
)}
/>
)}
</View>
</View>
);
}
+2
View File
@@ -0,0 +1,2 @@
// 아이콘 줄 '쇼츠'(/shorts)는 첫 영상부터
export { default } from './[id]';
+53
View File
@@ -0,0 +1,53 @@
import { useImperativeHandle, useRef, type Ref } from 'react';
import { WebView } from 'react-native-webview';
import { SITE_URL } from '@/lib/site';
const YT_ORIGIN = 'https://www.youtube-nocookie.com';
export type PlayerFunc = 'playVideo' | 'seekTo' | 'mute' | 'unMute';
export type PlayerHandle = { command: (func: PlayerFunc, args?: unknown[]) => void };
function embed(id: string) {
const q = new URLSearchParams({ autoplay: '1', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: '0', rel: '0', modestbranding: '1', enablejsapi: '1', origin: SITE_URL });
return `${YT_ORIGIN}/embed/${id}?${q}`;
}
/**
* 유튜브 플레이어를 날씨각 주소를 기준으로 한 작은 문서 안 iframe 으로 띄운다.
* 앱 웹뷰에서 embed 주소를 바로 열면 보낸 곳(Referer)이 없어 유튜브가 막는다. 웹과 같이 IFrame API 메시지로 재생 상태를 받고 명령한다
*/
function html(id: string) {
return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;background:transparent;overflow:hidden}iframe{border:0;width:100%;height:100%}</style></head>
<body><iframe id="f" src="${embed(id)}" allow="autoplay; encrypted-media"></iframe>
<script>
var f = document.getElementById('f');
f.addEventListener('load', function () { f.contentWindow.postMessage(JSON.stringify({ event: 'listening', id: ${JSON.stringify(id)} }), '${YT_ORIGIN}'); });
window.addEventListener('message', function (e) {
if (e.origin !== '${YT_ORIGIN}') return;
try { var m = JSON.parse(e.data); if (m.info && m.info.playerState === 1) window.ReactNativeWebView.postMessage('playing'); } catch (x) {}
});
window.cmd = function (func, args) { f.contentWindow.postMessage(JSON.stringify({ event: 'command', func: func, args: args || [] }), '${YT_ORIGIN}'); };
</script></body></html>`;
}
/** 소리 없이 자동재생하는 쇼츠 플레이어. 첫 장면이 나오면 onPlaying (그 전엔 위에 표지를 덮어 둔다) */
export function ShortPlayer({ id, onPlaying, ref }: { id: string; onPlaying: () => void; ref?: Ref<PlayerHandle> }) {
const view = useRef<WebView>(null);
useImperativeHandle(ref, () => ({
command: (func, args = []) => view.current?.injectJavaScript(`window.cmd && window.cmd(${JSON.stringify(func)}, ${JSON.stringify(args)}); true;`),
}));
return (
<WebView
ref={view}
source={{ html: html(id), baseUrl: SITE_URL }}
originWhitelist={['*']}
onMessage={(e) => e.nativeEvent.data === 'playing' && onPlaying()}
mediaPlaybackRequiresUserAction={false}
allowsInlineMediaPlayback
scrollEnabled={false}
setSupportMultipleWindows={false}
style={{ backgroundColor: 'transparent' }}
/>
);
}
+45
View File
@@ -0,0 +1,45 @@
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { useQuery } from '@tanstack/react-query';
import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import { Link } from 'expo-router';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Rail } from '@/components/ui';
const SKELS = [0, 1, 2, 3];
export const thumb = (id: string) => `https://i.ytimg.com/vi/${id}/hqdefault.jpg`;
/** 오늘 화면 히어로 아래 쇼츠 줄. 누르면 쇼츠 화면에서 위아래로 넘겨 본다. 앱은 데이터를 아끼려고 줄에서는 표지만 (웹은 첫 카드를 소리 없이 재생) */
export function ShortsRail() {
const q = useQuery(listShortsOptions());
const items = q.data?.items ?? [];
if (q.isPending)
return (
<Rail>
{SKELS.map((i) => (
<View key={i} className="aspect-[9/16] w-[120px] rounded-xl bg-skel" />
))}
</Rail>
);
if (!items.length) return null;
return (
<View accessibilityLabel="날씨각 쇼츠">
<Rail>
{items.map((s) => (
<Link key={s.id} href={{ pathname: '/shorts/[id]', params: { id: s.id } }} asChild>
<Pressable accessibilityLabel={`${s.title} 보기`} className="aspect-[9/16] w-[120px] overflow-hidden rounded-xl bg-[#1d2233]">
<Image source={{ uri: thumb(s.id) }} style={{ position: 'absolute', inset: 0 }} contentFit="cover" />
<LinearGradient colors={['transparent', 'rgba(0,0,0,0.65)']} locations={[0.55, 1]} style={{ position: 'absolute', inset: 0 }} />
<Text numberOfLines={3} className="absolute inset-x-2 bottom-2 text-[12px] leading-[16px] font-bold text-white">
{s.title}
</Text>
</Pressable>
</Link>
))}
</Rail>
</View>
);
}
+16
View File
@@ -76,6 +76,7 @@
"react-native-svg": "15.15.4",
"react-native-view-shot": "5.1.0",
"react-native-web": "~0.21.0",
"react-native-webview": "13.16.1",
"react-native-worklets": "0.10.1",
"tailwindcss": "^4.3.3",
"uniwind": "^1.12.2"
@@ -15546,6 +15547,21 @@
"peerDependencies": {
"expo": "*"
}
},
"node_modules/react-native-webview": {
"version": "13.16.1",
"resolved": "https://registry.npmjs.org/react-native-webview/-/react-native-webview-13.16.1.tgz",
"integrity": "sha512-If0eHhoEdOYDcHsX+xBFwHMbWBGK1BvGDQDQdVkwtSIXiq1uiqjkpWVP2uQ1as94J0CzvFE9PUNDuhiX0Z6ubw==",
"license": "MIT",
"peer": true,
"dependencies": {
"escape-string-regexp": "^4.0.0",
"invariant": "2.2.4"
},
"peerDependencies": {
"react": "*",
"react-native": "*"
}
}
}
}