mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-11-16 23:04:24 +08:00
feat(i18n): add Russian UI and harden localization
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import english from '@/messages/fragments/languages.en.json';
|
||||
import russian from '@/messages/fragments/languages.ru.json';
|
||||
import { createLocaleBootstrapScript } from './bootstrap';
|
||||
import { resolveClientLocale } from './client';
|
||||
|
||||
afterEach(async () => {
|
||||
document.cookie = 'NEXT_LOCALE=; Max-Age=0; Path=/';
|
||||
document.documentElement.removeAttribute('data-locale-pending');
|
||||
document.getElementById('locale-load-fallback')?.remove();
|
||||
await Promise.resolve();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('static locale first paint', () => {
|
||||
function setupFallback() {
|
||||
const fallback = document.createElement('div');
|
||||
fallback.id = 'locale-load-fallback';
|
||||
fallback.hidden = true;
|
||||
const message = document.createElement('p');
|
||||
message.setAttribute('data-locale-error-message', '');
|
||||
message.textContent = english.languageLoading.failed;
|
||||
const retry = document.createElement('button');
|
||||
retry.textContent = english.languageLoading.reload;
|
||||
fallback.append(message, retry);
|
||||
document.body.append(fallback);
|
||||
document.cookie = 'NEXT_LOCALE=ru; Path=/';
|
||||
return fallback;
|
||||
}
|
||||
|
||||
it('shows an independent Russian recovery action if hydration never completes', () => {
|
||||
vi.useFakeTimers();
|
||||
const fallback = setupFallback();
|
||||
new Function(createLocaleBootstrapScript('en'))();
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(fallback.hidden).toBe(false);
|
||||
expect(fallback.textContent).toContain(russian.languageLoading.failed);
|
||||
expect(fallback.querySelector('button')?.textContent).toBe(
|
||||
russian.languageLoading.reload,
|
||||
);
|
||||
expect(document.documentElement.hasAttribute('data-locale-pending')).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('shows recovery immediately when an application script fails', () => {
|
||||
vi.useFakeTimers();
|
||||
const fallback = setupFallback();
|
||||
new Function(createLocaleBootstrapScript('en'))();
|
||||
const script = document.createElement('script');
|
||||
document.body.append(script);
|
||||
script.dispatchEvent(new Event('error'));
|
||||
script.remove();
|
||||
expect(fallback.hidden).toBe(false);
|
||||
});
|
||||
|
||||
it('cancels the deadline when the provider reveals the localized page', async () => {
|
||||
vi.useFakeTimers();
|
||||
const fallback = setupFallback();
|
||||
new Function(createLocaleBootstrapScript('en'))();
|
||||
document.documentElement.removeAttribute('data-locale-pending');
|
||||
await Promise.resolve();
|
||||
vi.advanceTimersByTime(60000);
|
||||
expect(fallback.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it('waits for the body when a script fails during HTML parsing', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.spyOn(document, 'readyState', 'get').mockReturnValue('loading');
|
||||
document.cookie = 'NEXT_LOCALE=ru; Path=/';
|
||||
new Function(createLocaleBootstrapScript('en'))();
|
||||
const script = document.createElement('script');
|
||||
document.head.append(script);
|
||||
script.dispatchEvent(new Event('error'));
|
||||
script.remove();
|
||||
expect(document.documentElement.hasAttribute('data-locale-pending')).toBe(
|
||||
true,
|
||||
);
|
||||
const fallback = setupFallback();
|
||||
document.dispatchEvent(new Event('DOMContentLoaded'));
|
||||
expect(fallback.hidden).toBe(false);
|
||||
expect(fallback.textContent).toContain(russian.languageLoading.failed);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['ru', ['en-US'], 'ru', true],
|
||||
['en', ['ru-RU'], 'en', false],
|
||||
['', ['de-DE', 'ru-RU'], 'ru', true],
|
||||
['', ['de-DE', 'en-US'], 'en', false],
|
||||
['zh-CN', ['en-US'], 'zh-CN', true],
|
||||
['unsupported', ['ru-RU'], 'en', false],
|
||||
['%broken', ['ru-RU'], 'ru', true],
|
||||
] as const)(
|
||||
'matches provider resolution for cookie %s and browser %s',
|
||||
(cookie, languages, locale, pending) => {
|
||||
document.cookie = `NEXT_LOCALE=${cookie}; Path=/`;
|
||||
Object.defineProperty(navigator, 'languages', {
|
||||
value: languages,
|
||||
configurable: true,
|
||||
});
|
||||
new Function(createLocaleBootstrapScript('en'))();
|
||||
expect(resolveClientLocale()).toBe(locale);
|
||||
expect(document.documentElement.hasAttribute('data-locale-pending')).toBe(
|
||||
pending,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
defaultLocale,
|
||||
localeCookieName,
|
||||
locales,
|
||||
type AppLocale,
|
||||
} from './config';
|
||||
import english from '@/messages/fragments/languages.en.json';
|
||||
import chinese from '@/messages/fragments/languages.zh-CN.json';
|
||||
import russian from '@/messages/fragments/languages.ru.json';
|
||||
|
||||
// Runs in <head>, before static English markup can paint. Keep this script
|
||||
// self-contained: it must not depend on a loaded application bundle.
|
||||
export function createLocaleBootstrapScript(serverLocale: AppLocale): string {
|
||||
const settings = JSON.stringify({
|
||||
serverLocale,
|
||||
defaultLocale,
|
||||
localeCookieName,
|
||||
locales,
|
||||
fallbacks: {
|
||||
en: english.languageLoading,
|
||||
'zh-CN': chinese.languageLoading,
|
||||
ru: russian.languageLoading,
|
||||
},
|
||||
}).replaceAll('<', '\\u003c');
|
||||
return String.raw`(() => {
|
||||
const settings = ${settings};
|
||||
const normalize = (input) => {
|
||||
const family = input.trim().replaceAll('_', '-').toLowerCase().split('-')[0];
|
||||
return settings.locales.find((locale) => locale.toLowerCase().split('-')[0] === family);
|
||||
};
|
||||
const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith(settings.localeCookieName + '='));
|
||||
let preferred;
|
||||
if (cookie) {
|
||||
try {
|
||||
const value = decodeURIComponent(cookie.slice(settings.localeCookieName.length + 1));
|
||||
if (value) preferred = normalize(value) || settings.defaultLocale;
|
||||
} catch { /* Invalid cookie: use browser preference, as the provider does. */ }
|
||||
}
|
||||
if (!preferred) {
|
||||
for (const language of navigator.languages?.length ? navigator.languages : [navigator.language]) {
|
||||
preferred = normalize(language || '');
|
||||
if (preferred) break;
|
||||
}
|
||||
}
|
||||
if ((preferred || settings.defaultLocale) !== settings.serverLocale) {
|
||||
const root = document.documentElement;
|
||||
root.setAttribute('data-locale-pending', '');
|
||||
const showFailure = () => {
|
||||
if (!root.hasAttribute('data-locale-pending')) return;
|
||||
const fallback = document.getElementById('locale-load-fallback');
|
||||
if (!fallback) {
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', showFailure, {once: true});
|
||||
} else {
|
||||
root.removeAttribute('data-locale-pending');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!fallback.hidden) return;
|
||||
const copy = settings.fallbacks[preferred || settings.defaultLocale];
|
||||
const message = fallback.querySelector('[data-locale-error-message]');
|
||||
const retry = fallback.querySelector('button');
|
||||
if (message) message.textContent = copy.failed;
|
||||
if (retry) {
|
||||
retry.textContent = copy.reload;
|
||||
retry.addEventListener('click', () => window.location.reload(), {once: true});
|
||||
}
|
||||
fallback.hidden = false;
|
||||
};
|
||||
const timeout = setTimeout(showFailure, 10000);
|
||||
const onError = (event) => {
|
||||
if (event.target?.tagName === 'SCRIPT') showFailure();
|
||||
};
|
||||
window.addEventListener('error', onError, true);
|
||||
const observer = new MutationObserver(() => {
|
||||
if (!root.hasAttribute('data-locale-pending')) {
|
||||
clearTimeout(timeout);
|
||||
window.removeEventListener('error', onError, true);
|
||||
observer.disconnect();
|
||||
}
|
||||
});
|
||||
observer.observe(root, {attributes: true, attributeFilter: ['data-locale-pending']});
|
||||
}
|
||||
})();`;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
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 russian from '@/messages/fragments/builtin-metadata.ru.json';
|
||||
import {
|
||||
localizeConfigDescription,
|
||||
localizeTemplateMetadata,
|
||||
@@ -23,6 +24,16 @@ describe('built-in metadata presentation', () => {
|
||||
chinese.builtinMetadata.configDescriptions.site_name,
|
||||
);
|
||||
expect(original.value).toBe('My site');
|
||||
expect(
|
||||
localizeConfigDescription(original.key, original.description, 'ru'),
|
||||
).toBe(russian.builtinMetadata.configDescriptions.site_name);
|
||||
expect(
|
||||
localizeConfigDescription(
|
||||
original.key,
|
||||
russian.builtinMetadata.configDescriptions.site_name,
|
||||
'en',
|
||||
),
|
||||
).toBe(english.builtinMetadata.configDescriptions.site_name);
|
||||
});
|
||||
|
||||
it('preserves custom descriptions, edited values and unknown configuration keys', () => {
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import english from '@/messages/fragments/builtin-metadata.en.json';
|
||||
import chinese from '@/messages/fragments/builtin-metadata.zh-CN.json';
|
||||
import russian from '@/messages/fragments/builtin-metadata.ru.json';
|
||||
|
||||
function localizedDefault(
|
||||
value: string,
|
||||
en: string | undefined,
|
||||
zh: string | undefined,
|
||||
ru: 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;
|
||||
if (!en || !zh || !ru || ![en, zh, ru].includes(value)) return value;
|
||||
return locale === 'zh-CN' ? zh : locale === 'ru' ? ru : en;
|
||||
}
|
||||
|
||||
export function localizeConfigDescription(
|
||||
@@ -25,7 +27,8 @@ export function localizeConfigDescription(
|
||||
string,
|
||||
string
|
||||
>;
|
||||
return localizedDefault(value, en[key], zh[key], locale);
|
||||
const ru = russian.builtinMetadata.configDescriptions as typeof en;
|
||||
return localizedDefault(value, en[key], zh[key], ru[key], locale);
|
||||
}
|
||||
|
||||
export function localizeTemplateMetadata(
|
||||
@@ -41,5 +44,12 @@ export function localizeTemplateMetadata(
|
||||
{ name: string; description: string }
|
||||
>;
|
||||
const zh = chinese.builtinMetadata.templates as typeof en;
|
||||
return localizedDefault(value, en[key]?.[field], zh[key]?.[field], locale);
|
||||
const ru = russian.builtinMetadata.templates as typeof en;
|
||||
return localizedDefault(
|
||||
value,
|
||||
en[key]?.[field],
|
||||
zh[key]?.[field],
|
||||
ru[key]?.[field],
|
||||
locale,
|
||||
);
|
||||
}
|
||||
|
||||
+11
-2
@@ -17,7 +17,11 @@ function readCookie(name: string): string | null {
|
||||
.map((part) => part.trim())
|
||||
.find((part) => part.startsWith(`${name}=`));
|
||||
if (!match) return null;
|
||||
return decodeURIComponent(match.slice(name.length + 1));
|
||||
try {
|
||||
return decodeURIComponent(match.slice(name.length + 1));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getClientLocalePreference(): AppLocale | null {
|
||||
@@ -35,7 +39,12 @@ export function detectBrowserLocale(): AppLocale {
|
||||
: [navigator.language];
|
||||
for (const lang of languages) {
|
||||
const lower = (lang ?? '').toLowerCase();
|
||||
if (lower.startsWith('zh') || lower.startsWith('en')) {
|
||||
if (
|
||||
lower.startsWith('zh') ||
|
||||
lower.startsWith('en') ||
|
||||
lower === 'ru' ||
|
||||
lower.startsWith('ru-')
|
||||
) {
|
||||
return normalizeLocale(lang);
|
||||
}
|
||||
}
|
||||
|
||||
+12
-4
@@ -1,4 +1,4 @@
|
||||
export const locales = ['en', 'zh-CN'] as const;
|
||||
export const locales = ['en', 'zh-CN', 'ru'] as const;
|
||||
|
||||
export type AppLocale = (typeof locales)[number];
|
||||
|
||||
@@ -9,7 +9,7 @@ export const localeCookieName = 'NEXT_LOCALE';
|
||||
export function isAppLocale(
|
||||
value: string | undefined | null,
|
||||
): value is AppLocale {
|
||||
return value === 'zh-CN' || value === 'en';
|
||||
return value === 'zh-CN' || value === 'en' || value === 'ru';
|
||||
}
|
||||
|
||||
/** Normalize BCP 47 / browser tags into a supported app locale. */
|
||||
@@ -29,6 +29,9 @@ export function normalizeLocale(input?: string | null): AppLocale {
|
||||
if (lower === 'en' || lower.startsWith('en-')) {
|
||||
return 'en';
|
||||
}
|
||||
if (lower === 'ru' || lower.startsWith('ru-')) {
|
||||
return 'ru';
|
||||
}
|
||||
return defaultLocale;
|
||||
}
|
||||
|
||||
@@ -46,14 +49,19 @@ export function pickLocaleFromAcceptLanguage(
|
||||
const q = qParam ? Number.parseFloat(qParam.split('=')[1] ?? '1') : 1;
|
||||
return { tag: tag?.trim() ?? '', q: Number.isFinite(q) ? q : 0 };
|
||||
})
|
||||
.filter((c) => c.tag)
|
||||
.filter((c) => c.tag && c.q > 0)
|
||||
.sort((a, b) => b.q - a.q);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const normalized = normalizeLocale(candidate.tag);
|
||||
// Only accept if the raw tag roughly matches a supported family
|
||||
const lower = candidate.tag.toLowerCase();
|
||||
if (lower.startsWith('zh') || lower.startsWith('en')) {
|
||||
if (
|
||||
lower.startsWith('zh') ||
|
||||
lower.startsWith('en') ||
|
||||
lower === 'ru' ||
|
||||
lower.startsWith('ru-')
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { formatDateTime, getFormattingLocale } from './format';
|
||||
import { formatDateTime, formatNumber, getFormattingLocale } from './format';
|
||||
|
||||
afterEach(() => {
|
||||
document.documentElement.lang = '';
|
||||
@@ -12,6 +12,11 @@ describe('locale-aware formatting', () => {
|
||||
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');
|
||||
document.documentElement.lang = 'ru';
|
||||
expect(formatDateTime('2026-01-15T00:00:00Z')).toContain('15.01.2026');
|
||||
expect(formatNumber(1234.5)).toBe(
|
||||
new Intl.NumberFormat('ru-RU').format(1234.5),
|
||||
);
|
||||
expect(formatDateTime('自定义文本')).toBe('自定义文本');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ export function getFormattingLocale(): AppLocale {
|
||||
const localeToIntl: Record<AppLocale, string> = {
|
||||
'zh-CN': 'zh-CN',
|
||||
en: 'en-US',
|
||||
ru: 'ru-RU',
|
||||
};
|
||||
|
||||
export function formatDateTime(
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { messageContractTokens } from '../scripts/message-contract.mjs';
|
||||
import english from '@/messages/en.json';
|
||||
import chinese from '@/messages/zh-CN.json';
|
||||
import russian from '@/messages/ru.json';
|
||||
|
||||
describe('translation rendering contracts', () => {
|
||||
it('distinguishes translated renderer identifiers from translated prose', () => {
|
||||
const source = '$title <websites>Websites</websites> $content';
|
||||
expect(
|
||||
messageContractTokens('$title <websites>Сайты</websites> $content'),
|
||||
).toEqual(messageContractTokens(source));
|
||||
expect(
|
||||
messageContractTokens('$заголовок <websites>Сайты</websites> $content'),
|
||||
).not.toEqual(messageContractTokens(source));
|
||||
expect(
|
||||
messageContractTokens('$title <веб-сайты>Сайты</веб-сайты> $content'),
|
||||
).not.toEqual(messageContractTokens(source));
|
||||
});
|
||||
|
||||
it('keeps examples accepted by rate and duration validators copyable', () => {
|
||||
const contracts = {
|
||||
'proxyRoutes.rateLimitPlaceholder': ['512k', '1m'],
|
||||
'proxyRoutes.rateLimitHint': ['512k', '1m'],
|
||||
'proxyRoutes.reqLimitPlaceholder': ['10r/s', '100r/m'],
|
||||
'proxyRoutes.reqLimitHint': ['10r/s', '100r/m'],
|
||||
'proxyRoutes.validation.invalidLimitReq': ['10r/s', '100r/m'],
|
||||
'rateLimits.config.limitRateHint': ['512k', '1m'],
|
||||
'rateLimits.config.reqPerIpHint': ['10r/s', '100r/m'],
|
||||
'rateLimits.config.invalidReq': ['10r/s', '100r/m'],
|
||||
'builtinMetadata.configDescriptions.openresty_default_limit_req_per_ip': [
|
||||
'10r/s',
|
||||
'100r/m',
|
||||
],
|
||||
};
|
||||
for (const [locale, messages] of Object.entries({
|
||||
en: english,
|
||||
'zh-CN': chinese,
|
||||
ru: russian,
|
||||
})) {
|
||||
for (const [key, tokens] of Object.entries(contracts)) {
|
||||
let value: unknown = messages;
|
||||
for (const part of key.split('.'))
|
||||
value =
|
||||
value && typeof value === 'object'
|
||||
? (value as Record<string, unknown>)[part]
|
||||
: undefined;
|
||||
for (const token of tokens)
|
||||
expect(value, `${locale}:${key}`).toContain(token);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
let proxy: typeof import('../proxy').proxy;
|
||||
beforeAll(async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('WAVELET_RATE_LIMIT_ENABLED', 'true');
|
||||
({ proxy } = await import('../proxy'));
|
||||
});
|
||||
afterAll(() => {
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe('localized proxy rate limits', () => {
|
||||
it.each([
|
||||
['ru', 'en', 'Слишком много запросов. Повторите через 5 секунд.'],
|
||||
['en', 'ru', 'Too many requests; retry in 5 seconds'],
|
||||
[
|
||||
'',
|
||||
'de,ru-RU;q=0.9,en;q=0.8',
|
||||
'Слишком много запросов. Повторите через 5 секунд.',
|
||||
],
|
||||
])(
|
||||
'prefers cookie %s over Accept-Language %s',
|
||||
async (cookie, language, message) => {
|
||||
const request = new NextRequest('http://localhost/api/v1/oauth/login', {
|
||||
headers: {
|
||||
cookie: `NEXT_LOCALE=${cookie}`,
|
||||
'accept-language': language,
|
||||
'x-real-ip': `review-${cookie}-${language}`,
|
||||
},
|
||||
});
|
||||
expect(proxy(request).status).toBe(200);
|
||||
const limited = proxy(request);
|
||||
expect(limited.status).toBe(429);
|
||||
expect(limited.headers.get('retry-after')).toBe('5');
|
||||
expect(await limited.json()).toEqual({
|
||||
error_code: 'RATE_LIMITED',
|
||||
error_msg: message,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createTranslator } from 'next-intl';
|
||||
import english from '@/messages/fragments/runtime.en.json';
|
||||
import chinese from '@/messages/fragments/runtime.zh-CN.json';
|
||||
import russian from '@/messages/fragments/runtime.ru.json';
|
||||
import type { AppLocale } from './config';
|
||||
|
||||
export 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',
|
||||
}),
|
||||
ru: createTranslator({
|
||||
locale: 'ru',
|
||||
messages: russian,
|
||||
namespace: 'runtime',
|
||||
}),
|
||||
};
|
||||
|
||||
export function getRuntimeTranslator(locale: AppLocale) {
|
||||
return translators[locale];
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { isLogStorageDisabledMessage } from '@/app/(main)/admin/logs/components/
|
||||
import { searchItems } from '@/lib/utils/search-data';
|
||||
import english from '@/messages/en.json';
|
||||
import chinese from '@/messages/zh-CN.json';
|
||||
import { locales } from './config';
|
||||
import { getRuntimeTranslator } from './runtime';
|
||||
|
||||
afterEach(() => {
|
||||
@@ -78,6 +79,7 @@ describe('imperative runtime translations', () => {
|
||||
}
|
||||
for (const message of [
|
||||
'Edge edge-1 has invalid source',
|
||||
'Ребро edge-1 ссылается на отсутствующий исходный узел other',
|
||||
'边 ID edge-1 的端点无效',
|
||||
]) {
|
||||
expect(findGraphErrorTarget(new Error(message), [], ['edge-1'])).toEqual({
|
||||
@@ -108,17 +110,17 @@ describe('imperative runtime translations', () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('formats interpolated messages in both catalogs', () => {
|
||||
for (const locale of ['en', 'zh-CN'] as const) {
|
||||
it('formats interpolated messages in all catalogs', () => {
|
||||
for (const locale of locales) {
|
||||
const t = getRuntimeTranslator(locale);
|
||||
for (const [key, text] of Object.entries(english.runtime)) {
|
||||
if (/\{value\d+\}/.test(text)) {
|
||||
if (/\{value\d+(?:\}|,)/.test(text)) {
|
||||
const translated = t(key as keyof typeof english.runtime, {
|
||||
value0: 'CUSTOM',
|
||||
value0: 42,
|
||||
value1: 'VALUE',
|
||||
value2: 42,
|
||||
});
|
||||
expect(translated).toContain('CUSTOM');
|
||||
expect(translated).toContain('42');
|
||||
expect(translated).not.toContain('{value0}');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +1,20 @@
|
||||
'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 type { useTranslations } from 'next-intl';
|
||||
import { resolveClientLocale } from './client';
|
||||
import type { AppLocale } from './config';
|
||||
import { getRuntimeTranslator, type RuntimeKey } from './runtime-translators';
|
||||
|
||||
export { getRuntimeTranslator } from './runtime-translators';
|
||||
|
||||
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),
|
||||
getRuntimeTranslator(resolveClientLocale())(key, values),
|
||||
{
|
||||
raw: (key: RuntimeKey): string =>
|
||||
translators[resolveClientLocale()].raw(key),
|
||||
getRuntimeTranslator(resolveClientLocale()).raw(key),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createTranslator, type AbstractIntlMessages } from 'next-intl';
|
||||
import english from '@/messages/en.json';
|
||||
import russian from '@/messages/ru.json';
|
||||
import { normalizeLocale, pickLocaleFromAcceptLanguage } from './config';
|
||||
import { effectiveOfflinePageHTML } from '@/lib/openflare/offline-page-templates';
|
||||
import { getOriginErrorPageTemplate } from '@/lib/openflare/origin-error-page-templates';
|
||||
|
||||
function flatten(
|
||||
messages: AbstractIntlMessages,
|
||||
prefix = '',
|
||||
): Record<string, string> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(messages).flatMap(([key, value]) => {
|
||||
const path = prefix ? `${prefix}.${key}` : key;
|
||||
return typeof value === 'string'
|
||||
? [[path, value]]
|
||||
: Object.entries(flatten(value, path));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
describe('Russian UI', () => {
|
||||
it('negotiates Russian variants, quality values and English fallback', () => {
|
||||
expect(normalizeLocale('ru_RU')).toBe('ru');
|
||||
expect(normalizeLocale('ru-BY')).toBe('ru');
|
||||
expect(pickLocaleFromAcceptLanguage('de,ru-RU;q=0.9,en;q=0.7')).toBe('ru');
|
||||
expect(pickLocaleFromAcceptLanguage('ru;q=0,en;q=0.5')).toBe('en');
|
||||
expect(pickLocaleFromAcceptLanguage('de,fr')).toBe('en');
|
||||
});
|
||||
|
||||
it('keeps every message and named argument, and formats Russian ICU messages', () => {
|
||||
const source = flatten(english);
|
||||
const translated = flatten(russian);
|
||||
expect(Object.keys(translated).sort()).toEqual(Object.keys(source).sort());
|
||||
const errors: string[] = [];
|
||||
const t = createTranslator({
|
||||
locale: 'ru',
|
||||
messages: russian,
|
||||
onError: (error) => errors.push(error.message),
|
||||
});
|
||||
for (const [key, text] of Object.entries(source)) {
|
||||
const args = (value: string) =>
|
||||
[
|
||||
...new Set(
|
||||
[...value.matchAll(/\{(\w+)(?:\s*[,}])/g)].map((match) => match[1]),
|
||||
),
|
||||
].sort();
|
||||
expect(args(translated[key]), key).toEqual(args(text));
|
||||
// HTML, code examples and Go templates are intentionally read with t.raw.
|
||||
if (
|
||||
!text ||
|
||||
/\{\{|\{\w+:|className=|function |<\/?[a-zA-Z]|^\s*[{[]/.test(text)
|
||||
)
|
||||
continue;
|
||||
const numericArguments = new Set(
|
||||
[
|
||||
...translated[key].matchAll(
|
||||
/\{(\w+),\s*(?:plural|selectordinal|number)/g,
|
||||
),
|
||||
].map((match) => match[1]),
|
||||
);
|
||||
const values = Object.fromEntries(
|
||||
args(text).map((name) => [
|
||||
name,
|
||||
/^(count|total|current|page|pages|totalPages|value\d+)$/.test(name) ||
|
||||
numericArguments.has(name)
|
||||
? 2
|
||||
: 'CUSTOM',
|
||||
]),
|
||||
);
|
||||
t(key as Parameters<typeof t>[0], values);
|
||||
expect(errors, key).toEqual([]);
|
||||
}
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('uses Russian plural forms for 1, 2, 5, 21 and fractional counts', () => {
|
||||
const t = createTranslator({ locale: 'ru', messages: russian });
|
||||
for (const [count, expected] of [
|
||||
[1, '1 минута'],
|
||||
[2, '2 минуты'],
|
||||
[5, '5 минут'],
|
||||
[21, '21 минута'],
|
||||
[1.5, '1,5 минуты'],
|
||||
] as const) {
|
||||
expect(t('pages.source.intervalMinutes', { count })).toBe(expected);
|
||||
}
|
||||
expect(
|
||||
t('admin.files.stats.maxCountHint', { name: 'PDF', count: 2 }),
|
||||
).toContain('2 файла');
|
||||
});
|
||||
|
||||
it('formats certificate expiry and retry seconds across Russian plural boundaries', () => {
|
||||
const t = createTranslator({ locale: 'ru', messages: russian });
|
||||
for (const count of [
|
||||
0, 1, 2, 4, 5, 11, 12, 13, 14, 21, 22, 23, 24, 25, 101, 111,
|
||||
]) {
|
||||
const last = count % 10;
|
||||
const teen = count % 100 >= 11 && count % 100 <= 14;
|
||||
const day =
|
||||
!teen && last === 1
|
||||
? 'день'
|
||||
: !teen && last >= 2 && last <= 4
|
||||
? 'дня'
|
||||
: 'дней';
|
||||
const second =
|
||||
!teen && last === 1
|
||||
? 'секунду'
|
||||
: !teen && last >= 2 && last <= 4
|
||||
? 'секунды'
|
||||
: 'секунд';
|
||||
expect(
|
||||
t('certificates.certStatus.expiresInDays', { days: count }),
|
||||
).toContain(`${count} ${day}`);
|
||||
expect(
|
||||
t('runtime.too_many_requests_retry_in_value0_seconds_ab5e78f1', {
|
||||
value0: count,
|
||||
}),
|
||||
).toContain(`${count} ${second}`);
|
||||
}
|
||||
});
|
||||
|
||||
it('renders the empty-domain hint as rich text with its website link', () => {
|
||||
const errors: string[] = [];
|
||||
const t = createTranslator({
|
||||
locale: 'ru',
|
||||
messages: russian,
|
||||
onError: (error) => errors.push(error.message),
|
||||
});
|
||||
const result = t.rich('proxyRoutes.noZoneDomains', {
|
||||
websites: (chunks) => `[LINK]${chunks}[/LINK]`,
|
||||
});
|
||||
expect(errors).toEqual([]);
|
||||
expect(result).toContain('[LINK]');
|
||||
expect(result).not.toBe('proxyRoutes.noZoneDomains');
|
||||
});
|
||||
|
||||
it('localizes built-in page templates while retaining custom HTML and placeholders', () => {
|
||||
document.cookie = 'NEXT_LOCALE=ru; Path=/';
|
||||
try {
|
||||
expect(effectiveOfflinePageHTML('')).toContain('lang="ru"');
|
||||
for (const id of ['minimalist', 'line-style', 'baohaus']) {
|
||||
const html = getOriginErrorPageTemplate(id)?.html;
|
||||
expect(html).toContain('lang="ru"');
|
||||
const originals: Record<string, string> = {
|
||||
minimalist: english.runtime.origin_error_page_minimalist,
|
||||
'line-style': english.runtime.origin_error_page_line_style,
|
||||
baohaus: english.runtime.origin_error_page_baohaus,
|
||||
};
|
||||
expect(html?.match(/\{\{\w+\}\}/g)).toEqual(
|
||||
originals[id].match(/\{\{\w+\}\}/g),
|
||||
);
|
||||
}
|
||||
expect(effectiveOfflinePageHTML('<h1>Custom site</h1>')).toBe(
|
||||
'<h1>Custom site</h1>',
|
||||
);
|
||||
} finally {
|
||||
document.cookie = 'NEXT_LOCALE=; Max-Age=0; Path=/';
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user