mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-02 03:09:34 +08:00
feat: 完善 PWA,补齐多尺寸图标并加入 Service Worker 与离线页
- manifest 增加 192/512 与 maskable 图标、id、scope,屏幕方向改为 any 以支持平板横屏 - 新增 public/sw.js:静态资源缓存优先,页面导航断网时显示离线页,API 不缓存 - iOS 主屏幕图标改用 180px 的 apple-touch-icon - 中间件放行 sw.js 与 offline.html Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)。
|
||||
|
||||
BIN
public/icons/apple-touch-icon.png
Normal file
BIN
public/icons/apple-touch-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
BIN
public/icons/icon-192.png
Normal file
BIN
public/icons/icon-192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 63 KiB |
BIN
public/icons/icon-512.png
Normal file
BIN
public/icons/icon-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 378 KiB |
BIN
public/icons/icon-maskable-512.png
Normal file
BIN
public/icons/icon-maskable-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 314 KiB |
61
public/offline.html
Normal file
61
public/offline.html
Normal file
@@ -0,0 +1,61 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="theme-color" content="#4f46e5">
|
||||
<title>智能错题本</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-family: system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
background: #f8fafc;
|
||||
color: #0f172a;
|
||||
}
|
||||
main { max-width: 360px; padding: 32px 16px; text-align: center; }
|
||||
img { width: 96px; height: 96px; border-radius: 22px; }
|
||||
h1 { font-size: 20px; margin: 24px 0 8px; }
|
||||
p { margin: 0 0 24px; color: #475569; line-height: 1.6; }
|
||||
button {
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
padding: 10px 24px;
|
||||
font-size: 16px;
|
||||
color: #fff;
|
||||
background: #4f46e5;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { background: #0f172a; color: #f1f5f9; }
|
||||
p { color: #94a3b8; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<img src="/icons/icon-192.png" alt="">
|
||||
<h1 id="title">无法连接到服务器</h1>
|
||||
<p id="message">请检查网络连接,或确认错题本服务已启动,然后重试。</p>
|
||||
<button id="retry" type="button">重试</button>
|
||||
</main>
|
||||
<script>
|
||||
if (!/^zh/i.test(navigator.language || '')) {
|
||||
document.documentElement.lang = 'en';
|
||||
document.title = 'Wrong Notebook';
|
||||
document.getElementById('title').textContent = 'Cannot reach the server';
|
||||
document.getElementById('message').textContent = 'Check your network connection or make sure the Wrong Notebook server is running, then try again.';
|
||||
document.getElementById('retry').textContent = 'Retry';
|
||||
}
|
||||
document.getElementById('retry').addEventListener('click', function () {
|
||||
location.reload();
|
||||
});
|
||||
window.addEventListener('online', function () {
|
||||
location.reload();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
84
public/sw.js
Normal file
84
public/sw.js
Normal file
@@ -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));
|
||||
}
|
||||
});
|
||||
43
src/__tests__/unit/pwa.test.ts
Normal file
43
src/__tests__/unit/pwa.test.ts
Normal file
@@ -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\//);
|
||||
});
|
||||
});
|
||||
@@ -42,7 +42,7 @@ export const metadata: Metadata = {
|
||||
},
|
||||
icons: {
|
||||
icon: '/icons/icon.png',
|
||||
apple: '/icons/icon.png',
|
||||
apple: '/icons/apple-touch-icon.png',
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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' },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
<AppShell>{children}</AppShell>
|
||||
<BackgroundTasksButton />
|
||||
<FeedbackHost />
|
||||
<ServiceWorkerRegister />
|
||||
</TimeZoneProvider>
|
||||
</LanguageProvider>
|
||||
</SessionProvider>
|
||||
|
||||
19
src/components/service-worker-register.tsx
Normal file
19
src/components/service-worker-register.tsx
Normal file
@@ -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;
|
||||
}
|
||||
@@ -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).*)",
|
||||
],
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user