diff --git a/README.en.md b/README.en.md index db613068..653e8983 100644 --- a/README.en.md +++ b/README.en.md @@ -151,11 +151,13 @@ Screen capture requires a secure browser context (HTTPS). When running in Docker ## 📱 PWA (add to home screen) -The app is a PWA: add it to your phone's home screen to run it full screen and open it with one tap. +The app is a PWA: add it to your phone's or tablet's home screen to run it full screen and open it with one tap. Tablets can use it in landscape. - **iPhone / iPad (Safari)**: tap **Share** at the bottom → **Add to Home Screen**. - **Android (Chrome)**: tap the **menu** at the top right → **Add to Home screen** or **Install app**. +When served over HTTPS (or `localhost`), a service worker caches scripts, styles and icons so the app opens faster, and shows an offline page when the network is down. Questions, statistics and other data always come from the server and are not cached offline. + ## 🛠️ Tech stack - **Framework**: [Next.js 16](https://nextjs.org/) (App Router) + [React 19](https://react.dev/) + TypeScript diff --git a/README.md b/README.md index f521de04..a209e3e0 100644 --- a/README.md +++ b/README.md @@ -149,11 +149,13 @@ ## 📱 PWA 支持 (添加到主屏幕) -本项目支持 PWA,可将应用添加到手机主屏幕,全屏运行、点击图标直接打开。 +本项目支持 PWA,可将应用添加到手机或平板主屏幕,全屏运行、点击图标直接打开,平板可横屏使用。 - **iPhone / iPad (Safari)**: 点击底部 **分享** 按钮 -> 选择 **"添加到主屏幕"**。 - **Android (Chrome)**: 点击右上角 **菜单** -> 选择 **"添加到主屏幕"** 或 **"安装应用"**。 +通过 HTTPS(或 `localhost`)访问时会启用 Service Worker:缓存页面脚本、样式和图标以加快打开速度,断网时显示离线提示页。题目、统计等数据始终从服务器读取,不做离线缓存。 + ## 🛠️ 技术栈 - **框架**: [Next.js 16](https://nextjs.org/) (App Router) + [React 19](https://react.dev/) + TypeScript diff --git a/doc/wiki/Quick-Start.md b/doc/wiki/Quick-Start.md index 6030be72..54ae1f0e 100644 --- a/doc/wiki/Quick-Start.md +++ b/doc/wiki/Quick-Start.md @@ -73,6 +73,6 @@ npm run dev - iPhone / iPad:在 Safari 中打开应用,选择“分享 → 添加到主屏幕”。 - Android:在 Chrome 菜单中选择“添加到主屏幕”或“安装应用”。 -PWA 提供主屏幕入口;AI 识别等功能仍需要服务端和 AI 服务可用。截图还取决于浏览器是否支持屏幕共享,并要求安全上下文,详见[常见问题](FAQ)。 +PWA 提供主屏幕入口,平板可横屏使用;通过 HTTPS 访问时会缓存页面脚本和图标,断网时显示离线提示页,数据不做离线缓存。AI 识别等功能仍需要服务端和 AI 服务可用。截图还取决于浏览器是否支持屏幕共享,并要求安全上下文,详见[常见问题](FAQ)。 完整环境变量示例见 [`.env.example`](https://github.com/margrop/wrong-notebook/blob/main/.env.example)。 diff --git a/public/icons/apple-touch-icon.png b/public/icons/apple-touch-icon.png new file mode 100644 index 00000000..99c003e9 Binary files /dev/null and b/public/icons/apple-touch-icon.png differ diff --git a/public/icons/icon-192.png b/public/icons/icon-192.png new file mode 100644 index 00000000..4389cf68 Binary files /dev/null and b/public/icons/icon-192.png differ diff --git a/public/icons/icon-512.png b/public/icons/icon-512.png new file mode 100644 index 00000000..d25bbb89 Binary files /dev/null and b/public/icons/icon-512.png differ diff --git a/public/icons/icon-maskable-512.png b/public/icons/icon-maskable-512.png new file mode 100644 index 00000000..0b0aa9df Binary files /dev/null and b/public/icons/icon-maskable-512.png differ diff --git a/public/offline.html b/public/offline.html new file mode 100644 index 00000000..e4231061 --- /dev/null +++ b/public/offline.html @@ -0,0 +1,61 @@ + + + + + + + 智能错题本 + + + +
+ +

无法连接到服务器

+

请检查网络连接,或确认错题本服务已启动,然后重试。

+ +
+ + + diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 00000000..958a38b9 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,84 @@ +/* + * 错题本 PWA Service Worker + * + * - 页面导航:始终走网络,断网时返回离线页 /offline.html + * - /_next/static、/icons:文件名带哈希或基本不变,缓存优先 + * - API 与其他请求不经过缓存,保证数据始终来自服务器 + */ +const VERSION = 'v1'; +const STATIC_CACHE = `wrong-notebook-static-${VERSION}`; +const OFFLINE_URL = '/offline.html'; +const PRECACHE = [OFFLINE_URL, '/icons/icon-192.png', '/icons/icon-512.png']; +/** 静态缓存最多保留的条目数,超出后删除最早写入的 */ +const MAX_STATIC_ENTRIES = 300; + +self.addEventListener('install', (event) => { + event.waitUntil( + caches.open(STATIC_CACHE) + .then((cache) => cache.addAll(PRECACHE)) + .then(() => self.skipWaiting()) + ); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches.keys() + .then((keys) => Promise.all( + keys + .filter((key) => key.startsWith('wrong-notebook-') && key !== STATIC_CACHE) + .map((key) => caches.delete(key)) + )) + .then(() => self.clients.claim()) + ); +}); + +function isStaticAsset(url) { + return url.pathname.startsWith('/_next/static/') || url.pathname.startsWith('/icons/'); +} + +async function trimCache(cache) { + const keys = await cache.keys(); + const excess = keys.length - MAX_STATIC_ENTRIES; + for (let i = 0; i < excess; i++) { + if (!keys[i].url.endsWith(OFFLINE_URL)) await cache.delete(keys[i]); + } +} + +async function cacheFirst(request) { + const cached = await caches.match(request); + if (cached) return cached; + const response = await fetch(request); + if (response.ok && response.type === 'basic') { + const cache = await caches.open(STATIC_CACHE); + await cache.put(request, response.clone()); + trimCache(cache); + } + return response; +} + +async function networkWithOfflineFallback(request) { + try { + return await fetch(request); + } catch (error) { + const offline = await caches.match(OFFLINE_URL); + if (offline) return offline; + throw error; + } +} + +self.addEventListener('fetch', (event) => { + const { request } = event; + if (request.method !== 'GET') return; + + const url = new URL(request.url); + if (url.origin !== self.location.origin) return; + + if (request.mode === 'navigate') { + event.respondWith(networkWithOfflineFallback(request)); + return; + } + + if (isStaticAsset(url)) { + event.respondWith(cacheFirst(request)); + } +}); diff --git a/src/__tests__/unit/pwa.test.ts b/src/__tests__/unit/pwa.test.ts new file mode 100644 index 00000000..1d28c3dd --- /dev/null +++ b/src/__tests__/unit/pwa.test.ts @@ -0,0 +1,43 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { describe, it, expect, vi } from 'vitest'; + +vi.mock('next-auth/jwt', () => ({ getToken: vi.fn() })); +vi.mock('@/lib/logger', () => ({ + createLogger: vi.fn(() => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() })), +})); + +import manifest from '@/app/manifest'; +import { config } from '@/middleware'; + +const publicDir = path.resolve(__dirname, '../../../public'); + +describe('PWA', () => { + it('manifest 提供 192/512 图标和 maskable 图标,且文件存在', () => { + const icons = manifest().icons ?? []; + expect(icons.map((icon) => icon.sizes)).toEqual(expect.arrayContaining(['192x192', '512x512'])); + expect(icons.some((icon) => icon.purpose === 'maskable')).toBe(true); + for (const icon of icons) { + expect(fs.existsSync(path.join(publicDir, icon.src))).toBe(true); + } + }); + + it('manifest 不锁定屏幕方向,平板可横屏使用', () => { + expect(manifest().orientation).toBe('any'); + expect(manifest().display).toBe('standalone'); + }); + + it('Service Worker 与离线页不经过登录拦截', () => { + const matcher = new RegExp(`^${config.matcher[0]}$`); + expect(matcher.test('/sw.js')).toBe(false); + expect(matcher.test('/offline.html')).toBe(false); + expect(matcher.test('/notebooks')).toBe(true); + }); + + it('Service Worker 预缓存的离线页存在,且不缓存 API', () => { + const sw = fs.readFileSync(path.join(publicDir, 'sw.js'), 'utf8'); + expect(sw).toContain("'/offline.html'"); + expect(fs.existsSync(path.join(publicDir, 'offline.html'))).toBe(true); + expect(sw).not.toMatch(/['"]\/api\//); + }); +}); diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 59969fa7..9106b7a6 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -42,7 +42,7 @@ export const metadata: Metadata = { }, icons: { icon: '/icons/icon.png', - apple: '/icons/icon.png', + apple: '/icons/apple-touch-icon.png', }, }; diff --git a/src/app/manifest.ts b/src/app/manifest.ts index cc4b4cdb..48dc6652 100644 --- a/src/app/manifest.ts +++ b/src/app/manifest.ts @@ -2,20 +2,23 @@ import type { MetadataRoute } from 'next' export default function manifest(): MetadataRoute.Manifest { return { + id: '/', name: '智能错题本', short_name: '错题本', description: 'AI 驱动的智能错题管理系统,帮助学生高效整理、分析和复习错题', + lang: 'zh-CN', start_url: '/', + scope: '/', display: 'standalone', background_color: '#ffffff', theme_color: '#4f46e5', - orientation: 'portrait', + // 手机竖屏、平板横竖屏都可使用,方向交给系统 + orientation: 'any', + categories: ['education', 'productivity'], icons: [ - { - src: '/icons/icon.png', - sizes: 'any', - type: 'image/png', - }, + { src: '/icons/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' }, + { src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' }, + { src: '/icons/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' }, ], } } diff --git a/src/components/providers.tsx b/src/components/providers.tsx index 6d4254a6..73cdf076 100644 --- a/src/components/providers.tsx +++ b/src/components/providers.tsx @@ -6,6 +6,7 @@ import { TimeZoneProvider } from "@/contexts/TimeZoneContext"; import { AppShell } from "@/components/app-shell"; import { BackgroundTasksButton } from "@/components/background-tasks-button"; import { FeedbackHost } from "@/components/ui/feedback-host"; +import { ServiceWorkerRegister } from "@/components/service-worker-register"; export function Providers({ children, timeZone }: { children: React.ReactNode; timeZone?: string }) { return ( @@ -15,6 +16,7 @@ export function Providers({ children, timeZone }: { children: React.ReactNode; t {children} + diff --git a/src/components/service-worker-register.tsx b/src/components/service-worker-register.tsx new file mode 100644 index 00000000..ef055cd8 --- /dev/null +++ b/src/components/service-worker-register.tsx @@ -0,0 +1,19 @@ +"use client"; + +import { useEffect } from "react"; +import { frontendLogger } from "@/lib/frontend-logger"; + +/** + * 注册 PWA Service Worker(public/sw.js)。 + * 仅生产环境注册,避免开发时缓存干扰热更新;Service Worker 需要安全上下文(HTTPS 或 localhost)。 + */ +export function ServiceWorkerRegister() { + useEffect(() => { + if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return; + navigator.serviceWorker.register("/sw.js", { scope: "/" }).catch((error: unknown) => { + frontendLogger.warn("[PWA]", "Service worker registration failed", { error: String(error) }); + }); + }, []); + + return null; +} diff --git a/src/middleware.ts b/src/middleware.ts index f74b7ef6..1ecfb919 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -68,7 +68,8 @@ export const config = { * - _next/image (image optimization files) * - favicon.ico (favicon file) * - icons/、manifest.webmanifest(PWA 图标与清单,登录页也要能加载) + * - sw.js、offline.html(Service Worker 与离线页,未登录时也要能加载) */ - "/((?!api|_next/static|_next/image|favicon.ico|icons/|manifest.webmanifest).*)", + "/((?!api|_next/static|_next/image|favicon.ico|icons/|manifest.webmanifest|sw.js|offline.html).*)", ], };