105 lines
3.5 KiB
TypeScript
105 lines
3.5 KiB
TypeScript
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'
|
|
}
|
|
|
|
const onPhone = () => ['ios', 'android', 'inapp'].includes(platform())
|
|
|
|
/** 설치를 권할 곳: 휴대폰 브라우저, 그리고 설치창을 띄울 수 있는 PC 브라우저(Chrome·Edge). PC Safari·Firefox 와 이미 설치해 연 화면은 뺀다 */
|
|
export function useInstallable() {
|
|
const canPrompt = useCanPrompt()
|
|
return platform() !== 'standalone' && (onPhone() || canPrompt)
|
|
}
|
|
|
|
/** 설치창을 바로 띄울 수 있는지 (안드로이드 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()
|
|
try {
|
|
await e.prompt()
|
|
} catch (err) {
|
|
// 이미 한 번 띄웠거나 브라우저가 막으면 안내 창으로 넘긴다
|
|
console.warn('[install] prompt', err)
|
|
return false
|
|
}
|
|
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' })
|
|
}
|
|
}
|