diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index 27a96500..605c3364 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -60,6 +60,10 @@ file-viewer 一条真的懒加载链。所以那个触发点很窄,而更常 给 `deploy/prod.sh` 和后端对账、给「关于」弹窗(帮助菜单,`shell/about-dialog.tsx`)显示用。 ⚠️ 那份 JSON 要保持紧凑的一行,原因见 [`deploy` 分册](../../deploy/AGENTS.md)「线上是哪一版」 +提示本身是 `src/components/update-notice.tsx` 那张卡片(#444):品牌色、新旧版本号、实心「立即刷新」+「稍后」。 +它走 `toast.custom`(`packages/ui` 的通用插槽),**不要另起一个 fixed 浮层** —— 右上角同时弹的别的 toast 会和它撞在同一个角上, +走同一个视口才会排队。`version.json` 的 `version` 只拿来显示,判据照旧是 `buildId`。 + 开发期 `apply: 'build'` 让插件整个不生效,`BUILD_ID` 回落成 `dev`, `/version.json` 404 → 检测静默跳过(dev 没有「发版」这件事)。 E2E 靠 `page.route` 造一个不同的 `buildId` 来验,见 diff --git a/apps/web/e2e/tests/new-version.spec.ts b/apps/web/e2e/tests/new-version.spec.ts index f68dcbdd..7e976305 100644 --- a/apps/web/e2e/tests/new-version.spec.ts +++ b/apps/web/e2e/tests/new-version.spec.ts @@ -11,22 +11,90 @@ import { expect, test } from "../fixtures/base" * (404 不能被当成发新版)验的是真实的开发期行为,不是假设。 */ test.describe("新版本提示", () => { - test("服务端 buildId 变了 → 弹一条带「刷新」的提示", async ({ authedPage: page }) => { + test("服务端 buildId 变了 → 弹一张带「立即刷新」的卡片,显示新旧版本号", async ({ authedPage: page }) => { await page.route("**/version.json", (route) => route.fulfill({ status: 200, contentType: "application/json", - body: JSON.stringify({ buildId: "e2e-new-build" }), + body: JSON.stringify({ buildId: "e2e-new-build", version: "99.0.0" }), }) ) await page.goto("/dashboard") - const toast = page.getByTestId("toast") - await expect(toast).toContainText("已发布新版本") + const notice = page.getByTestId("update-notice") + await expect(notice).toContainText("新版本已就绪") + // 新版本号来自 version.json;旧版本号是这份前端自己编译进去的,不写死 + await expect(notice.getByTestId("update-notice-versions")).toContainText("v99.0.0") // 🔴 不能自动刷新 —— 用户可能正在填一张长表单。只给按钮 - await expect(toast.getByRole("button", { name: "刷新" })).toBeVisible() + await expect(notice.getByTestId("update-notice-reload")).toBeVisible() await expect(page).toHaveURL(/\/dashboard/) + + // 「稍后」关掉这一张(同一页之后的轮询不会再弹,见 app-version.ts 的 notified) + await notice.getByTestId("update-notice-later").click() + await expect(notice).toBeHidden() + }) + + test("version.json 里没有 version 时照样提示,只是不显示版本那一行", async ({ authedPage: page }) => { + await page.route("**/version.json", (route) => + route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ buildId: "e2e-new-build" }), + }) + ) + + await page.goto("/dashboard") + + const notice = page.getByTestId("update-notice") + await expect(notice.getByTestId("update-notice-reload")).toBeVisible() + await expect(notice.getByTestId("update-notice-versions")).toHaveCount(0) + }) + + /** + * 懒加载失败那条路:手里没有版本号,`notifyNewVersion()` 要自己现取一次 `version.json`。 + * + * 让 `version.json` 回 `buildId: "dev"`(开发期编译进去的就是它)—— 轮询那条路判定「没换版」、 + * 不会抢先弹,卡片只可能来自懒加载失败这一支,显示的版本号也只可能是现取到的那个。 + * 失败本身用一个未处理的 rejection 造:浏览器真实的报错文案,`isStaleAssetError` 认的就是它。 + */ + test("懒加载分片取不到 → 弹卡片,版本号是现取的", async ({ authedPage: page }) => { + let fetched = 0 + await page.route("**/version.json", (route) => { + fetched += 1 + return route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ buildId: "dev", version: "99.1.0" }), + }) + }) + + await page.goto("/dashboard") + await expect(page.getByTestId("dash-greeting")).toBeVisible() + // 轮询那一次已经回来了,而且没弹 —— 否则下面断言的卡片分不清是谁弹的 + await expect.poll(() => fetched).toBeGreaterThan(0) + await expect(page.getByTestId("update-notice")).toHaveCount(0) + + await page.evaluate(() => { + void Promise.reject(new TypeError("Failed to fetch dynamically imported module: /assets/viewer-gone.js")) + }) + + const notice = page.getByTestId("update-notice") + await expect(notice.getByTestId("update-notice-versions")).toContainText("v99.1.0") + await expect(notice.getByTestId("update-notice-reload")).toBeVisible() + }) + + test("懒加载分片取不到、version.json 也取不到 → 照样弹,只是没有版本行", async ({ authedPage: page }) => { + await page.goto("/dashboard") + await expect(page.getByTestId("dash-greeting")).toBeVisible() + + await page.evaluate(() => { + void Promise.reject(new TypeError("Failed to fetch dynamically imported module: /assets/viewer-gone.js")) + }) + + const notice = page.getByTestId("update-notice") + await expect(notice.getByTestId("update-notice-reload")).toBeVisible() + await expect(notice.getByTestId("update-notice-versions")).toHaveCount(0) }) test("拿不到 version.json(开发期就是这样)不能弹提示", async ({ authedPage: page }) => { diff --git a/apps/web/src/components/update-notice.tsx b/apps/web/src/components/update-notice.tsx new file mode 100644 index 00000000..74977794 --- /dev/null +++ b/apps/web/src/components/update-notice.tsx @@ -0,0 +1,142 @@ +import { useTranslation } from "react-i18next" +import { IconArrowRight, IconRefresh } from "@tabler/icons-react" + +import { Button } from "@admin/ui/components/button" +import { ToastDescription, ToastTitle } from "@admin/ui/components/toast" + +import { + MORTISE_OUTLINE, + TENON_OUTLINE, + type Outline, +} from "@/components/tenon-outline" + +const toPath = (pts: Outline) => + `M${pts.map(([x, y]) => `${x} ${y}`).join(" L")} Z` + +/** + * 「服务端发新版了」那张卡片(#444)。检测在 `lib/app-version.ts`,这里只管长相。 + * + * 原来复用的是 `toast.warning`:琥珀色三角读起来像「出错了」,唯一要点的「刷新」 + * 是一行小号文字链接。发版是好事,所以换成品牌色:榫头滑进卯眼 = 新的一片咬合上来。 + * + * 由 `lib/app-version.ts` 的 `showUpdateNotice` 经 `toast.custom` 弹出 —— 走 toast 的视口, + * 不另起一个 fixed 浮层:右上角同时弹的别的 toast 会和它排队,而不是撞在同一个角上。 + */ +export function UpdateNotice({ + versions, + onLater, +}: { + versions: { current: string; next: string } | null + onLater: () => void +}) { + const { t } = useTranslation() + + return ( +
+ + {/* 顶边一道品牌色,和登录页标题里那两个字的流光同一组色 */} +
+
+ +
+
+ + + + +
+ +
+

+ Update +

+ + {t("新版本已就绪")} + + + {versions && ( +
+ {versions.current} + + + {versions.next} + +
+ )} + + + {t("未保存的内容请先保存,再刷新。")} + + +
+ + +
+
+
+
+ ) +} + +/** + * 榫头从左边滑进卯眼、咬合时整块轻轻一顿 —— 只在出现时演一次,不循环(常驻的卡片一直动是干扰)。 + * 颜色全走 `--primary-ink`(不是裸 `--primary`):主题色偏好换成什么,这张卡片跟着换, + * 深色下也跟着提亮 —— 裸 `--primary` 在深色里还是原来那个深靛蓝(见 ui 分册)。 + */ +const CSS = ` +.update-notice-rail { + background: linear-gradient(90deg, var(--primary-ink) 0%, color-mix(in oklch, var(--primary-ink) 55%, oklch(0.7 0.2 350)) 60%, transparent 100%); +} +.update-notice-tenon { + transform-box: fill-box; + animation: update-notice-slide .7s cubic-bezier(.3,.7,.2,1) .25s both; +} +.update-notice-tile { animation: update-notice-seat .35s ease-out .9s both } +@keyframes update-notice-slide { from { transform: translateX(-45%); opacity: .2 } to { transform: none; opacity: 1 } } +@keyframes update-notice-seat { 0% { transform: none } 40% { transform: scale(.92) } 100% { transform: none } } +@media (prefers-reduced-motion: reduce) { + .update-notice-tenon, .update-notice-tile { animation: none } +} +` diff --git a/apps/web/src/lib/app-version.ts b/apps/web/src/lib/app-version.ts index a143e73e..c90a5c54 100644 --- a/apps/web/src/lib/app-version.ts +++ b/apps/web/src/lib/app-version.ts @@ -1,6 +1,10 @@ -import { t } from "@admin/i18n" +import { createElement } from "react" + import { toast } from "@admin/ui/components/toast" +import { UpdateNotice } from "@/components/update-notice" +import { BRAND } from "@/lib/brand" + /** * 「服务端发新版了」的检测。 * @@ -71,28 +75,60 @@ let notified = false /** * 提示一次就够。**不自动刷新** —— 中后台的用户可能正在填一张长表单, * 替他刷新等于把没提交的东西扔了。给一个按钮,什么时候刷由他定。 + * + * `nextVersion` 是服务器上那一版的版本号(`version.json` 的 `version`),只用来显示。 + * 懒加载失败那条路手里没有它,就现取一次;取不到照样弹,只是不显示版本那一行。 */ -export function notifyNewVersion() { +export async function notifyNewVersion(nextVersion?: string | null) { if (notified) return notified = true - toast.warning(t("已发布新版本"), { - description: t("当前页面用的还是旧版前端,刷新后继续使用。"), - // 0 = 不自动消失:这条自己溜走就等于没提示 - timeout: 0, - action: { label: t("刷新"), onClick: () => window.location.reload() }, - }) + const next = + nextVersion === undefined + ? ((await fetchServed())?.version ?? null) + : nextVersion + showUpdateNotice(next) +} + +/** + * 弹那张卡片(#444)。**不自动消失**(`timeout: 0`):这条自己溜走就等于没提示。 + * 同一个版本号重新构建(换了基础镜像之类)时,「v1.1.3 → v1.1.3」是噪音,不显示版本那一行。 + */ +function showUpdateNotice(nextVersion: string | null) { + const current = BRAND.version + const next = nextVersion ? `v${nextVersion.replace(/^v/, "")}` : null + const versions = next && next !== current ? { current, next } : null + toast.custom( + (close) => createElement(UpdateNotice, { versions, onLater: close }), + { timeout: 0 } + ) } -async function fetchBuildId(): Promise { +type Served = { buildId: string; version: string | null } + +async function fetchServed(): Promise { + // 懒加载失败那条路也会走到这里,那时服务器可能正在重启 —— 别让提示等一个挂住的请求。 + // 手写超时而不是 `AbortSignal.timeout()`:老浏览器没有那个静态方法,调用会抛错、 + // 被下面的 catch 吞掉,于是每一次轮询都返回 null,新版检测整个静默失效(#445 评审) + const ctrl = new AbortController() + const timer = setTimeout(() => ctrl.abort(), 5000) try { - const res = await fetch("/version.json", { cache: "no-store" }) + const res = await fetch("/version.json", { + cache: "no-store", + signal: ctrl.signal, + }) if (!res.ok) return null // 开发期没有这个文件,vite 可能回落成 index.html(HTML 进不了 JSON.parse)—— // 拿不到就当「这个环境没有版本信息」,静默跳过,不要报错也不要提示 - const body = (await res.json()) as { buildId?: unknown } - return typeof body.buildId === "string" ? body.buildId : null + const body = (await res.json()) as { buildId?: unknown; version?: unknown } + if (typeof body.buildId !== "string") return null + return { + buildId: body.buildId, + version: typeof body.version === "string" ? body.version : null, + } } catch { return null + } finally { + clearTimeout(timer) } } @@ -105,8 +141,10 @@ export function installVersionWatch(): () => void { const check = async () => { if (notified) return lastCheck = Date.now() - const served = await fetchBuildId() - if (served && served !== BUILD_ID) notifyNewVersion() + const served = await fetchServed() + // 新版检测**只认 `buildId`**;`version` 只是给卡片显示的(见 apps/web 分册) + if (served && served.buildId !== BUILD_ID) + void notifyNewVersion(served.version) } const onWake = () => { @@ -116,11 +154,11 @@ export function installVersionWatch(): () => void { } const onRejection = (e: PromiseRejectionEvent) => { - if (isStaleAssetError(e.reason)) notifyNewVersion() + if (isStaleAssetError(e.reason)) void notifyNewVersion() } const onError = (e: ErrorEvent) => { - if (isStaleAssetError(e.error ?? e.message)) notifyNewVersion() + if (isStaleAssetError(e.error ?? e.message)) void notifyNewVersion() } void check() diff --git a/apps/web/src/routes/-error.tsx b/apps/web/src/routes/-error.tsx index 1cec9146..953cfe1b 100644 --- a/apps/web/src/routes/-error.tsx +++ b/apps/web/src/routes/-error.tsx @@ -1,4 +1,5 @@ import { useTranslation } from 'react-i18next' +import { IconRefresh } from "@tabler/icons-react" import { Button } from "@admin/ui/components/button" import { isStaleAssetError } from "@/lib/app-version" @@ -37,13 +38,14 @@ export function ErrorPage({ error: thrown }: { error?: unknown }) { return (
-

{t('已发布新版本')}

+

{t('新版本已就绪')}

{t('当前页面用的还是旧版前端,刷新后继续使用。')}

) diff --git a/packages/i18n/src/locales/en-US.json b/packages/i18n/src/locales/en-US.json index 72bc55d5..7337bc29 100644 --- a/packages/i18n/src/locales/en-US.json +++ b/packages/i18n/src/locales/en-US.json @@ -1248,7 +1248,6 @@ "已发出": "Sent", "已发布": "Published", "已发布 v{{n}}": "Published v{{n}}", - "已发布新版本": "A new version is available", "已发布版本": "Published version", "已取消": "Canceled", "已取消移动「{{name}}」": "Cancelled moving \"{{name}}\"", @@ -1758,6 +1757,7 @@ "新手机号": "New phone number", "新标签打开": "Open in new tab", "新版本 {{version}} 已下载": "Version {{version}} downloaded", + "新版本已就绪": "A new version is ready", "新登录撞上会话上限时怎么办。被挤掉的那台会看到「账号已在其他设备登录」": "What happens when a new sign-in hits the session limit. The device that gets pushed out is told the account signed in elsewhere", "新的待办": "New task", "新邮箱": "New email", @@ -1913,6 +1913,7 @@ "服务进程": "Service process", "未传完(已传 {{pct}}%),重新选择这个文件即可接着传": "Not finished ({{pct}}% uploaded). Choose this file again to resume", "未保存": "unsaved", + "未保存的内容请先保存,再刷新。": "Save any unsaved work, then reload.", "未写入": "Not saved", "未分组": "Ungrouped", "未分组的参数不会被 dynamic_config 加载,只能由业务代码自己读": "Ungrouped settings are not loaded by dynamic_config; only business code can read them", @@ -2414,8 +2415,10 @@ "移除失败": "Failed to remove", "移除筛选条件 {{name}}": "Remove filter {{name}}", "移除附件": "Remove attachment", + "稍后": "Later", "空": "Empty", "空闲超时": "Idle timeout", + "立即刷新": "Reload now", "立即发布": "Publish now", "立即执行一次": "Run now", "站内": "In-app", diff --git a/packages/i18n/src/locales/zh-CN.json b/packages/i18n/src/locales/zh-CN.json index 715e023f..1d9049f1 100644 --- a/packages/i18n/src/locales/zh-CN.json +++ b/packages/i18n/src/locales/zh-CN.json @@ -1248,7 +1248,6 @@ "已发出": "已发出", "已发布": "已发布", "已发布 v{{n}}": "已发布 v{{n}}", - "已发布新版本": "已发布新版本", "已发布版本": "已发布版本", "已取消": "已取消", "已取消移动「{{name}}」": "已取消移动「{{name}}」", @@ -1758,6 +1757,7 @@ "新手机号": "新手机号", "新标签打开": "新标签打开", "新版本 {{version}} 已下载": "新版本 {{version}} 已下载", + "新版本已就绪": "新版本已就绪", "新登录撞上会话上限时怎么办。被挤掉的那台会看到「账号已在其他设备登录」": "新登录撞上会话上限时怎么办。被挤掉的那台会看到「账号已在其他设备登录」", "新的待办": "新的待办", "新邮箱": "新邮箱", @@ -1913,6 +1913,7 @@ "服务进程": "服务进程", "未传完(已传 {{pct}}%),重新选择这个文件即可接着传": "未传完(已传 {{pct}}%),重新选择这个文件即可接着传", "未保存": "未保存", + "未保存的内容请先保存,再刷新。": "未保存的内容请先保存,再刷新。", "未写入": "未写入", "未分组": "未分组", "未分组的参数不会被 dynamic_config 加载,只能由业务代码自己读": "未分组的参数不会被 dynamic_config 加载,只能由业务代码自己读", @@ -2414,8 +2415,10 @@ "移除失败": "移除失败", "移除筛选条件 {{name}}": "移除筛选条件 {{name}}", "移除附件": "移除附件", + "稍后": "稍后", "空": "空", "空闲超时": "空闲超时", + "立即刷新": "立即刷新", "立即发布": "立即发布", "立即执行一次": "立即执行一次", "站内": "站内", diff --git a/packages/ui/src/components/toast.tsx b/packages/ui/src/components/toast.tsx index f88b11b0..db7033e3 100644 --- a/packages/ui/src/components/toast.tsx +++ b/packages/ui/src/components/toast.tsx @@ -123,7 +123,38 @@ function push(tone: ToastTone, title: React.ReactNode, opts: Options = {}) { return id } +/** + * 自定义内容的那一份 payload,挂在 Base UI 的 `data` 上。 + * `render` 收到 `close`,卡片自己的「稍后 / 立即刷新」按钮靠它关掉这一条。 + */ +type CustomData = { render: (close: () => void) => React.ReactNode } + +function isCustom(data: unknown): data is CustomData { + return typeof data === "object" && data !== null && typeof (data as CustomData).render === "function" +} + +/** + * 整张卡片由调用方画,但仍然走同一个视口:叠放、滑动关闭、进退场动画、 + * 读屏播报都和其它 toast 一致 —— 另起一个 fixed 浮层会和这里的 toast 撞在同一个角上。 + * + * 调用方的内容里用 `ToastTitle` / `ToastDescription` 标出标题和描述, + * 读屏才知道这条提示在说什么(Base UI 靠它们关联 `aria-labelledby`)。 + */ +function pushCustom(render: CustomData["render"], opts: { timeout?: number } = {}) { + const id: string = manager.add({ + type: "custom", + timeout: opts.timeout ?? 4500, + data: { render }, + }) + return id +} + +export const ToastTitle = ToastPrimitive.Title +export const ToastDescription = ToastPrimitive.Description + export const toast = { + /** 整张卡片自己画(见 `pushCustom`)。返回 id */ + custom: (render: CustomData["render"], opts?: { timeout?: number }) => pushCustom(render, opts), /** 中性通知,不带语气色 */ message: (title: React.ReactNode, opts?: Options) => push("message", title, opts), info: (title: React.ReactNode, opts?: Options) => push("info", title, opts), @@ -158,17 +189,59 @@ const TONE_CLASS: Record = { loading: "text-muted-foreground", } +/** 进退场 + 跟手滑动,普通条目和自定义卡片共用 */ +function motionClass(fromTop: boolean) { + return cn( + "translate-x-[var(--toast-swipe-movement-x)] translate-y-[var(--toast-swipe-movement-y)] transition-all duration-200", + // 进场从锚定边浮起,离场缩一点淡出;被 limit 顶掉的直接淡出 + fromTop + ? "data-[starting-style]:-translate-y-3 data-[starting-style]:opacity-0" + : "data-[starting-style]:translate-y-3 data-[starting-style]:opacity-0", + "data-[ending-style]:scale-[0.97] data-[ending-style]:opacity-0", + "data-[limited]:opacity-0", + // 拖动过程中不要再叠一层过渡,否则跟手会有橡皮筋感 + "data-[swiping]:transition-none" + ) +} + function ToastItem({ toast: item }: { toast: ToastPrimitive.Root.ToastObject }) { const t = useT() const position = React.useContext(ToastPositionContext) - // promise() 的 loading 阶段不带 type,按 loading 处理(转圈比信息图标准) - const tone = (item.type as ToastTone | undefined) ?? "loading" - const Icon = TONE_ICON[tone] ?? IconInfoCircle - const spinning = tone === "loading" // 顶部方位从上方落下,底部方位从下方浮起 —— 位置能切换后, // 进场动画方向也要跟着方位走,否则顶部的 toast 会「先往下缩一截再定住」 const fromTop = position.startsWith("top") + if (isCustom(item.data)) { + const { render } = item.data + return ( + + {render(() => manager.close(item.id))} + + ) + } + + return +} + +function ToneToast({ + item, + fromTop, + closeLabel, +}: { + item: ToastPrimitive.Root.ToastObject + fromTop: boolean + closeLabel: string +}) { + // promise() 的 loading 阶段不带 type,按 loading 处理(转圈比信息图标准) + const tone = (item.type as ToastTone | undefined) ?? "loading" + const Icon = TONE_ICON[tone] ?? IconInfoCircle + const spinning = tone === "loading" return ( @@ -199,7 +264,7 @@ function ToastItem({ toast: item }: { toast: ToastPrimitive.Root.ToastObject }) )}