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:
28
apps/web/src/components/InstallCard.tsx
Normal file
28
apps/web/src/components/InstallCard.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
/** "홈 화면에 추가" offer (docs/07 §11). Hidden when already installed, dismissed, or not installable. */
|
||||
import { dismissInstall, promptInstall, useInstallMode } from '../lib/pwa';
|
||||
|
||||
export function InstallCard() {
|
||||
const mode = useInstallMode();
|
||||
if (!mode) return null;
|
||||
return (
|
||||
<section className="card row" aria-label="홈 화면에 추가" style={{ gap: 12 }}>
|
||||
<span style={{ fontSize: '1.8rem' }} aria-hidden>
|
||||
📲
|
||||
</span>
|
||||
<div style={{ flex: '1 1 220px' }}>
|
||||
<strong>홈 화면에 추가해 보세요</strong>
|
||||
<div className="muted small">
|
||||
{mode === 'ios' ? 'Safari 공유 버튼(네모에 화살표)을 누르고 [홈 화면에 추가]를 골라 주세요.' : '앱처럼 아이콘을 눌러 바로 열 수 있어요.'}
|
||||
</div>
|
||||
</div>
|
||||
{mode === 'prompt' && (
|
||||
<button className="btn btn-primary btn-sm" onClick={() => void promptInstall()}>
|
||||
추가하기
|
||||
</button>
|
||||
)}
|
||||
<button className="btn btn-secondary btn-sm" onClick={dismissInstall}>
|
||||
닫기
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { formatRoomCode } from '@bg/shared/lite';
|
||||
import { useToasts, toast } from '../store/toast';
|
||||
import { useRoom } from '../net/socket';
|
||||
import { haptic } from '../lib/feedback';
|
||||
import { useOnline } from '../lib/pwa';
|
||||
|
||||
const AVATAR_COLORS = ['#2563eb', '#db2777', '#16a34a', '#ea580c', '#7c3aed', '#0891b2', '#ca8a04', '#dc2626'];
|
||||
|
||||
@@ -138,7 +139,8 @@ export function Toasts() {
|
||||
export function ConnectionBanner() {
|
||||
const status = useRoom((s) => s.status);
|
||||
const code = useRoom((s) => s.code);
|
||||
if (!code) return null;
|
||||
const online = useOnline();
|
||||
if (!code) return online ? null : <div className="conn-banner" role="status">인터넷 연결이 없어요. 연결되면 다시 쓸 수 있어요.</div>;
|
||||
if (status === 'reconnecting' || status === 'connecting') return <div className="conn-banner">다시 연결하는 중…</div>;
|
||||
if (status === 'offline') return <div className="conn-banner">인터넷 연결이 끊겼어요. 연결되면 자동으로 이어져요.</div>;
|
||||
return null;
|
||||
|
||||
93
apps/web/src/lib/pwa.ts
Normal file
93
apps/web/src/lib/pwa.ts
Normal 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);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { useSession } from './store/session';
|
||||
import { toast } from './store/toast';
|
||||
import { Home } from './pages/Home';
|
||||
import { SiteHeader } from './components/SiteHeader';
|
||||
import { initPwa } from './lib/pwa';
|
||||
|
||||
const JoinPage = lazy(() => import('./pages/JoinPage'));
|
||||
const RoomPage = lazy(() => import('./pages/RoomPage'));
|
||||
@@ -75,6 +76,7 @@ function Shell() {
|
||||
);
|
||||
}
|
||||
|
||||
initPwa();
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Sheet } from '../components/ui';
|
||||
import { NicknameForm } from '../components/NicknameForm';
|
||||
import { CodeInput } from '../components/CodeInput';
|
||||
import { GameGrid } from '../components/GameGrid';
|
||||
import { InstallCard } from '../components/InstallCard';
|
||||
import { gameName } from '../components/GameNotice';
|
||||
import { api } from '../net/api';
|
||||
import { useSession } from '../store/session';
|
||||
@@ -110,6 +111,8 @@ export function Home() {
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<InstallCard />
|
||||
|
||||
{picker && (
|
||||
<Sheet onClose={() => setPicker(false)} label="게임 고르기">
|
||||
<h2>어떤 게임을 할까요?</h2>
|
||||
|
||||
137
apps/web/src/sw.test.ts
Normal file
137
apps/web/src/sw.test.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
/** Service worker cache rules (docs/07 §11), run against fake caches/fetch. */
|
||||
import { beforeEach, expect, test } from 'bun:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const ORIGIN = 'https://game.test';
|
||||
const SRC = readFileSync(join(import.meta.dir, '../sw.js'), 'utf8');
|
||||
|
||||
class FakeCache {
|
||||
map = new Map<string, Response>();
|
||||
async match(req: { url: string } | string) {
|
||||
return this.map.get(typeof req === 'string' ? new URL(req, ORIGIN).href : req.url)?.clone();
|
||||
}
|
||||
async put(req: { url: string }, res: Response) {
|
||||
this.map.set(req.url, res);
|
||||
}
|
||||
async add(req: Request) {
|
||||
this.put(req, await net(req));
|
||||
}
|
||||
async keys() {
|
||||
return [...this.map.keys()].map((url) => ({ url }));
|
||||
}
|
||||
async delete(req: { url: string }) {
|
||||
return this.map.delete(req.url);
|
||||
}
|
||||
}
|
||||
|
||||
let stores: Map<string, FakeCache>;
|
||||
let net: (req: { url: string }) => Promise<Response>;
|
||||
let fetched: string[];
|
||||
let handlers: Record<string, (e: unknown) => void>;
|
||||
|
||||
const caches = {
|
||||
open: async (name: string) => stores.get(name) ?? stores.set(name, new FakeCache()).get(name)!,
|
||||
keys: async () => [...stores.keys()],
|
||||
delete: async (name: string) => stores.delete(name),
|
||||
match: async (req: string, opts: { cacheName: string }) => stores.get(opts.cacheName)?.match(req),
|
||||
};
|
||||
const fetchFn = (req: { url: string }) => {
|
||||
fetched.push(new URL(req.url).pathname);
|
||||
return net(req);
|
||||
};
|
||||
class RelRequest extends Request {
|
||||
constructor(url: string, init?: RequestInit) {
|
||||
super(new URL(url, ORIGIN), init);
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
stores = new Map();
|
||||
fetched = [];
|
||||
handlers = {};
|
||||
net = async (req) => new Response(`body of ${new URL(req.url).pathname}`, { headers: { 'Content-Type': 'text/javascript' } });
|
||||
const self = {
|
||||
location: new URL(ORIGIN),
|
||||
addEventListener: (type: string, fn: (e: unknown) => void) => (handlers[type] = fn),
|
||||
skipWaiting: async () => {},
|
||||
clients: { claim: async () => {} },
|
||||
};
|
||||
new Function('self', 'caches', 'fetch', 'Request', SRC)(self, caches, fetchFn, RelRequest);
|
||||
});
|
||||
|
||||
async function lifecycle(type: 'install' | 'activate') {
|
||||
const pending: Promise<unknown>[] = [];
|
||||
handlers[type]!({ waitUntil: (p: Promise<unknown>) => pending.push(p) });
|
||||
await Promise.all(pending);
|
||||
}
|
||||
|
||||
/** Dispatches a fetch; returns undefined when the worker leaves the request to the browser. */
|
||||
async function request(path: string, opts: { mode?: string; method?: string; origin?: string } = {}) {
|
||||
let res: Promise<Response> | undefined;
|
||||
const pending: Promise<unknown>[] = [];
|
||||
handlers.fetch!({
|
||||
request: { url: new URL(path, opts.origin ?? ORIGIN).href, method: opts.method ?? 'GET', mode: opts.mode ?? 'cors' },
|
||||
respondWith: (p: Promise<Response>) => (res = p),
|
||||
waitUntil: (p: Promise<unknown>) => pending.push(p),
|
||||
});
|
||||
const out = await res;
|
||||
await Promise.all(pending);
|
||||
return out;
|
||||
}
|
||||
|
||||
test('install keeps the offline page; activate drops old caches only', async () => {
|
||||
stores.set('bg-shell-old', new FakeCache());
|
||||
stores.set('bg-assets-v0', new FakeCache());
|
||||
stores.set('someone-else', new FakeCache());
|
||||
await lifecycle('install');
|
||||
await lifecycle('activate');
|
||||
const names = [...stores.keys()];
|
||||
expect(names).toContain('someone-else');
|
||||
expect(names.filter((n) => n.startsWith('bg-'))).toEqual([expect.stringMatching(/^bg-shell-/)]);
|
||||
expect(await (await caches.match('/offline.html', { cacheName: names.find((n) => n.startsWith('bg-shell-'))! }))?.text()).toBe('body of /offline.html');
|
||||
});
|
||||
|
||||
test('API, WebSocket, health, internal, non-GET and other origins are never handled', async () => {
|
||||
await lifecycle('install');
|
||||
for (const path of ['/api/me', '/api/admin/stats', '/ws', '/healthz', '/internal/metrics']) {
|
||||
expect(await request(path)).toBeUndefined();
|
||||
expect(await request(path, { mode: 'navigate' })).toBeUndefined();
|
||||
}
|
||||
expect(await request('/assets/a.js', { method: 'POST' })).toBeUndefined();
|
||||
expect(await request('/assets/a.js', { origin: 'https://cdn.discordapp.com' })).toBeUndefined();
|
||||
expect([...stores.keys()].filter((n) => n.startsWith('bg-assets'))).toEqual([]);
|
||||
});
|
||||
|
||||
test('pages come from the network and are never cached; offline shows the offline page', async () => {
|
||||
await lifecycle('install');
|
||||
net = async () => new Response('<!doctype html>v1', { headers: { 'Content-Type': 'text/html' } });
|
||||
expect(await (await request('/r/123456', { mode: 'navigate' }))!.text()).toBe('<!doctype html>v1');
|
||||
net = async () => new Response('<!doctype html>v2', { headers: { 'Content-Type': 'text/html' } });
|
||||
expect(await (await request('/', { mode: 'navigate' }))!.text()).toBe('<!doctype html>v2');
|
||||
net = () => Promise.reject(new TypeError('Failed to fetch'));
|
||||
expect(await (await request('/', { mode: 'navigate' }))!.text()).toBe('body of /offline.html');
|
||||
expect([...stores.values()].flatMap((c) => [...c.map.keys()]).map((u) => new URL(u).pathname)).toEqual(['/offline.html']);
|
||||
});
|
||||
|
||||
test('hashed assets are cache-first; HTML fallbacks and partial responses are not kept', async () => {
|
||||
expect(await (await request('/assets/a-1.js'))!.text()).toBe('body of /assets/a-1.js');
|
||||
expect(await (await request('/assets/a-1.js'))!.text()).toBe('body of /assets/a-1.js');
|
||||
expect(fetched).toEqual(['/assets/a-1.js']);
|
||||
|
||||
net = async () => new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } });
|
||||
await request('/assets/gone.js');
|
||||
net = async () => new Response('part', { status: 206, headers: { 'Content-Type': 'audio/mpeg' } });
|
||||
await request('/assets/s.mp3');
|
||||
net = async () => new Response('err', { status: 500 });
|
||||
await request('/assets/b.js');
|
||||
expect([...stores.get('bg-assets-v1')!.map.keys()].map((u) => new URL(u).pathname)).toEqual(['/assets/a-1.js']);
|
||||
});
|
||||
|
||||
test('asset cache is bounded, oldest out first', async () => {
|
||||
for (let i = 0; i < 205; i++) await request(`/assets/f${i}.js`);
|
||||
const kept = [...stores.get('bg-assets-v1')!.map.keys()].map((u) => new URL(u).pathname);
|
||||
expect(kept.length).toBe(200);
|
||||
expect(kept[0]).toBe('/assets/f5.js');
|
||||
expect(kept.at(-1)).toBe('/assets/f204.js');
|
||||
});
|
||||
Reference in New Issue
Block a user