Initial import of weiyuan frontend
This commit is contained in:
Vendored
+300
@@ -0,0 +1,300 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 界面语言启动判定(React 渲染前执行),方案见 docs/11-前端与体验中心/i18n/按IP国家自动切换界面语言方案.md。
|
||||
//
|
||||
// 优先级:URL ?lang=(本会话保持)> 用户在顶栏亲手点选 > 服务端判定(IP 国家 / 浏览器语言 / 默认语言)。
|
||||
// 服务端结果缓存在 lang_boot:有本地候选时立即渲染、后台静默刷新,刷新结果留到下次访问生效,
|
||||
// 不在会话中途切换语言;只有首访才等待接口(超时回退浏览器语言)。
|
||||
//
|
||||
// 环境(storage / 请求 / 语言包加载)一律注入,便于 node 单测。
|
||||
import { normalizeLanguage } from './language.js';
|
||||
import { isSupportedLanguage } from './catalog.js';
|
||||
|
||||
export const STORAGE_KEYS = {
|
||||
session: 'lang_session', // sessionStorage:URL ?lang= 命中后本会话保持,SPA 跳转不丢
|
||||
userChoice: 'lang_user_choice', // 仅顶栏点选时写入
|
||||
boot: 'lang_boot', // 服务端判定结果 + 公共配置
|
||||
legacy: 'i18nextLng', // 旧检测器自动写入的缓存,分不清是否手选
|
||||
migrated: 'lang_migrated',
|
||||
};
|
||||
|
||||
// 后台刷新写入 lang_boot 后派发,顶栏据此重新读取启用语言(首访时刷新可能晚于顶栏首次渲染)
|
||||
export const LANG_BOOT_UPDATED_EVENT = 'lang-boot-updated';
|
||||
|
||||
const LOCALE_REQUEST_TIMEOUT_MS = 500;
|
||||
// 语言包超时仍渲染:宁可先显示中文回退(随后 bindI18nStore:'added' 补渲染),也不把首屏卡在加载上
|
||||
const LANGUAGE_LOAD_TIMEOUT_MS = 1500;
|
||||
// 与后端默认配置、改造前的 i18next fallbackLng 保持一致
|
||||
const FALLBACK_LANGUAGE = 'zh';
|
||||
|
||||
const safeGet = (storage, key) => {
|
||||
try {
|
||||
return storage?.getItem(key) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const safeSet = (storage, key, value) => {
|
||||
try {
|
||||
storage?.setItem(key, value);
|
||||
} catch {
|
||||
// 隐私模式 / 配额满:放弃缓存,不影响本次判定
|
||||
}
|
||||
};
|
||||
|
||||
const safeRemove = (storage, key) => {
|
||||
try {
|
||||
storage?.removeItem(key);
|
||||
} catch {
|
||||
// 同上
|
||||
}
|
||||
};
|
||||
|
||||
const browserStorage = (name) => {
|
||||
try {
|
||||
return typeof window !== 'undefined' ? window[name] : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// 空值不能直接交给 normalizeLanguage:它对空输入返回 'zh'
|
||||
const toLanguageCode = (tag) => {
|
||||
if (!tag || !String(tag).trim()) return '';
|
||||
const code = normalizeLanguage(tag);
|
||||
return isSupportedLanguage(code) ? code : '';
|
||||
};
|
||||
|
||||
const readBoot = (storage) => {
|
||||
const raw = safeGet(storage, STORAGE_KEYS.boot);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const boot = JSON.parse(raw);
|
||||
return boot && typeof boot === 'object' ? boot : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// 顶栏等处读取公共配置(启用语言、是否允许切换)
|
||||
export const getBootConfig = (storage = browserStorage('localStorage')) =>
|
||||
readBoot(storage)?.config || null;
|
||||
|
||||
// 配置未知时不放行:否则首访(还没有 lang_boot)时 ?lang= 或旧的手选可以绕过后台的启用语言
|
||||
// 白名单,渲染出后台已停用、译文可能未维护的语种,而后端同一层是拒绝的(R82 F1)
|
||||
const isEnabled = (code, config) =>
|
||||
Boolean(code) &&
|
||||
Array.isArray(config?.enabled_languages) &&
|
||||
config.enabled_languages.includes(code);
|
||||
|
||||
// 不发请求即可确定的语言;返回 null 表示需要等服务端判定
|
||||
export function resolveLocalLanguage({ sessionLanguage, userChoice, boot }) {
|
||||
const config = boot?.config;
|
||||
const session = toLanguageCode(sessionLanguage);
|
||||
if (isEnabled(session, config)) return { language: session, source: 'query' };
|
||||
|
||||
// 顶栏切换被关闭后用户无法再改选,旧选择不能继续压过管理员规则
|
||||
const user = toLanguageCode(userChoice);
|
||||
if (config?.language_switch_enabled !== false && isEnabled(user, config)) {
|
||||
return { language: user, source: 'user' };
|
||||
}
|
||||
|
||||
const cached = toLanguageCode(boot?.language);
|
||||
if (isEnabled(cached, config)) return { language: cached, source: 'cache' };
|
||||
return null;
|
||||
}
|
||||
|
||||
export function browserFallbackLanguage(navigatorLanguages) {
|
||||
for (const tag of navigatorLanguages || []) {
|
||||
const code = toLanguageCode(tag);
|
||||
if (code) return code;
|
||||
}
|
||||
return FALLBACK_LANGUAGE;
|
||||
}
|
||||
|
||||
// 超时或失败都 resolve(null),启动流程永不因语言判定卡住
|
||||
const settleWithin = (promise, ms) =>
|
||||
new Promise((resolve) => {
|
||||
const timer = setTimeout(() => resolve(null), ms);
|
||||
promise.then(
|
||||
(value) => {
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
},
|
||||
() => {
|
||||
clearTimeout(timer);
|
||||
resolve(null);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// 方案决策 D1:旧 i18nextLng 基本是检测器按浏览器语言自动写入的,删除后按 IP 重判一次,只执行一次
|
||||
function migrateLegacyLanguage(local) {
|
||||
if (safeGet(local, STORAGE_KEYS.migrated)) return;
|
||||
safeRemove(local, STORAGE_KEYS.legacy);
|
||||
safeSet(local, STORAGE_KEYS.migrated, '1');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param i18n i18next 实例
|
||||
* @param env { local, session, search, navigatorLanguages,
|
||||
* fetchLocale(params) => Promise<data|null>, loadLanguage(code) => Promise,
|
||||
* requestTimeoutMs?, loadTimeoutMs? }
|
||||
* @returns { language, source, refresh } refresh 为后台刷新 lang_boot 的 Promise(单测用)
|
||||
*/
|
||||
export async function bootstrapLanguage(i18n, env) {
|
||||
const { local, session } = env;
|
||||
const navigatorLanguages = env.navigatorLanguages || [];
|
||||
migrateLegacyLanguage(local);
|
||||
|
||||
const query = toLanguageCode(
|
||||
new URLSearchParams(env.search || '').get('lang'),
|
||||
);
|
||||
if (query) {
|
||||
safeSet(session, STORAGE_KEYS.session, query);
|
||||
// 会话内保持已由 sessionStorage 负责;参数留在地址栏会让用户在顶栏改选后按 F5 又被改回
|
||||
env.stripLangParam?.();
|
||||
}
|
||||
|
||||
const sessionLanguage = safeGet(session, STORAGE_KEYS.session);
|
||||
const userChoice = safeGet(local, STORAGE_KEYS.userChoice);
|
||||
const boot = readBoot(local);
|
||||
|
||||
// URL 参数不发给服务端:否则缓存的判定结果会把链接参数带到之后的访问
|
||||
const refresh = Promise.resolve()
|
||||
.then(() =>
|
||||
env.fetchLocale({
|
||||
user_lang: userChoice || '',
|
||||
browser: navigatorLanguages.join(','),
|
||||
}),
|
||||
)
|
||||
.then((data) => {
|
||||
storeBootResult(data, { local, notify: env.onBootUpdated });
|
||||
return data || null;
|
||||
})
|
||||
.catch(() => null);
|
||||
|
||||
const localHit = resolveLocalLanguage({ sessionLanguage, userChoice, boot });
|
||||
let language = localHit?.language;
|
||||
let source = localHit?.source;
|
||||
if (!language) {
|
||||
const data = await settleWithin(
|
||||
refresh,
|
||||
env.requestTimeoutMs ?? LOCALE_REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
// 首访没有缓存配置:拿到服务端下发的配置后再校验会话参数与用户手选,二者仍优先于服务端判定
|
||||
const checked = resolveLocalLanguage({
|
||||
sessionLanguage,
|
||||
userChoice,
|
||||
boot: { config: data?.config },
|
||||
});
|
||||
if (checked) {
|
||||
language = checked.language;
|
||||
source = checked.source;
|
||||
} else {
|
||||
language = toLanguageCode(data?.language);
|
||||
source = language ? data.source || 'remote' : 'fallback';
|
||||
}
|
||||
if (!language) {
|
||||
// 配置也拿不到(超时/离线):退回目录级校验,保证分享链接与手选在断网时仍可用
|
||||
language =
|
||||
toLanguageCode(sessionLanguage) ||
|
||||
toLanguageCode(userChoice) ||
|
||||
browserFallbackLanguage(navigatorLanguages);
|
||||
source = 'fallback';
|
||||
}
|
||||
}
|
||||
|
||||
await settleWithin(
|
||||
Promise.resolve().then(() => env.loadLanguage(language)),
|
||||
env.loadTimeoutMs ?? LANGUAGE_LOAD_TIMEOUT_MS,
|
||||
);
|
||||
await i18n.changeLanguage(language);
|
||||
return { language, source, refresh };
|
||||
}
|
||||
|
||||
export function createBrowserEnv({ fetchLocale, loadLanguage }) {
|
||||
return {
|
||||
local: browserStorage('localStorage'),
|
||||
session: browserStorage('sessionStorage'),
|
||||
search: typeof window !== 'undefined' ? window.location.search : '',
|
||||
navigatorLanguages:
|
||||
typeof navigator !== 'undefined'
|
||||
? navigator.languages?.length
|
||||
? [...navigator.languages]
|
||||
: [navigator.language].filter(Boolean)
|
||||
: [],
|
||||
fetchLocale,
|
||||
loadLanguage,
|
||||
stripLangParam: () => {
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete('lang');
|
||||
window.history.replaceState(
|
||||
window.history.state,
|
||||
'',
|
||||
url.pathname + url.search + url.hash,
|
||||
);
|
||||
} catch {
|
||||
// 地址栏清理失败不影响判定
|
||||
}
|
||||
},
|
||||
onBootUpdated: announceBootUpdated,
|
||||
};
|
||||
}
|
||||
|
||||
// 写入服务端判定结果并通知顶栏;启动时的后台刷新与后台保存配置后共用
|
||||
export function storeBootResult(
|
||||
data,
|
||||
{ local = browserStorage('localStorage'), notify } = {},
|
||||
) {
|
||||
if (!data?.language) return false;
|
||||
safeSet(
|
||||
local,
|
||||
STORAGE_KEYS.boot,
|
||||
JSON.stringify({ language: data.language, config: data.config || null }),
|
||||
);
|
||||
notify?.();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function announceBootUpdated() {
|
||||
try {
|
||||
window.dispatchEvent(new Event(LANG_BOOT_UPDATED_EVENT));
|
||||
} catch {
|
||||
// 非浏览器环境或事件派发失败:顶栏在下次渲染时仍会读到新缓存
|
||||
}
|
||||
}
|
||||
|
||||
// 顶栏点选:记为显式选择,并覆盖本会话的 ?lang= 参数
|
||||
export function rememberUserLanguage(
|
||||
code,
|
||||
{
|
||||
local = browserStorage('localStorage'),
|
||||
session = browserStorage('sessionStorage'),
|
||||
} = {},
|
||||
) {
|
||||
const language = toLanguageCode(code);
|
||||
if (!language) return '';
|
||||
safeSet(local, STORAGE_KEYS.userChoice, language);
|
||||
safeRemove(session, STORAGE_KEYS.session);
|
||||
return language;
|
||||
}
|
||||
Vendored
+478
@@ -0,0 +1,478 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
STORAGE_KEYS,
|
||||
bootstrapLanguage,
|
||||
browserFallbackLanguage,
|
||||
getBootConfig,
|
||||
rememberUserLanguage,
|
||||
resolveLocalLanguage,
|
||||
storeBootResult,
|
||||
} from './bootstrap.js';
|
||||
|
||||
const memoryStorage = (initial = {}) => {
|
||||
const map = new Map(Object.entries(initial));
|
||||
return {
|
||||
getItem: (key) => (map.has(key) ? map.get(key) : null),
|
||||
setItem: (key, value) => map.set(key, String(value)),
|
||||
removeItem: (key) => map.delete(key),
|
||||
has: (key) => map.has(key),
|
||||
};
|
||||
};
|
||||
|
||||
const config = (overrides = {}) => ({
|
||||
enabled_languages: ['zh', 'zh-TW', 'en', 'ja', 'ko', 'vi', 'th'],
|
||||
default_language: 'en',
|
||||
language_switch_enabled: true,
|
||||
hash: 'abcd1234',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const bootJSON = (language, overrides) =>
|
||||
JSON.stringify({ language, config: config(overrides) });
|
||||
|
||||
const makeEnv = (overrides = {}) => {
|
||||
const calls = [];
|
||||
const env = {
|
||||
local: memoryStorage({ [STORAGE_KEYS.migrated]: '1' }),
|
||||
session: memoryStorage(),
|
||||
search: '',
|
||||
navigatorLanguages: ['en-US'],
|
||||
fetchLocale: async () => null,
|
||||
loadLanguage: async (code) => calls.push(`load:${code}`),
|
||||
requestTimeoutMs: 30,
|
||||
loadTimeoutMs: 30,
|
||||
...overrides,
|
||||
};
|
||||
const i18n = {
|
||||
language: 'zh',
|
||||
async changeLanguage(code) {
|
||||
calls.push(`change:${code}`);
|
||||
this.language = code;
|
||||
},
|
||||
};
|
||||
return { env, i18n, calls };
|
||||
};
|
||||
|
||||
const never = () => new Promise(() => {});
|
||||
|
||||
test('local priority: session > user choice > cached server result', () => {
|
||||
const boot = { language: 'ja', config: config() };
|
||||
assert.deepEqual(
|
||||
resolveLocalLanguage({ sessionLanguage: 'th', userChoice: 'ko', boot }),
|
||||
{ language: 'th', source: 'query' },
|
||||
);
|
||||
assert.deepEqual(resolveLocalLanguage({ userChoice: 'zh-HK', boot }), {
|
||||
language: 'zh-TW',
|
||||
source: 'user',
|
||||
});
|
||||
assert.deepEqual(resolveLocalLanguage({ boot }), {
|
||||
language: 'ja',
|
||||
source: 'cache',
|
||||
});
|
||||
assert.equal(resolveLocalLanguage({}), null);
|
||||
});
|
||||
|
||||
test('switch disabled ignores user choice; disabled languages are skipped', () => {
|
||||
assert.deepEqual(
|
||||
resolveLocalLanguage({
|
||||
userChoice: 'ko',
|
||||
boot: {
|
||||
language: 'ja',
|
||||
config: config({ language_switch_enabled: false }),
|
||||
},
|
||||
}),
|
||||
{ language: 'ja', source: 'cache' },
|
||||
);
|
||||
assert.equal(
|
||||
resolveLocalLanguage({
|
||||
sessionLanguage: 'th',
|
||||
userChoice: 'th',
|
||||
boot: { language: 'th', config: config({ enabled_languages: ['en'] }) },
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
resolveLocalLanguage({ sessionLanguage: 'fr', userChoice: '' }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('browser fallback maps to a catalog language or en', () => {
|
||||
assert.equal(browserFallbackLanguage(['fr-FR', 'zh-HK', 'en']), 'zh-TW');
|
||||
assert.equal(browserFallbackLanguage(['fr', 'de']), 'zh');
|
||||
assert.equal(browserFallbackLanguage(undefined), 'zh');
|
||||
});
|
||||
|
||||
test('first visit waits for server result and caches it', async () => {
|
||||
let params;
|
||||
const { env, i18n, calls } = makeEnv({
|
||||
fetchLocale: async (p) => {
|
||||
params = p;
|
||||
return { language: 'ja', source: 'ip', config: config() };
|
||||
},
|
||||
});
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
assert.equal(result.language, 'ja');
|
||||
assert.equal(result.source, 'ip');
|
||||
assert.deepEqual(calls, ['load:ja', 'change:ja']);
|
||||
assert.deepEqual(params, { user_lang: '', browser: 'en-US' });
|
||||
assert.deepEqual(JSON.parse(env.local.getItem(STORAGE_KEYS.boot)), {
|
||||
language: 'ja',
|
||||
config: config(),
|
||||
});
|
||||
});
|
||||
|
||||
test('first visit timeout falls back to browser language', async () => {
|
||||
const { env, i18n } = makeEnv({
|
||||
fetchLocale: never,
|
||||
navigatorLanguages: ['fr-FR', 'ko-KR'],
|
||||
});
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
assert.equal(result.language, 'ko');
|
||||
assert.equal(result.source, 'fallback');
|
||||
});
|
||||
|
||||
test('cached result renders immediately and refreshes in background for next visit', async () => {
|
||||
const { env, i18n } = makeEnv({
|
||||
fetchLocale: async () => ({
|
||||
language: 'zh-TW',
|
||||
source: 'ip',
|
||||
config: config({ hash: 'new' }),
|
||||
}),
|
||||
});
|
||||
env.local.setItem(STORAGE_KEYS.boot, bootJSON('ja'));
|
||||
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
assert.equal(result.language, 'ja', 'must not switch language mid-session');
|
||||
await result.refresh;
|
||||
assert.equal(
|
||||
JSON.parse(env.local.getItem(STORAGE_KEYS.boot)).language,
|
||||
'zh-TW',
|
||||
);
|
||||
|
||||
// 挂起的请求也不能阻塞有缓存时的启动
|
||||
const pending = makeEnv({ fetchLocale: never });
|
||||
pending.env.local.setItem(STORAGE_KEYS.boot, bootJSON('ko'));
|
||||
assert.equal(
|
||||
(await bootstrapLanguage(pending.i18n, pending.env)).language,
|
||||
'ko',
|
||||
);
|
||||
});
|
||||
|
||||
test('failed refresh keeps the previous cache', async () => {
|
||||
const { env, i18n } = makeEnv({
|
||||
fetchLocale: async () => {
|
||||
throw new Error('network');
|
||||
},
|
||||
});
|
||||
env.local.setItem(STORAGE_KEYS.boot, bootJSON('vi'));
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
assert.equal(result.language, 'vi');
|
||||
assert.equal(await result.refresh, null);
|
||||
assert.equal(JSON.parse(env.local.getItem(STORAGE_KEYS.boot)).language, 'vi');
|
||||
});
|
||||
|
||||
test('?lang= wins for the session and is not sent to the server', async () => {
|
||||
let params;
|
||||
const { env, i18n } = makeEnv({
|
||||
search: '?lang=th-TH',
|
||||
fetchLocale: async (p) => {
|
||||
params = p;
|
||||
return { language: 'en', source: 'default', config: config() };
|
||||
},
|
||||
});
|
||||
env.local.setItem(STORAGE_KEYS.userChoice, 'ko');
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
assert.equal(result.language, 'th');
|
||||
assert.equal(env.session.getItem(STORAGE_KEYS.session), 'th');
|
||||
assert.equal(params.lang, undefined);
|
||||
assert.equal(params.user_lang, 'ko');
|
||||
|
||||
// 同会话内跳转(URL 不再带参数)仍保持
|
||||
const next = await bootstrapLanguage(i18n, { ...env, search: '' });
|
||||
assert.equal(next.language, 'th');
|
||||
});
|
||||
|
||||
test('valid ?lang= is stripped from the address bar; invalid one is left alone', async () => {
|
||||
let stripped = 0;
|
||||
const valid = makeEnv({
|
||||
search: '?lang=ja&from=ad',
|
||||
stripLangParam: () => stripped++,
|
||||
});
|
||||
await bootstrapLanguage(valid.i18n, valid.env);
|
||||
assert.equal(stripped, 1);
|
||||
|
||||
const invalid = makeEnv({
|
||||
search: '?lang=fr',
|
||||
stripLangParam: () => stripped++,
|
||||
});
|
||||
await bootstrapLanguage(invalid.i18n, invalid.env);
|
||||
assert.equal(stripped, 1);
|
||||
});
|
||||
|
||||
test('boot update is announced only after a successful refresh', async () => {
|
||||
let announced = 0;
|
||||
const ok = makeEnv({
|
||||
fetchLocale: async () => ({ language: 'ja', config: config() }),
|
||||
onBootUpdated: () => announced++,
|
||||
});
|
||||
await (
|
||||
await bootstrapLanguage(ok.i18n, ok.env)
|
||||
).refresh;
|
||||
assert.equal(announced, 1);
|
||||
|
||||
const failed = makeEnv({
|
||||
fetchLocale: async () => {
|
||||
throw new Error('network');
|
||||
},
|
||||
onBootUpdated: () => announced++,
|
||||
});
|
||||
await (
|
||||
await bootstrapLanguage(failed.i18n, failed.env)
|
||||
).refresh;
|
||||
assert.equal(announced, 1);
|
||||
});
|
||||
|
||||
test('storeBootResult writes cache and notifies only for a real result', () => {
|
||||
const local = memoryStorage();
|
||||
let notified = 0;
|
||||
const notify = () => notified++;
|
||||
assert.equal(storeBootResult(null, { local, notify }), false);
|
||||
assert.equal(storeBootResult({ source: 'ip' }, { local, notify }), false);
|
||||
assert.equal(local.has(STORAGE_KEYS.boot), false);
|
||||
assert.equal(notified, 0);
|
||||
|
||||
assert.equal(
|
||||
storeBootResult({ language: 'ko', config: config() }, { local, notify }),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(JSON.parse(local.getItem(STORAGE_KEYS.boot)), {
|
||||
language: 'ko',
|
||||
config: config(),
|
||||
});
|
||||
assert.equal(notified, 1);
|
||||
});
|
||||
|
||||
test('hanging language pack still renders after the load timeout', async () => {
|
||||
const { env, i18n, calls } = makeEnv({
|
||||
fetchLocale: async () => ({ language: 'th', config: config() }),
|
||||
loadLanguage: () => new Promise(() => {}),
|
||||
});
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
assert.equal(result.language, 'th');
|
||||
assert.deepEqual(calls, ['change:th']);
|
||||
});
|
||||
|
||||
test('cached start changes language exactly once, even after refresh resolves', async () => {
|
||||
const { env, i18n, calls } = makeEnv({
|
||||
fetchLocale: async () => ({ language: 'ko', config: config() }),
|
||||
});
|
||||
env.local.setItem(STORAGE_KEYS.boot, bootJSON('ja'));
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
await result.refresh;
|
||||
assert.deepEqual(calls, ['load:ja', 'change:ja']);
|
||||
});
|
||||
|
||||
test('cached language disabled by the cached config falls through to the server', async () => {
|
||||
const { env, i18n } = makeEnv({
|
||||
fetchLocale: async () => ({
|
||||
language: 'en',
|
||||
source: 'default',
|
||||
config: config(),
|
||||
}),
|
||||
});
|
||||
env.local.setItem(
|
||||
STORAGE_KEYS.boot,
|
||||
bootJSON('th', { enabled_languages: ['en', 'ja'] }),
|
||||
);
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
assert.equal(result.language, 'en');
|
||||
assert.equal(result.source, 'default');
|
||||
});
|
||||
|
||||
// 首访没有缓存配置时,?lang= 与旧手选都必须先经服务端下发的启用语言白名单(R82 F1)
|
||||
test('first visit validates ?lang= and stored choice against the served config', async () => {
|
||||
const served = config({ enabled_languages: ['zh', 'en'] });
|
||||
|
||||
const disabled = makeEnv({
|
||||
search: '?lang=ja',
|
||||
fetchLocale: async () => ({
|
||||
language: 'en',
|
||||
source: 'default',
|
||||
config: served,
|
||||
}),
|
||||
});
|
||||
const blocked = await bootstrapLanguage(disabled.i18n, disabled.env);
|
||||
assert.equal(blocked.language, 'en');
|
||||
assert.equal(blocked.source, 'default');
|
||||
|
||||
const stored = makeEnv({
|
||||
fetchLocale: async () => ({
|
||||
language: 'en',
|
||||
source: 'default',
|
||||
config: served,
|
||||
}),
|
||||
});
|
||||
stored.env.local.setItem(STORAGE_KEYS.userChoice, 'ja');
|
||||
assert.equal(
|
||||
(await bootstrapLanguage(stored.i18n, stored.env)).language,
|
||||
'en',
|
||||
);
|
||||
|
||||
const allowed = makeEnv({
|
||||
search: '?lang=ja',
|
||||
fetchLocale: async () => ({
|
||||
language: 'en',
|
||||
source: 'default',
|
||||
config: config(),
|
||||
}),
|
||||
});
|
||||
const kept = await bootstrapLanguage(allowed.i18n, allowed.env);
|
||||
assert.equal(kept.language, 'ja');
|
||||
assert.equal(kept.source, 'query');
|
||||
|
||||
// 配置拿不到(超时/离线)时才退回目录级校验,保证分享链接仍可用
|
||||
const offline = makeEnv({ search: '?lang=ja', fetchLocale: never });
|
||||
const best = await bootstrapLanguage(offline.i18n, offline.env);
|
||||
assert.equal(best.language, 'ja');
|
||||
assert.equal(best.source, 'fallback');
|
||||
});
|
||||
|
||||
test('candidates are not accepted while the enabled list is unknown', () => {
|
||||
assert.equal(
|
||||
resolveLocalLanguage({ sessionLanguage: 'ja', boot: null }),
|
||||
null,
|
||||
);
|
||||
assert.equal(resolveLocalLanguage({ userChoice: 'ja', boot: null }), null);
|
||||
assert.equal(
|
||||
resolveLocalLanguage({
|
||||
userChoice: 'ja',
|
||||
boot: { language: 'ja', config: {} },
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
// 生产默认超时此前从未被执行:所有用例都注入 30ms,把默认值放大 1000× 也全绿(R85 ③-5)。
|
||||
test('default request timeout keeps the first paint under ~1s', async () => {
|
||||
const { env, i18n } = makeEnv({ fetchLocale: never });
|
||||
delete env.requestTimeoutMs;
|
||||
delete env.loadTimeoutMs;
|
||||
const started = Date.now();
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
const elapsed = Date.now() - started;
|
||||
assert.equal(result.source, 'fallback');
|
||||
assert.ok(
|
||||
elapsed >= 300 && elapsed < 1500,
|
||||
`首访等待 ${elapsed}ms,应落在 500ms 量级(默认 LOCALE_REQUEST_TIMEOUT_MS)`,
|
||||
);
|
||||
});
|
||||
|
||||
// 语言包 chunk 404 时应立即回退渲染,而不是干等满加载超时(R85 ③-5)。
|
||||
test('rejected language pack falls through immediately', async () => {
|
||||
const { env, i18n, calls } = makeEnv({
|
||||
fetchLocale: async () => ({ language: 'th', config: config() }),
|
||||
loadLanguage: async () => {
|
||||
throw new Error('chunk 404');
|
||||
},
|
||||
loadTimeoutMs: 5000,
|
||||
});
|
||||
const started = Date.now();
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
const elapsed = Date.now() - started;
|
||||
assert.equal(result.language, 'th');
|
||||
assert.deepEqual(calls, ['change:th']);
|
||||
assert.ok(elapsed < 1000, `加载失败应立即继续,实际等待 ${elapsed}ms`);
|
||||
});
|
||||
|
||||
test('getBootConfig exposes the cached public config', () => {
|
||||
const local = memoryStorage();
|
||||
assert.equal(getBootConfig(local), null);
|
||||
local.setItem(STORAGE_KEYS.boot, bootJSON('ja'));
|
||||
assert.deepEqual(getBootConfig(local), config());
|
||||
local.setItem(STORAGE_KEYS.boot, 'not json');
|
||||
assert.equal(getBootConfig(local), null);
|
||||
});
|
||||
|
||||
test('missing language_switch_enabled is treated as enabled', () => {
|
||||
const partial = config();
|
||||
delete partial.language_switch_enabled;
|
||||
assert.deepEqual(
|
||||
resolveLocalLanguage({
|
||||
userChoice: 'ko',
|
||||
boot: { language: 'ja', config: partial },
|
||||
}),
|
||||
{ language: 'ko', source: 'user' },
|
||||
);
|
||||
});
|
||||
|
||||
test('offline fallback prefers the session parameter over the stored choice', async () => {
|
||||
const { env, i18n } = makeEnv({ search: '?lang=th', fetchLocale: never });
|
||||
env.local.setItem(STORAGE_KEYS.userChoice, 'ko');
|
||||
const result = await bootstrapLanguage(i18n, env);
|
||||
assert.equal(result.language, 'th');
|
||||
});
|
||||
|
||||
test('legacy i18nextLng is removed exactly once', async () => {
|
||||
const { env, i18n } = makeEnv();
|
||||
env.local.removeItem(STORAGE_KEYS.migrated);
|
||||
env.local.setItem(STORAGE_KEYS.legacy, 'en-US');
|
||||
await bootstrapLanguage(i18n, env);
|
||||
assert.equal(env.local.has(STORAGE_KEYS.legacy), false);
|
||||
assert.equal(env.local.getItem(STORAGE_KEYS.migrated), '1');
|
||||
|
||||
env.local.setItem(STORAGE_KEYS.legacy, 'ja');
|
||||
await bootstrapLanguage(i18n, env);
|
||||
assert.equal(env.local.getItem(STORAGE_KEYS.legacy), 'ja');
|
||||
});
|
||||
|
||||
test('rememberUserLanguage stores explicit choice and clears session override', () => {
|
||||
const local = memoryStorage();
|
||||
const session = memoryStorage({ [STORAGE_KEYS.session]: 'th' });
|
||||
assert.equal(rememberUserLanguage('ja-JP', { local, session }), 'ja');
|
||||
assert.equal(local.getItem(STORAGE_KEYS.userChoice), 'ja');
|
||||
assert.equal(session.has(STORAGE_KEYS.session), false);
|
||||
|
||||
assert.equal(rememberUserLanguage('fr', { local, session }), '');
|
||||
assert.equal(local.getItem(STORAGE_KEYS.userChoice), 'ja');
|
||||
});
|
||||
|
||||
test('throwing storage never breaks startup', async () => {
|
||||
const broken = {
|
||||
getItem() {
|
||||
throw new Error('denied');
|
||||
},
|
||||
setItem() {
|
||||
throw new Error('denied');
|
||||
},
|
||||
removeItem() {
|
||||
throw new Error('denied');
|
||||
},
|
||||
};
|
||||
const { env, i18n } = makeEnv({
|
||||
local: broken,
|
||||
session: broken,
|
||||
fetchLocale: async () => ({ language: 'ko', config: config() }),
|
||||
});
|
||||
assert.equal((await bootstrapLanguage(i18n, env)).language, 'ko');
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 界面语言目录——前端唯一来源(加载器、顶栏展示、后台配置页均从这里取)。
|
||||
//
|
||||
// 新增语种:补 locales/xx.json → 在此登记 → 后端 setting/language_setting 的
|
||||
// SupportedLanguages 同步(Go 契约测试会比对两边语言码)。
|
||||
//
|
||||
// 保持纯数据:不引 React、不静态 import JSON,bootstrap 的 node 单测直接加载本文件。
|
||||
// endonym 一律用该语言自称,用户看不懂当前界面语言时仍能认出自己的那一项;
|
||||
// flag 为国家码,由展示层映射到旗帜组件(简繁共用 CN,靠自称区分)。
|
||||
export const LANGUAGE_CATALOG = [
|
||||
// zh 由 i18n.js 同步打包,无需按需加载
|
||||
{ code: 'zh', endonym: '简体中文', flag: 'CN', load: null },
|
||||
{
|
||||
code: 'zh-TW',
|
||||
endonym: '繁體中文',
|
||||
flag: 'CN',
|
||||
load: () => import('./locales/zh-TW.json'),
|
||||
},
|
||||
{
|
||||
code: 'en',
|
||||
endonym: 'English',
|
||||
flag: 'GB',
|
||||
load: () => import('./locales/en.json'),
|
||||
},
|
||||
{
|
||||
code: 'ja',
|
||||
endonym: '日本語',
|
||||
flag: 'JP',
|
||||
load: () => import('./locales/ja.json'),
|
||||
},
|
||||
{
|
||||
code: 'ko',
|
||||
endonym: '한국어',
|
||||
flag: 'KR',
|
||||
load: () => import('./locales/ko.json'),
|
||||
},
|
||||
{
|
||||
code: 'vi',
|
||||
endonym: 'Tiếng Việt',
|
||||
flag: 'VN',
|
||||
load: () => import('./locales/vi.json'),
|
||||
},
|
||||
{
|
||||
code: 'th',
|
||||
endonym: 'ไทย',
|
||||
flag: 'TH',
|
||||
load: () => import('./locales/th.json'),
|
||||
},
|
||||
];
|
||||
|
||||
export const LANGUAGE_CODES = LANGUAGE_CATALOG.map((entry) => entry.code);
|
||||
|
||||
export const isSupportedLanguage = (code) => LANGUAGE_CODES.includes(code);
|
||||
|
||||
export const getLanguageEntry = (code) =>
|
||||
LANGUAGE_CATALOG.find((entry) => entry.code === code) || null;
|
||||
|
||||
// 按后台配置的启用语言过滤并排序;配置缺失时展示全部
|
||||
export const orderEnabledLanguages = (enabledLanguages) => {
|
||||
if (!Array.isArray(enabledLanguages) || enabledLanguages.length === 0) {
|
||||
return LANGUAGE_CATALOG;
|
||||
}
|
||||
const entries = enabledLanguages.map(getLanguageEntry).filter(Boolean);
|
||||
return entries.length > 0 ? entries : LANGUAGE_CATALOG;
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import i18n from 'i18next';
|
||||
import { initReactI18next } from 'react-i18next';
|
||||
import { normalizeLanguage } from './language';
|
||||
import { getLanguageEntry } from './catalog';
|
||||
|
||||
// Load Chinese synchronously; other languages are loaded on demand.
|
||||
import zhTranslation from './locales/zh.json';
|
||||
|
||||
const loadedLanguages = new Set(['zh']);
|
||||
|
||||
// 可 await:启动流程(i18n/bootstrap.js)要等语言包落库后再渲染,避免首屏先闪回退语言
|
||||
export const loadLanguage = async (lng) => {
|
||||
if (loadedLanguages.has(lng)) return;
|
||||
const entry = getLanguageEntry(lng);
|
||||
if (!entry?.load) return;
|
||||
|
||||
try {
|
||||
const translation = await entry.load();
|
||||
const data = translation.default || translation;
|
||||
const translationData = data.translation || data;
|
||||
i18n.addResourceBundle(lng, 'translation', translationData, true, true);
|
||||
loadedLanguages.add(lng);
|
||||
} catch (error) {
|
||||
console.error(`Failed to load language: ${lng}`, error);
|
||||
}
|
||||
};
|
||||
|
||||
i18n.use(initReactI18next).init({
|
||||
// 初始语言由 i18n/bootstrap.js 在渲染前判定(URL 参数 / 用户选择 / IP 国家 /
|
||||
// 浏览器语言 / 默认语言),不再使用浏览器语言检测器;此处只是渲染前的占位。
|
||||
lng: 'zh',
|
||||
// 不能用 'languageOnly':它会把 zh-TW 截成 zh,繁体包永远不会命中。
|
||||
load: 'all',
|
||||
resources: { zh: zhTranslation },
|
||||
fallbackLng: 'zh',
|
||||
// Natural-language keys may contain dots and colons, so keep all keys flat.
|
||||
keySeparator: false,
|
||||
nsSeparator: false,
|
||||
// The locale files carry hundreds of ""-valued keys written by
|
||||
// i18next-cli sync as translation TODOs. i18next treats "" as a valid
|
||||
// translation by default, which renders those strings as BLANK; treating
|
||||
// them as missing falls back to the key itself (the readable Chinese
|
||||
// source text) instead.
|
||||
// 注:locales/{fr,ru}.json 未登记进 catalog.js(译文覆盖率不足),当前不会被加载。
|
||||
returnEmptyString: false,
|
||||
interpolation: { escapeValue: false },
|
||||
// 语种按需加载:bundle 由 addResourceBundle 异步落库,只有订阅 store 的
|
||||
// 'added' 才会在落库后补渲染;仅默认的 bindI18n:'languageChanged' 是同步
|
||||
// 触发的,那一刻资源还没到,界面会停在回退语言直到用户再点一次。
|
||||
react: { useSuspense: false, bindI18nStore: 'added' },
|
||||
});
|
||||
|
||||
// <html lang> 必须跟着切:泰文词间无空格,浏览器要靠 lang="th" 才会启用 ICU
|
||||
// 词典分词,否则整串泰文是不可断原子、窄列必然溢出;lang 还决定字体回退(CJK
|
||||
// 与谚文/泰文字形的消歧,日文/繁体汉字字形)和读屏语言。index.html 里的
|
||||
// lang="zh" 只是首帧默认值。
|
||||
const syncHtmlLang = (lng) => {
|
||||
if (typeof document !== 'undefined') document.documentElement.lang = lng;
|
||||
};
|
||||
|
||||
i18n.on('languageChanged', (lng) => {
|
||||
const code = normalizeLanguage(lng);
|
||||
syncHtmlLang(code);
|
||||
loadLanguage(code);
|
||||
});
|
||||
|
||||
export default i18n;
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 界面语言码归一化——全站唯一入口。
|
||||
//
|
||||
// 以前一律 split('-')[0] 取主语言,但繁体中文与简体共用主语言 zh,只能靠
|
||||
// 地区/书写系统子标签区分:zh-TW / zh-HK / zh-MO / zh-Hant-* 归到 'zh-TW'
|
||||
// (繁体包),zh-CN / zh-SG / zh-Hans-* / 裸 zh 归到 'zh'。其余语言仍取主语言,
|
||||
// 这样历史缓存里的 en-US / ko-KR 之类照旧命中各自的语言包。
|
||||
export const normalizeLanguage = (lng) => {
|
||||
if (!lng) return 'zh';
|
||||
const parts = String(lng).replace(/_/g, '-').toLowerCase().split('-');
|
||||
const base = parts[0];
|
||||
if (base !== 'zh') return base;
|
||||
const subtags = parts.slice(1);
|
||||
if (subtags.includes('hant')) return 'zh-TW';
|
||||
if (subtags.includes('hans')) return 'zh';
|
||||
if (subtags.some((s) => s === 'tw' || s === 'hk' || s === 'mo')) {
|
||||
return 'zh-TW';
|
||||
}
|
||||
return 'zh';
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import { normalizeLanguage } from './language.js';
|
||||
|
||||
// 与后端 setting/language_setting 的 Normalize 共用同一份用例,防止两端归一化口径漂移
|
||||
const sharedCases = JSON.parse(
|
||||
readFileSync(new URL('./language_cases.json', import.meta.url), 'utf8'),
|
||||
);
|
||||
|
||||
test('shared normalization cases (kept in sync with backend)', () => {
|
||||
for (const { input, expected } of sharedCases) {
|
||||
assert.equal(normalizeLanguage(input), expected, input);
|
||||
}
|
||||
});
|
||||
|
||||
test('traditional Chinese variants map to zh-TW', () => {
|
||||
for (const lng of [
|
||||
'zh-TW',
|
||||
'zh-HK',
|
||||
'zh-MO',
|
||||
'zh-Hant',
|
||||
'zh-Hant-TW',
|
||||
'zh_TW',
|
||||
]) {
|
||||
assert.equal(normalizeLanguage(lng), 'zh-TW', lng);
|
||||
}
|
||||
});
|
||||
|
||||
test('simplified Chinese variants map to zh', () => {
|
||||
for (const lng of [
|
||||
'zh',
|
||||
'zh-CN',
|
||||
'zh-SG',
|
||||
'zh-Hans',
|
||||
'zh-Hans-HK',
|
||||
undefined,
|
||||
'',
|
||||
]) {
|
||||
assert.equal(normalizeLanguage(lng), 'zh', String(lng));
|
||||
}
|
||||
});
|
||||
|
||||
test('other languages keep only the primary subtag', () => {
|
||||
assert.equal(normalizeLanguage('en-US'), 'en');
|
||||
assert.equal(normalizeLanguage('ja-JP'), 'ja');
|
||||
assert.equal(normalizeLanguage('vi'), 'vi');
|
||||
assert.equal(normalizeLanguage('ko-KR'), 'ko');
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
[
|
||||
{ "input": "zh-TW", "expected": "zh-TW" },
|
||||
{ "input": "zh-HK", "expected": "zh-TW" },
|
||||
{ "input": "zh-MO", "expected": "zh-TW" },
|
||||
{ "input": "zh-Hant", "expected": "zh-TW" },
|
||||
{ "input": "zh-Hant-TW", "expected": "zh-TW" },
|
||||
{ "input": "zh_TW", "expected": "zh-TW" },
|
||||
{ "input": "ZH-hk", "expected": "zh-TW" },
|
||||
{ "input": "zh", "expected": "zh" },
|
||||
{ "input": "zh-CN", "expected": "zh" },
|
||||
{ "input": "zh-SG", "expected": "zh" },
|
||||
{ "input": "zh-Hans", "expected": "zh" },
|
||||
{ "input": "zh-Hans-HK", "expected": "zh" },
|
||||
{ "input": "en-US", "expected": "en" },
|
||||
{ "input": "EN_gb", "expected": "en" },
|
||||
{ "input": "ja-JP", "expected": "ja" },
|
||||
{ "input": "ko-KR", "expected": "ko" },
|
||||
{ "input": "vi", "expected": "vi" },
|
||||
{ "input": "th-TH", "expected": "th" }
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const locale = JSON.parse(
|
||||
readFileSync(new URL('./zh.json', import.meta.url), 'utf8'),
|
||||
).translation;
|
||||
|
||||
test('organization role labels are localized in Chinese', () => {
|
||||
assert.deepEqual(
|
||||
{
|
||||
admin: locale.Admin,
|
||||
deptAdmin: locale['Dept Admin'],
|
||||
member: locale.Member,
|
||||
},
|
||||
{ admin: '管理员', deptAdmin: '部门管理员', member: '成员' },
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const localeCodes = ['zh', 'zh-TW', 'en', 'fr', 'ru', 'ja', 'ko', 'vi', 'th'];
|
||||
const paypalKeys = [
|
||||
'PayPal 设置',
|
||||
'订阅 CHECKOUT.ORDER.APPROVED、PAYMENT.CAPTURE.COMPLETED、PAYMENT.CAPTURE.PENDING 和 PAYMENT.CAPTURE.DECLINED 事件',
|
||||
'Sandbox 测试环境',
|
||||
'最低充值单位',
|
||||
'结算币种',
|
||||
'换算汇率',
|
||||
'更新 PayPal 设置',
|
||||
'隐藏 PayPal 支付',
|
||||
'开启后拒绝 PayPal 新订单,但仍处理已发起订单的回跳、Webhook 和主动对账',
|
||||
'管理员未开启 PayPal 充值!',
|
||||
'PayPal 充值成功',
|
||||
'PayPal 支付处理中,请稍后查看充值记录',
|
||||
'已取消 PayPal 支付',
|
||||
'PayPal 支付确认失败,请稍后重试',
|
||||
'敏感信息不会显示',
|
||||
'PayPal 订单创建中,请稍后重试',
|
||||
'汇率来源',
|
||||
'manual',
|
||||
'open_exchange_rates',
|
||||
'manual_fallback',
|
||||
'报价已过期,请重新获取',
|
||||
'报价剩余',
|
||||
'汇率模式',
|
||||
'手工汇率',
|
||||
'准实时汇率',
|
||||
'汇率保护加点(基点)',
|
||||
'当前市场汇率',
|
||||
'暂无可用的市场汇率快照',
|
||||
'汇率刷新成功',
|
||||
'已确认手工兜底汇率',
|
||||
'立即刷新汇率',
|
||||
'确认手工兜底汇率',
|
||||
'PayPal 报价已更新,请重新确认',
|
||||
'支付服务费',
|
||||
'平台承担',
|
||||
'实际支付',
|
||||
'用户承担支付服务费',
|
||||
'支付服务费比例(%)',
|
||||
'手续费策略版本',
|
||||
'默认由平台承担;启用后将按配置比例向用户展示并收取支付服务费',
|
||||
'承担方',
|
||||
'用户承担',
|
||||
'费率',
|
||||
'操作人',
|
||||
'获取手续费策略失败',
|
||||
'手续费比例必须在有效范围内',
|
||||
'手续费策略已被其他管理员更新,请重新确认',
|
||||
'最后更新人',
|
||||
'PayPal 结算',
|
||||
'基础金额',
|
||||
'PayPal 实际手续费',
|
||||
'PayPal 净收金额',
|
||||
'结算状态',
|
||||
'待回填',
|
||||
'已完整',
|
||||
'不可获取',
|
||||
];
|
||||
|
||||
test('PayPal UI strings are translated in every supported locale', () => {
|
||||
for (const code of localeCodes) {
|
||||
const locale = JSON.parse(
|
||||
readFileSync(new URL(`./locales/${code}.json`, import.meta.url), 'utf8'),
|
||||
).translation;
|
||||
for (const key of paypalKeys) {
|
||||
assert.equal(
|
||||
typeof locale[key] === 'string' && locale[key].trim().length > 0,
|
||||
true,
|
||||
`${code} is missing translation: ${key}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user