Files
MonkeyCode/monkeyai/web/scripts/check-localization.mjs
T
monster 32251ce5be feat: 完善官网与管理端十语言支持及 RTL 适配
补充官网多语言静态页面、管理端词条和动态提示,统一相关资源用量展示,保留表格导出等现有修改。

修正 RTL 布局与字体回退,并加入翻译契约、文案宽度、逻辑样式及浏览器回归检查。
2026-11-27 10:58:49 +08:00

203 lines
12 KiB
JavaScript

import assert from "node:assert/strict"
import { readFile, stat } from "node:fs/promises"
import path from "node:path"
import { fileURLToPath } from "node:url"
import { chromium } from "playwright-core"
import { LANGUAGE_OPTIONS, LANGUAGE_STORAGE_KEY } from "../src/i18n/language.ts"
import { zhCN } from "../src/i18n/locales/zh-CN.ts"
if (!process.env.CHROME_BIN) throw new Error("请设置 CHROME_BIN,并先执行 npm run build")
const dist = fileURLToPath(new URL("../dist/", import.meta.url))
await stat(path.join(dist, "index.html"))
const origin = "http://localization.test"
const browser = await chromium.launch({
executablePath: process.env.CHROME_BIN,
args: ["--no-sandbox", "--disable-dev-shm-usage"],
})
const languages = process.env.LANGUAGE
? LANGUAGE_OPTIONS.filter(({ value }) => value === process.env.LANGUAGE)
: LANGUAGE_OPTIONS
assert.ok(languages.length, "LANGUAGE 必须是支持的语言代码")
const widths = process.env.WIDTH ? [Number(process.env.WIDTH)] : [1440, 390, 320]
const dictionaries = Object.fromEntries(await Promise.all(languages.map(async ({ value }) =>
[value, Object.values(await import("../src/i18n/locales/" + value + ".ts"))[0]]
)))
const types = {
".html": "text/html", ".js": "text/javascript", ".css": "text/css",
".woff2": "font/woff2", ".svg": "image/svg+xml", ".png": "image/png",
".webp": "image/webp",
}
async function fixture(language, width, authenticated = true) {
const context = await browser.newContext({
viewport: { width, height: 900 }, locale: language, reducedMotion: "reduce",
})
await context.addInitScript(({ key, language }) => {
localStorage.setItem(key, language)
}, { key: LANGUAGE_STORAGE_KEY, language })
const state = { failNetwork: false, networkReads: 0 }
const user = { id: "admin", name: "测试管理员", email: "admin@example.com", role: "admin", status: "active", joined_at: "2026-01-01T00:00:00Z" }
await context.route("**/*", async (route) => {
const request = route.request()
const endpoint = new URL(request.url()).pathname
if (endpoint.startsWith("/api/")) {
assert.equal(request.method(), "GET", "此检查不应发起写请求:" + endpoint)
let body = { items: [] }
if (endpoint.endsWith("/session")) body = { authenticated, user: authenticated ? user : null }
else if (endpoint.endsWith("/branding")) body = { product_name: "测试团队" }
else if (endpoint.endsWith("/license/status")) body = { state: "valid" }
else if (endpoint.endsWith("/methods")) body = { password_enabled: true, email_code_enabled: true, email_code_auto_registration_enabled: false }
else if (endpoint.endsWith("/providers")) body = { providers: [] }
else if (endpoint.endsWith("/users")) body = { users: [user] }
else if (endpoint.endsWith("/groups")) body = { groups: [{
id: "00000000-0000-0000-0000-000000000000", parent_id: null,
name: "测试团队", member_ids: [user.id], actions: ["add-subgroup"], allow_add_members: true,
}] }
else if (/\/settings\/(model_network|mcp)$/.test(endpoint)) {
state.networkReads++
if (state.failNetwork) return route.fulfill({ status: 503, json: {} })
body = { value: { blocked_cidrs: [] } }
}
return route.fulfill({ json: body })
}
let file = path.resolve(dist, "." + endpoint)
assert.ok(file.startsWith(dist), "静态资源路径必须位于构建目录内")
if (!(await stat(file).catch(() => null))?.isFile()) file = path.join(dist, "index.html")
return route.fulfill({ contentType: types[path.extname(file)] || "application/octet-stream", body: await readFile(file) })
})
const page = await context.newPage()
page.setDefaultTimeout(10000)
const errors = []
page.on("pageerror", (error) => errors.push(error.message))
return { context, page, state, errors }
}
async function bounds(page, label) {
const size = await page.evaluate(() => ({
actual: document.documentElement.scrollWidth, viewport: innerWidth,
}))
assert.ok(size.actual <= size.viewport + 1, label + ":页面出现水平溢出 " + JSON.stringify(size))
}
async function unclipped(locator, label) {
await locator.first().waitFor({ state: "visible" })
const clipped = await locator.evaluateAll((elements) => elements
.filter((element) => element.checkVisibility() && element.getBoundingClientRect().width > 0)
.filter((element) => element.scrollWidth > element.clientWidth + 1)
.map((element) => ({ text: element.textContent, actual: element.scrollWidth, available: element.clientWidth })))
assert.deepEqual(clipped, [], label + ":文案被截断")
}
async function switchLanguage(page, from, language) {
await page.getByRole("button", { name: from.language.change, exact: true }).click()
await page.getByRole("menuitemradio", { name: language.label, exact: true }).click()
await page.waitForFunction((language) => document.documentElement.lang === language, language.value)
assert.equal(await page.locator("html").getAttribute("dir"), language.value === "ar" ? "rtl" : "ltr")
assert.equal(await page.evaluate((key) => localStorage.getItem(key), LANGUAGE_STORAGE_KEY), language.value)
}
try {
for (const width of widths) {
for (const language of languages) {
const dictionary = dictionaries[language.value]
const label = language.value + " / " + width
const { context, page, errors } = await fixture(language.value, width)
try {
await page.goto(origin + "/admin/settings/security")
await page.getByText(dictionary.pages.security.model.title, { exact: true }).waitFor()
await page.evaluate(() => document.fonts.ready)
assert.equal(await page.locator("html").getAttribute("lang"), language.value)
assert.equal(await page.locator("html").getAttribute("dir"), language.value === "ar" ? "rtl" : "ltr")
await bounds(page, label)
if (width < 768) await page.locator('[data-slot="sidebar-trigger"]').click()
const sidebar = page.locator('[data-slot="sidebar-content"]')
await sidebar.waitFor()
for (const section of ["statistics", "usageRecords", "aiResources", "billingManagement", "systemSettings"]) {
const trigger = sidebar.getByRole("button", { name: dictionary.sections[section], exact: true })
if (await trigger.getAttribute("aria-expanded") !== "true") await trigger.click()
await unclipped(sidebar.locator('[data-slot="sidebar-menu-sub-button"] > span'), label + " / " + section)
await unclipped(trigger.locator(":scope > span"), label + " / 主导航")
}
if (width < 768) {
const box = await page.locator('[data-mobile="true"]').boundingBox()
assert.ok(box && box.x >= -1 && box.x + box.width <= width + 1, label + ":移动导航越界")
if (language.value === "ar") assert.ok(Math.abs(box.x + box.width - width) <= 1, "RTL 导航应位于右侧")
await page.keyboard.press("Escape")
} else {
assert.equal(await page.locator('[data-slot="sidebar-container"]').getAttribute("data-side"), language.value === "ar" ? "right" : "left")
}
await page.goto(origin + "/admin/settings/members")
await page.getByRole("button", { name: dictionary.pages.membersAndGroups.bulk.addMember, exact: true }).click()
const dialog = page.getByRole("dialog")
await dialog.waitFor()
await dialog.getByRole("tab", { name: dictionary.pages.membersAndGroups.bulk.addOne, exact: true }).waitFor()
await unclipped(dialog.getByRole("tab"), label + " / 添加成员选项")
await dialog.getByRole("tab", { name: dictionary.pages.membersAndGroups.bulk.addMany, exact: true }).click()
await unclipped(dialog.getByRole("tab"), label + " / 批量添加选项")
const dialogBox = await dialog.boundingBox()
assert.ok(dialogBox && dialogBox.x >= -1 && dialogBox.x + dialogBox.width <= width + 1, label + ":成员弹窗越界")
const close = dialog.locator('button[data-slot="dialog-close"]')
const closeBox = await close.boundingBox()
assert.equal(await dialog.evaluate((element) => getComputedStyle(element).direction), language.value === "ar" ? "rtl" : "ltr", label + ":弹窗方向错误")
if (language.value === "ar") {
for (const target of [page.locator("body"), dialog.locator('[data-slot="dialog-title"]')]) {
const fontFamily = await target.evaluate((element) => getComputedStyle(element).fontFamily)
assert.ok(fontFamily.includes("Noto Sans Arabic Variable") && fontFamily.includes("Noto Sans SC Variable"), label + ":阿拉伯语及中文回退字体缺失;" + fontFamily)
}
}
const centeredClose = closeBox.x + closeBox.width / 2 - (dialogBox.x + dialogBox.width / 2)
assert.ok(language.value === "ar" ? centeredClose < 0 : centeredClose > 0,
label + ":关闭按钮应处于文字结束侧;" + JSON.stringify(await close.evaluate((element) => {
const style = getComputedStyle(element)
return { direction: style.direction, left: style.left, right: style.right, insetInlineEnd: style.insetInlineEnd }
})))
await bounds(page, label + " / 成员弹窗")
if (process.env.SCREENSHOT_DIR && width === 320 && ["de-DE", "ar"].includes(language.value)) {
await page.screenshot({ path: path.join(process.env.SCREENSHOT_DIR, "localization-" + language.value + "-320.png"), animations: "disabled" })
}
assert.deepEqual(errors, [], label + ":浏览器运行错误")
console.log("通过:导航、成员弹窗及方向 / " + label)
} catch (error) {
console.error("失败场景:" + label, { pageErrors: errors, text: (await page.locator("body").innerText()).slice(0, 1200) })
throw error
} finally { await context.close() }
}
}
for (const language of languages) {
const dictionary = dictionaries[language.value]
const { context, page, errors } = await fixture("zh-CN", 390, false)
try {
await page.goto(origin + "/login?oauth_error=admin_role_required")
const toast = page.locator('ol[aria-live="polite"] > li')
await toast.getByText(zhCN.login.oauthAdminRequired, { exact: true }).waitFor()
await toast.evaluate((element) => { element.dataset.localizationProbe = "same-toast" })
await switchLanguage(page, zhCN, language)
await toast.getByText(dictionary.login.oauthAdminRequired, { exact: true }).waitFor()
assert.equal(await toast.count(), 1, "切换语言不应重复创建提示")
assert.equal(await toast.getAttribute("data-localization-probe"), "same-toast", "应更新已存在的提示而非替换")
await bounds(page, language.value + " / 登录")
assert.deepEqual(errors, [], language.value + ":登录页面运行错误")
console.log("通过:已保存提示即时切换 / " + language.value)
} finally { await context.close() }
const saved = await fixture("zh-CN", 390)
try {
saved.state.failNetwork = true
await saved.page.goto(origin + "/admin/settings/security")
const alerts = saved.page.getByRole("alert")
await alerts.first().getByText(zhCN.webUi.requestFailed, { exact: true }).waitFor()
assert.equal(await alerts.count(), 2)
const reads = saved.state.networkReads
await switchLanguage(saved.page, zhCN, language)
await alerts.first().getByText(dictionary.webUi.requestFailed, { exact: true }).waitFor()
assert.equal(await alerts.last().innerText(), dictionary.webUi.requestFailed)
assert.equal(saved.state.networkReads, reads, "更新已保存错误不应重新请求接口")
assert.deepEqual(saved.errors, [])
console.log("通过:已保存错误无重新请求切换 / " + language.value)
} finally { await saved.context.close() }
}
console.log("本轮验收范围:十语言导航和成员弹窗、窄屏与 RTL、已保存提示和错误;使用模拟接口,不代表全站业务端到端验收。")
} finally {
await browser.close()
}