feat: 홈 화면에 추가 — 오늘의 각 아래 설치 카드(닫으면 2주 숨김, 홈 화면에서 열면 안 보임)와 내 정보 메뉴, 안드로이드는 설치창·아이폰·카카오톡 등은 기기별 안내, 192·512·maskable 아이콘과 서비스 워커, 설치·실행 GA 이벤트

This commit is contained in:
minaChoi committed 2026-10-21 09:02:08 +09:00
1 parent 4e9b0bacba
commit e5716c0c7c
12 files changed
+248 -7

No files matched your search

+10 -3
View File
@@ -20,12 +20,14 @@ import {
unlikeCommentMutation,
updateMeMutation,
} from '../api/client/@tanstack/react-query.gen'
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
import { AuthProvider, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '../api/client/types.gen'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
import { GoogleButton } from './googleLogin'
import { useInstall } from './install'
import { InstallSheet } from './installBanner'
import { MixSheet } from './myGak'
import { ownPage, useRegion } from './regionContext'
import { useSky } from './skyContext'
@@ -74,7 +76,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
)
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가' } as const
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
@@ -135,6 +137,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
{state.type === 'install' && <InstallSheet />}
</div>
)}
{!state && <RegionLinks />}
@@ -866,6 +869,7 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
function MeSheet({ onDone }: { onDone: () => void }) {
const install = useInstall()
const { me, logout } = useAuth()
const queryClient = useQueryClient()
const update = useMutation(updateMeMutation())
@@ -899,8 +903,11 @@ function MeSheet({ onDone }: { onDone: () => void }) {
<Body className="flex flex-col gap-3">
<div className="flex flex-col items-center gap-1.5">
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.login_id}(으)로 로그인했어요</p>
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
</div>
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
📲 홈 화면에 추가
</button>
<section aria-label="내 캐릭터">
<h4 className="m-0 mb-2 text-sm font-extrabold">내 캐릭터</h4>
<div className="grid grid-cols-3 gap-2" role="radiogroup" aria-label="캐릭터 고르기">
+2
View File
@@ -5,6 +5,7 @@ import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TalkData, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
import { InstallBanner } from './installBanner'
import { MyGakRow } from './myGak'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
@@ -400,6 +401,7 @@ export function TodayPage() {
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
)}
<InstallBanner />
<div>
{load === 'loading' && <PostsSkel />}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
+90
View File
@@ -0,0 +1,90 @@
import { useSyncExternalStore } from 'react'
import { track } from '../lib/analytics'
import { useSheet } from './sheetContext'
type InstallPromptEvent = Event & { prompt: () => Promise<void>; userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }> }
const DISMISS_KEY = 'nalssigak.b.installDismissed'
const DISMISS_DAYS = 14
// 안드로이드 Chrome 은 설치할 수 있을 때 이 이벤트를 한 번 준다. 앱이 뜨기 전에 올 수 있어 모듈을 불러올 때 바로 받아 둔다
let deferred: InstallPromptEvent | null = null
const listeners = new Set<() => void>()
const notify = () => listeners.forEach((cb) => cb())
if (typeof window !== 'undefined') {
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault()
deferred = e as InstallPromptEvent
notify()
})
window.addEventListener('appinstalled', () => {
deferred = null
track('install_done', {})
notify()
})
}
export type Platform = 'standalone' | 'inapp' | 'ios' | 'android' | 'other'
/** 지금 이 기기에서 홈 화면 추가를 어떻게 안내할지 */
export function platform(): Platform {
const ua = navigator.userAgent
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) return 'standalone'
if (/KAKAOTALK|Instagram|FBAN|FBAV|NAVER\(inapp|; wv\)|Line\//i.test(ua)) return 'inapp'
if (/iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return 'ios'
if (/Android/.test(ua)) return 'android'
return 'other'
}
/** 설치창을 바로 띄울 수 있는지 (안드로이드 Chrome 등) */
export function useCanPrompt() {
return useSyncExternalStore(
(cb) => {
listeners.add(cb)
return () => listeners.delete(cb)
},
() => deferred != null,
)
}
/** 설치창을 띄운다. 띄웠으면 true */
export async function promptInstall(): Promise<boolean> {
if (!deferred) return false
const e = deferred
deferred = null
notify()
await e.prompt()
const { outcome } = await e.userChoice
track('install_choice', { outcome })
return true
}
export function dismissed(): boolean {
try {
const at = Number(localStorage.getItem(DISMISS_KEY))
return at > 0 && Date.now() - at < DISMISS_DAYS * 86_400_000
} catch {
// 저장소를 못 쓰는 브라우저에선 이번 방문 동안만 보인다
return false
}
}
export function dismiss() {
try {
localStorage.setItem(DISMISS_KEY, String(Date.now()))
} catch (e) {
console.warn('[install] 닫은 시각을 저장하지 못함', e)
}
}
/** 홈 화면에 추가: 설치창을 띄울 수 있으면 띄우고, 아니면 기기별 안내 창을 연다 */
export function useInstall() {
const { open } = useSheet()
const canPrompt = useCanPrompt()
return async (from: 'banner' | 'menu') => {
const shown = canPrompt && (await promptInstall())
track('install_click', { from, method: shown ? 'prompt' : 'guide' })
if (!shown) open({ type: 'install' })
}
}
+103
View File
@@ -0,0 +1,103 @@
import { useEffect, useState } from 'react'
import { track } from '../lib/analytics'
import { dismiss, dismissed, platform, useInstall } from './install'
const SITE = 'https://weather.o2o.kr'
/** 오늘 탭의 작은 설치 카드. 오늘의 각까지 본 뒤 자리에 놓고, 닫으면 2주 숨기고, 홈 화면에서 연 경우엔 안 보인다 */
export function InstallBanner() {
const install = useInstall()
const [hidden, setHidden] = useState(() => platform() === 'standalone' || dismissed())
useEffect(() => {
if (!hidden) track('install_banner_view', {})
}, [hidden])
if (hidden) return null
return (
<aside aria-label="홈 화면에 추가" className="mx-3 mt-3.5 flex items-center gap-3 rounded-[22px] bg-white p-3.5 shadow-[inset_0_-5px_0_var(--shade)]">
<img src="/app/icon-192.png" alt="" className="size-12 shrink-0 rounded-[14px]" />
<div className="min-w-0 flex-1">
<p className="m-0 font-jua text-[16.5px] leading-snug">내일도 우산각·빨래각, 바로 확인하세요</p>
<p className="m-0 mt-0.5 text-[12.5px] font-semibold text-(--ink2)">날씨각을 홈 화면에 추가하고 한 번에 열어보세요.</p>
<div className="mt-2 flex gap-1.5">
<button type="button" onClick={() => install('banner')} className="cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">
📲 홈 화면에 추가
</button>
<button
type="button"
onClick={() => {
dismiss()
setHidden(true)
}}
className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2)"
>
닫기
</button>
</div>
</div>
</aside>
)
}
function Steps({ items }: { items: string[] }) {
return (
<ol className="m-0 flex list-none flex-col gap-2 p-0">
{items.map((t, i) => (
<li key={t} className="flex items-start gap-2.5 rounded-2xl bg-[#f3f6fb] px-3.5 py-3 text-[14.5px] font-bold">
<b className="grid size-6 shrink-0 place-items-center rounded-full bg-(--orange) font-jua text-[14px] font-normal text-white">{i + 1}</b>
<span>{t}</span>
</li>
))}
</ol>
)
}
/** 설치창을 띄울 수 없는 기기의 안내 */
export function InstallSheet() {
const p = platform()
const [copied, setCopied] = useState(false)
const copy = () =>
navigator.clipboard.writeText(SITE).then(
() => setCopied(true),
(e: unknown) => console.error('[install] copy', e),
)
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
{p === 'standalone' && <p className="m-0 text-[15px] font-bold">이미 홈 화면에서 열었어요. 다음에도 아이콘을 눌러 바로 여세요.</p>}
{p === 'ios' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">아이폰은 Safari에서 이렇게 추가해요.</p>
<Steps items={['아래쪽 가운데 공유 버튼(네모에 위쪽 화살표)을 눌러요', "목록을 올려 '홈 화면에 추가'를 눌러요", "오른쪽 위 '추가'를 누르면 끝이에요"]} />
</>
)}
{p === 'android' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">지금 브라우저에선 설치창을 바로 띄울 수 없어요. 메뉴에서 추가해 주세요.</p>
<Steps items={['오른쪽 위 ⋮ 메뉴를 눌러요', "'홈 화면에 추가' 또는 '앱 설치'를 눌러요", "'추가' 또는 '설치'를 누르면 끝이에요"]} />
</>
)}
{p === 'inapp' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">카카오톡 같은 앱 안에서는 홈 화면에 추가할 수 없어요. Safari나 Chrome에서 열어 주세요.</p>
<Steps items={["오른쪽 위 ⋮ 또는 공유 버튼에서 '다른 브라우저로 열기'를 눌러요", '안 보이면 아래 주소를 복사해 Safari·Chrome에 붙여 넣어요', "열린 화면에서 '홈 화면에 추가'를 눌러요"]} />
</>
)}
{p === 'other' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">휴대폰에서 열면 홈 화면에 추가할 수 있어요.</p>
<Steps items={['휴대폰 Safari(아이폰)나 Chrome(갤럭시)에서 아래 주소를 열어요', "공유 버튼이나 ⋮ 메뉴에서 '홈 화면에 추가'를 눌러요"]} />
</>
)}
{(p === 'inapp' || p === 'other') && (
<div className="mt-3 flex items-center gap-2 rounded-2xl border border-(--line) px-3.5 py-2.5">
<span className="min-w-0 flex-1 truncate text-[14.5px] font-bold select-all">{SITE}</span>
<button type="button" onClick={copy} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
{copied ? '복사함' : '주소 복사'}
</button>
</div>
)}
</div>
)
}
+1
View File
@@ -14,6 +14,7 @@ export type SheetState =
| { type: 'me' }
| { type: 'region' }
| { type: 'mix'; shared?: MyGak }
| { type: 'install' }
| null
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
+5
View File
@@ -6,6 +6,11 @@ type Events = {
login: { method: 'id' | 'google' }
sign_up: { method: 'id' }
region_change: { region_name: string; method: 'list' | 'location' }
install_banner_view: Record<string, never>
install_click: { from: 'banner' | 'menu'; method: 'prompt' | 'guide' }
install_choice: { outcome: 'accepted' | 'dismissed' }
install_done: Record<string, never>
app_launch: { mode: 'standalone' }
}
declare global {
+8
View File
@@ -4,6 +4,8 @@ import { createRoot } from 'react-dom/client'
import './index.css'
import './api/setup'
import App from './App.tsx'
import './b/install'
import { track } from './lib/analytics'
// iOS는 user-scalable=no를 무시해서 두 손가락 확대를 직접 막는다
for (const type of ['gesturestart', 'gesturechange']) document.addEventListener(type, (e) => e.preventDefault(), { passive: false })
@@ -13,6 +15,12 @@ const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, refetchOnWindowFocus: false, placeholderData: keepPreviousData } },
})
// 홈 화면 설치 조건(서비스 워커)과, 홈 화면 아이콘으로 연 횟수
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch((e: unknown) => console.error('[sw] register', e))
}
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) track('app_launch', { mode: 'standalone' })
createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>