Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/web/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 来验,见
Expand Down
78 changes: 73 additions & 5 deletions apps/web/e2e/tests/new-version.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down
142 changes: 142 additions & 0 deletions apps/web/src/components/update-notice.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div
data-testid="update-notice"
className="relative overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-xl"
>
<style href="update-notice" precedence="medium">
{CSS}
</style>
{/* 顶边一道品牌色,和登录页标题里那两个字的流光同一组色 */}
<div
aria-hidden
className="update-notice-rail absolute inset-x-0 top-0 h-0.5"
/>
<div
aria-hidden
className="pointer-events-none absolute -end-14 -top-16 size-40 rounded-full bg-primary/12 blur-3xl"
/>

<div className="relative flex gap-3.5 p-4">
<div
aria-hidden
className="update-notice-tile grid size-10 shrink-0 place-items-center rounded-lg bg-primary text-primary-foreground shadow-sm"
>
<svg
viewBox="0 0 24 24"
className="size-6"
fill="currentColor"
focusable="false"
>
<path className="update-notice-tenon" d={toPath(TENON_OUTLINE)} />
<path d={toPath(MORTISE_OUTLINE)} fillOpacity="0.5" />
</svg>
</div>

<div className="min-w-0 flex-1">
<p
aria-hidden
className="font-mono text-[10px] leading-none tracking-[0.3em] text-primary uppercase"
>
Update
</p>
<ToastTitle className="mt-1.5 text-sm leading-snug font-semibold">
{t("新版本已就绪")}
</ToastTitle>

{versions && (
<div
data-testid="update-notice-versions"
className="mt-1.5 flex items-center gap-1.5 font-mono text-xs"
>
<span className="text-muted-foreground">{versions.current}</span>
<IconArrowRight
aria-hidden
className="size-3 text-muted-foreground/70"
/>
<span className="rounded-sm bg-primary/10 px-1.5 py-px font-medium text-primary">
{versions.next}
</span>
</div>
)}

<ToastDescription className="mt-2 text-[13px] leading-relaxed text-pretty text-muted-foreground">
{t("未保存的内容请先保存,再刷新。")}
</ToastDescription>

<div className="mt-3.5 flex items-center gap-2">
<Button
size="sm"
onClick={() => window.location.reload()}
data-testid="update-notice-reload"
>
<IconRefresh data-icon="inline-start" />
{t("立即刷新")}
</Button>
<Button
size="sm"
variant="ghost"
onClick={onLater}
data-testid="update-notice-later"
>
{t("稍后")}
</Button>
</div>
</div>
</div>
</div>
)
}

/**
* 榫头从左边滑进卯眼、咬合时整块轻轻一顿 —— 只在出现时演一次,不循环(常驻的卡片一直动是干扰)。
* 颜色全走 `--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 }
}
`
70 changes: 54 additions & 16 deletions apps/web/src/lib/app-version.ts
Original file line number Diff line number Diff line change
@@ -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"

/**
* 「服务端发新版了」的检测。
*
Expand Down Expand Up @@ -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<string | null> {
type Served = { buildId: string; version: string | null }

async function fetchServed(): Promise<Served | null> {
// 懒加载失败那条路也会走到这里,那时服务器可能正在重启 —— 别让提示等一个挂住的请求。
// 手写超时而不是 `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)
}
}

Expand All @@ -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 = () => {
Expand All @@ -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()
Expand Down
6 changes: 4 additions & 2 deletions apps/web/src/routes/-error.tsx
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -37,13 +38,14 @@ export function ErrorPage({ error: thrown }: { error?: unknown }) {
return (
<div className="flex min-h-svh flex-col items-center justify-center gap-4 p-6 text-center">
<div className="space-y-1">
<h1 className="text-lg font-semibold">{t('已发布新版本')}</h1>
<h1 className="text-lg font-semibold">{t('新版本已就绪')}</h1>
<p className="max-w-md text-sm text-muted-foreground">
{t('当前页面用的还是旧版前端,刷新后继续使用。')}
</p>
</div>
<Button onClick={() => window.location.reload()} data-testid="stale-reload">
{t('刷新')}
<IconRefresh data-icon="inline-start" />
{t('立即刷新')}
</Button>
</div>
)
Expand Down
Loading
Loading