mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-11-16 23:04:24 +08:00
fix(i18n): use English runtime text and localize system UI
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import english from '@/messages/fragments/builtin-metadata.en.json';
|
||||
import chinese from '@/messages/fragments/builtin-metadata.zh-CN.json';
|
||||
import {
|
||||
localizeConfigDescription,
|
||||
localizeTemplateMetadata,
|
||||
} from './builtin-metadata';
|
||||
|
||||
describe('built-in metadata presentation', () => {
|
||||
it('localizes known descriptions in both directions without changing stored data', () => {
|
||||
const original = {
|
||||
key: 'site_name',
|
||||
description: chinese.builtinMetadata.configDescriptions.site_name,
|
||||
value: 'My site',
|
||||
};
|
||||
expect(
|
||||
localizeConfigDescription(original.key, original.description, 'en'),
|
||||
).toBe(english.builtinMetadata.configDescriptions.site_name);
|
||||
expect(
|
||||
localizeConfigDescription(original.key, 'Platform display name', 'zh-CN'),
|
||||
).toBe(original.description);
|
||||
expect(original.description).toBe(
|
||||
chinese.builtinMetadata.configDescriptions.site_name,
|
||||
);
|
||||
expect(original.value).toBe('My site');
|
||||
});
|
||||
|
||||
it('preserves custom descriptions, edited values and unknown configuration keys', () => {
|
||||
expect(
|
||||
localizeConfigDescription('site_name', 'Custom description', 'zh-CN'),
|
||||
).toBe('Custom description');
|
||||
expect(localizeConfigDescription('site_name', '', 'en')).toBe('');
|
||||
expect(
|
||||
localizeConfigDescription(
|
||||
'unknown',
|
||||
chinese.builtinMetadata.configDescriptions.site_name,
|
||||
'en',
|
||||
),
|
||||
).toBe(chinese.builtinMetadata.configDescriptions.site_name);
|
||||
});
|
||||
|
||||
it('only localizes the exact defaults of built-in templates', () => {
|
||||
const original = chinese.builtinMetadata.templates.login_email;
|
||||
expect(
|
||||
localizeTemplateMetadata(
|
||||
'login_email',
|
||||
true,
|
||||
'name',
|
||||
original.name,
|
||||
'en',
|
||||
),
|
||||
).toBe(english.builtinMetadata.templates.login_email.name);
|
||||
expect(
|
||||
localizeTemplateMetadata(
|
||||
'login_email',
|
||||
true,
|
||||
'description',
|
||||
original.description,
|
||||
'en',
|
||||
),
|
||||
).toBe(english.builtinMetadata.templates.login_email.description);
|
||||
expect(
|
||||
localizeTemplateMetadata(
|
||||
'login_email',
|
||||
false,
|
||||
'name',
|
||||
original.name,
|
||||
'en',
|
||||
),
|
||||
).toBe(original.name);
|
||||
expect(
|
||||
localizeTemplateMetadata(
|
||||
'login_email',
|
||||
true,
|
||||
'name',
|
||||
'My verification email',
|
||||
'zh-CN',
|
||||
),
|
||||
).toBe('My verification email');
|
||||
expect(
|
||||
localizeTemplateMetadata('unknown', true, 'name', original.name, 'en'),
|
||||
).toBe(original.name);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import english from '@/messages/fragments/builtin-metadata.en.json';
|
||||
import chinese from '@/messages/fragments/builtin-metadata.zh-CN.json';
|
||||
|
||||
function localizedDefault(
|
||||
value: string,
|
||||
en: string | undefined,
|
||||
zh: string | undefined,
|
||||
locale: string,
|
||||
): string {
|
||||
// Only known defaults are translated. Custom and unknown text stays intact.
|
||||
if (!en || !zh || (value !== en && value !== zh)) return value;
|
||||
return locale === 'zh-CN' ? zh : en;
|
||||
}
|
||||
|
||||
export function localizeConfigDescription(
|
||||
key: string,
|
||||
value: string,
|
||||
locale: string,
|
||||
): string {
|
||||
const en = english.builtinMetadata.configDescriptions as Record<
|
||||
string,
|
||||
string
|
||||
>;
|
||||
const zh = chinese.builtinMetadata.configDescriptions as Record<
|
||||
string,
|
||||
string
|
||||
>;
|
||||
return localizedDefault(value, en[key], zh[key], locale);
|
||||
}
|
||||
|
||||
export function localizeTemplateMetadata(
|
||||
key: string,
|
||||
isSystem: boolean,
|
||||
field: 'name' | 'description',
|
||||
value: string,
|
||||
locale: string,
|
||||
): string {
|
||||
if (!isSystem) return value;
|
||||
const en = english.builtinMetadata.templates as Record<
|
||||
string,
|
||||
{ name: string; description: string }
|
||||
>;
|
||||
const zh = chinese.builtinMetadata.templates as typeof en;
|
||||
return localizedDefault(value, en[key]?.[field], zh[key]?.[field], locale);
|
||||
}
|
||||
@@ -1,16 +1,11 @@
|
||||
export const locales = ['zh-CN', 'en'] as const;
|
||||
export const locales = ['en', 'zh-CN'] as const;
|
||||
|
||||
export type AppLocale = (typeof locales)[number];
|
||||
|
||||
export const defaultLocale: AppLocale = 'zh-CN';
|
||||
export const defaultLocale: AppLocale = 'en';
|
||||
|
||||
export const localeCookieName = 'NEXT_LOCALE';
|
||||
|
||||
export const localeLabels: Record<AppLocale, string> = {
|
||||
'zh-CN': '中文',
|
||||
en: 'English',
|
||||
};
|
||||
|
||||
export function isAppLocale(
|
||||
value: string | undefined | null,
|
||||
): value is AppLocale {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { formatDateTime, getFormattingLocale } from './format';
|
||||
|
||||
afterEach(() => {
|
||||
document.documentElement.lang = '';
|
||||
});
|
||||
|
||||
describe('locale-aware formatting', () => {
|
||||
it('uses the rendered language for dates and preserves invalid input', () => {
|
||||
document.documentElement.lang = 'en';
|
||||
expect(getFormattingLocale()).toBe('en');
|
||||
expect(formatDateTime('2026-01-15T00:00:00Z')).toContain('01/15/2026');
|
||||
document.documentElement.lang = 'zh-CN';
|
||||
expect(formatDateTime('2026-01-15T00:00:00Z')).toContain('2026/01/15');
|
||||
expect(formatDateTime('自定义文本')).toBe('自定义文本');
|
||||
});
|
||||
});
|
||||
+11
-3
@@ -1,5 +1,13 @@
|
||||
import type { AppLocale } from './config';
|
||||
import { defaultLocale } from './config';
|
||||
import { defaultLocale, normalizeLocale } from './config';
|
||||
|
||||
// Match the language currently rendered by the provider, including the initial
|
||||
// static-export render. This module also remains safe in server contexts.
|
||||
export function getFormattingLocale(): AppLocale {
|
||||
return typeof document === 'undefined'
|
||||
? defaultLocale
|
||||
: normalizeLocale(document.documentElement.lang);
|
||||
}
|
||||
|
||||
const localeToIntl: Record<AppLocale, string> = {
|
||||
'zh-CN': 'zh-CN',
|
||||
@@ -8,7 +16,7 @@ const localeToIntl: Record<AppLocale, string> = {
|
||||
|
||||
export function formatDateTime(
|
||||
dateStr: string | Date,
|
||||
locale: AppLocale = defaultLocale,
|
||||
locale: AppLocale = getFormattingLocale(),
|
||||
timeZone = 'Asia/Shanghai',
|
||||
): string {
|
||||
try {
|
||||
@@ -29,7 +37,7 @@ export function formatDateTime(
|
||||
|
||||
export function formatNumber(
|
||||
value: number,
|
||||
locale: AppLocale = defaultLocale,
|
||||
locale: AppLocale = getFormattingLocale(),
|
||||
): string {
|
||||
try {
|
||||
return new Intl.NumberFormat(localeToIntl[locale] ?? locale).format(value);
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { createTranslator, type AbstractIntlMessages } from 'next-intl';
|
||||
import { NetworkError, isCancelError } from '@/lib/services/core/errors';
|
||||
import { buildTaskPayload } from '@/lib/task-param-utils';
|
||||
import { effectiveOfflinePageHTML } from '@/lib/openflare/offline-page-templates';
|
||||
import { findGraphErrorTarget } from '@/app/(main)/waf/rules/editor/components/editor-behavior';
|
||||
import { isLogStorageDisabledMessage } from '@/app/(main)/admin/logs/components/log-storage-error';
|
||||
import { searchItems } from '@/lib/utils/search-data';
|
||||
import english from '@/messages/en.json';
|
||||
import chinese from '@/messages/zh-CN.json';
|
||||
import { getRuntimeTranslator } from './runtime';
|
||||
|
||||
afterEach(() => {
|
||||
document.cookie = 'NEXT_LOCALE=; Max-Age=0; Path=/';
|
||||
});
|
||||
|
||||
describe('imperative runtime translations', () => {
|
||||
it('recognizes disabled log storage independently of the current language', () => {
|
||||
expect(
|
||||
isLogStorageDisabledMessage(
|
||||
'Log storage is disabled; analytics are unavailable',
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isLogStorageDisabledMessage('日志存储未启用,无法查询访问日志'),
|
||||
).toBe(true);
|
||||
expect(isLogStorageDisabledMessage('Unexpected network error')).toBe(false);
|
||||
});
|
||||
it('uses the current locale when creating errors and preserves field values', () => {
|
||||
document.cookie = 'NEXT_LOCALE=en; Path=/';
|
||||
expect(new NetworkError().message).toBe(
|
||||
'Network connection failed; check your network',
|
||||
);
|
||||
const result = buildTaskPayload(
|
||||
[
|
||||
{
|
||||
name: 'value',
|
||||
label: '自定义名称',
|
||||
type: 'number',
|
||||
required: false,
|
||||
placeholder: '',
|
||||
description: '',
|
||||
},
|
||||
],
|
||||
{ value: 'invalid' },
|
||||
);
|
||||
expect(result.error).toBe('自定义名称 must be a valid number');
|
||||
document.cookie = 'NEXT_LOCALE=zh-CN; Path=/';
|
||||
expect(new NetworkError().message).toBe('网络连接失败,请检查您的网络');
|
||||
});
|
||||
|
||||
it('recognizes historical canceled requests independently of the current locale', () => {
|
||||
document.cookie = 'NEXT_LOCALE=en; Path=/';
|
||||
expect(isCancelError(new Error('请求已被取消'))).toBe(true);
|
||||
document.cookie = 'NEXT_LOCALE=zh-CN; Path=/';
|
||||
expect(isCancelError(new Error('Request canceled'))).toBe(true);
|
||||
expect(isCancelError(new Error('Other error'))).toBe(false);
|
||||
});
|
||||
|
||||
it('selects offline HTML at use time without rewriting custom HTML', () => {
|
||||
document.cookie = 'NEXT_LOCALE=en; Path=/';
|
||||
expect(effectiveOfflinePageHTML('')).toContain('lang="en"');
|
||||
document.cookie = 'NEXT_LOCALE=zh-CN; Path=/';
|
||||
expect(effectiveOfflinePageHTML('')).toContain('lang="zh-CN"');
|
||||
const custom = '<p>用户内容</p>';
|
||||
expect(effectiveOfflinePageHTML(custom)).toBe(custom);
|
||||
});
|
||||
|
||||
it('finds graph targets in both current English and historical Chinese errors', () => {
|
||||
for (const message of [
|
||||
'Node node-1 contains invalid IP',
|
||||
'节点 node-1 包含无效 IP',
|
||||
]) {
|
||||
expect(findGraphErrorTarget(new Error(message), ['node-1'], [])).toEqual({
|
||||
kind: 'node',
|
||||
id: 'node-1',
|
||||
});
|
||||
}
|
||||
for (const message of [
|
||||
'Edge edge-1 has invalid source',
|
||||
'边 ID edge-1 的端点无效',
|
||||
]) {
|
||||
expect(findGraphErrorTarget(new Error(message), [], ['edge-1'])).toEqual({
|
||||
kind: 'edge',
|
||||
id: 'edge-1',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps Chinese search aliases in the Chinese catalog', () => {
|
||||
const zh = createTranslator({
|
||||
locale: 'zh-CN',
|
||||
messages: chinese as AbstractIntlMessages,
|
||||
namespace: 'layout',
|
||||
});
|
||||
const en = createTranslator({
|
||||
locale: 'en',
|
||||
messages: english as AbstractIntlMessages,
|
||||
namespace: 'layout',
|
||||
});
|
||||
expect(
|
||||
searchItems('日志', true, zh).some((item) => item.url === '/admin/logs'),
|
||||
).toBe(true);
|
||||
expect(
|
||||
searchItems('terminal', true, en).some(
|
||||
(item) => item.url === '/admin/logs',
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('formats interpolated messages in both catalogs', () => {
|
||||
for (const locale of ['en', 'zh-CN'] as const) {
|
||||
const t = getRuntimeTranslator(locale);
|
||||
for (const [key, text] of Object.entries(english.runtime)) {
|
||||
if (/\{value\d+\}/.test(text)) {
|
||||
const translated = t(key as keyof typeof english.runtime, {
|
||||
value0: 'CUSTOM',
|
||||
value1: 'VALUE',
|
||||
value2: 42,
|
||||
});
|
||||
expect(translated).toContain('CUSTOM');
|
||||
expect(translated).not.toContain('{value0}');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
'use client';
|
||||
|
||||
import { createTranslator, type useTranslations } from 'next-intl';
|
||||
import english from '@/messages/fragments/runtime.en.json';
|
||||
import chinese from '@/messages/fragments/runtime.zh-CN.json';
|
||||
import { resolveClientLocale } from './client';
|
||||
import type { AppLocale } from './config';
|
||||
|
||||
export type RuntimeTranslator = ReturnType<typeof useTranslations>;
|
||||
type RuntimeKey = keyof typeof english.runtime;
|
||||
|
||||
const translators = {
|
||||
en: createTranslator({
|
||||
locale: 'en',
|
||||
messages: english,
|
||||
namespace: 'runtime',
|
||||
}),
|
||||
'zh-CN': createTranslator({
|
||||
locale: 'zh-CN',
|
||||
messages: chinese,
|
||||
namespace: 'runtime',
|
||||
}),
|
||||
};
|
||||
|
||||
export function getRuntimeTranslator(locale: AppLocale) {
|
||||
return translators[locale];
|
||||
}
|
||||
|
||||
// Imperative browser code (network errors, form utilities) has no React hook
|
||||
// context. Resolve the current preference when creating a message, not at import.
|
||||
export const runtimeText = Object.assign(
|
||||
(key: RuntimeKey, values?: Record<string, string | number>) =>
|
||||
translators[resolveClientLocale()](key, values),
|
||||
{
|
||||
raw: (key: RuntimeKey): string =>
|
||||
translators[resolveClientLocale()].raw(key),
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user