M9: PWA — 홈 화면에 추가, 오프라인 안내

- 매니페스트·아이콘(192/512/maskable/apple-touch, scripts/pwa-icons.ts로 다시 만들기)
- 손으로 쓴 서비스 워커(apps/web/sw.js): 빌드 때 Vite 플러그인이 빌드 ID를 넣음.
  페이지는 네트워크만(오프라인이면 offline.html), /assets/*만 캐시 먼저(200개까지),
  /api·/ws·/healthz·/internal은 손대지 않음
- 오프라인 안내 페이지, 방 밖에서도 "인터넷 연결이 없어요" 띠
- 홈 아래 "홈 화면에 추가" 카드(설치 버튼, iOS는 공유 메뉴 안내, 닫으면 기억)
- 테스트: apps/web/src/sw.test.ts, e2e/pwa.e2e.ts(E2E_PORT), a11y.e2e.ts도 E2E_PORT 읽기
- 문서: 07 §11, 11 배포(no-cache 대상), README 확인 목록

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-06 13:12:23 +09:00
parent c27cb0a11a
commit 2ed1a7ed33
21 changed files with 716 additions and 5 deletions

93
apps/web/src/lib/pwa.ts Normal file
View File

@@ -0,0 +1,93 @@
/** PWA glue (docs/07 §11): service worker registration, "홈 화면에 추가", online state. */
import { useSyncExternalStore } from 'react';
interface BeforeInstallPromptEvent extends Event {
prompt(): Promise<void>;
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;
}
const DISMISS_KEY = 'bg.installDismissed';
let deferred: BeforeInstallPromptEvent | null = null;
let dismissed = false;
const listeners = new Set<() => void>();
const emit = () => listeners.forEach((l) => l());
/** Call once at startup, before React renders: the install event can fire very early. */
export function initPwa(): void {
try {
dismissed = localStorage.getItem(DISMISS_KEY) === '1';
} catch {
// Storage blocked: just show the offer again next time.
}
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault(); // we offer our own button instead of the browser's mini bar
deferred = e as BeforeInstallPromptEvent;
emit();
});
window.addEventListener('appinstalled', () => {
deferred = null;
emit();
});
// Dev builds never register: Vite serves unhashed modules that must not be cached.
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
window.addEventListener('load', () => void navigator.serviceWorker.register('/sw.js').catch(() => {}));
}
}
function standalone(): boolean {
return matchMedia('(display-mode: standalone)').matches || (navigator as { standalone?: boolean }).standalone === true;
}
function ios(): boolean {
return /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
}
/** 'prompt' = the browser can install with one tap, 'ios' = show Safari share-menu steps, null = hide. */
export type InstallMode = 'prompt' | 'ios' | null;
function installMode(): InstallMode {
if (dismissed || standalone()) return null;
if (deferred) return 'prompt';
return ios() ? 'ios' : null;
}
const subscribe = (l: () => void) => {
listeners.add(l);
return () => void listeners.delete(l);
};
export function useInstallMode(): InstallMode {
return useSyncExternalStore(subscribe, installMode, () => null);
}
export async function promptInstall(): Promise<void> {
const e = deferred;
if (!e) return;
deferred = null; // a prompt event can be used only once
emit();
await e.prompt();
await e.userChoice;
}
export function dismissInstall(): void {
dismissed = true;
try {
localStorage.setItem(DISMISS_KEY, '1');
} catch {
// ignore
}
emit();
}
const subscribeOnline = (l: () => void) => {
window.addEventListener('online', l);
window.addEventListener('offline', l);
return () => {
window.removeEventListener('online', l);
window.removeEventListener('offline', l);
};
};
export function useOnline(): boolean {
return useSyncExternalStore(subscribeOnline, () => navigator.onLine, () => true);
}