SHA256
Локализовать интерфейс SHiNE на русский и английский
This commit is contained in:
@@ -1,9 +1,10 @@
|
||||
import { expandRussian } from './i18n-source-helper.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { isDmSendEnter } from '../js/services/dm-composer-keys.js';
|
||||
|
||||
const read = (relative) => fs.readFileSync(new URL(relative, import.meta.url), 'utf8');
|
||||
const read = (relative) => expandRussian(fs.readFileSync(new URL(relative, import.meta.url), 'utf8'));
|
||||
|
||||
test('обычный Enter отправляет, модификаторы и IME не отправляют', () => {
|
||||
const normal = { key: 'Enter', shiftKey: false, ctrlKey: false, altKey: false, metaKey: false, isComposing: false };
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const moduleUrl = new URL('../js/i18n/index.js', import.meta.url);
|
||||
const assets = new URL('../js/i18n/', import.meta.url);
|
||||
|
||||
function setupBrowser({ languages = ['ru-RU', 'en-US'], selected = '' } = {}) {
|
||||
const values = new Map(selected ? [['shine-ui-language-v1', selected]] : []);
|
||||
const element = { lang: '' };
|
||||
const existing = {
|
||||
window: globalThis.window,
|
||||
navigator: globalThis.navigator,
|
||||
document: globalThis.document,
|
||||
localStorage: globalThis.localStorage,
|
||||
fetch: globalThis.fetch,
|
||||
};
|
||||
Object.defineProperty(globalThis, 'navigator', { value: { languages, language: languages[0] }, configurable: true });
|
||||
globalThis.window = { __SHINE_BUILD_HASH__: 'test' };
|
||||
globalThis.document = { documentElement: element };
|
||||
globalThis.localStorage = {
|
||||
getItem: (key) => values.get(key) ?? null,
|
||||
setItem: (key, value) => values.set(key, String(value)),
|
||||
};
|
||||
globalThis.fetch = async (url) => {
|
||||
const path = new URL(url);
|
||||
const content = await readFile(fileURLToPath(new URL(path.pathname, assets)));
|
||||
return { ok: true, json: async () => JSON.parse(content.toString()) };
|
||||
};
|
||||
return {
|
||||
values, element,
|
||||
restore() {
|
||||
Object.defineProperty(globalThis, 'navigator', { value: existing.navigator, configurable: true });
|
||||
for (const key of ['window', 'document', 'localStorage', 'fetch']) {
|
||||
if (existing[key] === undefined) delete globalThis[key];
|
||||
else globalThis[key] = existing[key];
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function freshModule() {
|
||||
return import(`${moduleUrl.href}?test=${Math.random().toString(36).slice(2)}`);
|
||||
}
|
||||
|
||||
test('системный ru-RU определяется как ru и подгружается русский словарь', async () => {
|
||||
const env = setupBrowser({ languages: ['ru-RU', 'en-US'] });
|
||||
try {
|
||||
const i18n = await freshModule();
|
||||
await i18n.initI18n();
|
||||
assert.equal(i18n.getLanguage(), 'ru');
|
||||
assert.equal(i18n.t('language.menu'), 'Язык / Language');
|
||||
assert.equal(env.element.lang, 'ru');
|
||||
assert.deepEqual(i18n.getLanguages().map(({ code }) => code), ['ru', 'en']);
|
||||
} finally { env.restore(); }
|
||||
});
|
||||
|
||||
test('если язык браузера не поддерживается, язык по умолчанию English', async () => {
|
||||
const env = setupBrowser({ languages: ['de-DE', 'fr-FR'] });
|
||||
try {
|
||||
const i18n = await freshModule();
|
||||
await i18n.initI18n();
|
||||
assert.equal(i18n.getLanguage(), 'en');
|
||||
assert.equal(i18n.t('language.menu'), 'Language / Language');
|
||||
assert.equal(env.element.lang, 'en');
|
||||
} finally { env.restore(); }
|
||||
});
|
||||
|
||||
test('первый поддерживаемый язык из navigator.languages побеждает', async () => {
|
||||
const env = setupBrowser({ languages: ['de-DE', 'ru-BY', 'en-US'] });
|
||||
try {
|
||||
const i18n = await freshModule();
|
||||
await i18n.initI18n();
|
||||
assert.equal(i18n.getLanguage(), 'ru');
|
||||
} finally { env.restore(); }
|
||||
});
|
||||
|
||||
test('ручной выбор общий для профилей, сохраняется в отдельном ключе и меняет html lang', async () => {
|
||||
const env = setupBrowser({ languages: ['ru-RU'] });
|
||||
try {
|
||||
const i18n = await freshModule();
|
||||
await i18n.initI18n();
|
||||
let updates = 0;
|
||||
const unsubscribe = i18n.onLanguageChange(() => { updates++; });
|
||||
assert.equal(await i18n.setLanguage('en'), true);
|
||||
assert.equal(i18n.getLanguage(), 'en');
|
||||
assert.equal(env.values.get('shine-ui-language-v1'), 'en');
|
||||
assert.equal(env.element.lang, 'en');
|
||||
assert.equal(updates, 1);
|
||||
await i18n.setLanguage('en');
|
||||
assert.equal(updates, 1);
|
||||
unsubscribe();
|
||||
await i18n.setLanguage('ru');
|
||||
assert.equal(updates, 1);
|
||||
assert.equal(await i18n.setLanguage('zz'), false);
|
||||
assert.equal(i18n.getLanguage(), 'ru');
|
||||
} finally { env.restore(); }
|
||||
});
|
||||
|
||||
test('ручной выбор языка имеет приоритет над браузером', async () => {
|
||||
const env = setupBrowser({ languages: ['ru-RU'], selected: 'en' });
|
||||
try {
|
||||
const i18n = await freshModule();
|
||||
await i18n.initI18n();
|
||||
assert.equal(i18n.getLanguage(), 'en');
|
||||
} finally { env.restore(); }
|
||||
});
|
||||
|
||||
test('недостающие английские ключи возвращают русский текст; параметры подставляются', async () => {
|
||||
const env = setupBrowser();
|
||||
try {
|
||||
const i18n = await freshModule();
|
||||
await i18n.initI18n();
|
||||
assert.equal(i18n.t('screens.start_view.text_003'), 'Войти');
|
||||
assert.equal(i18n.t('unknown.key'), 'unknown.key');
|
||||
assert.equal(i18n.t('missing.{who}', { who: 'Alice' }), 'missing.Alice');
|
||||
} finally { env.restore(); }
|
||||
});
|
||||
|
||||
test('в профилях не сохраняется язык, а экран выбора строится из реестра', async () => {
|
||||
const state = await readFile(new URL('../js/state.js', import.meta.url), 'utf8');
|
||||
const page = await readFile(new URL('../js/pages/language-view.js', import.meta.url), 'utf8');
|
||||
assert.ok(state.includes('language: getLanguage()'));
|
||||
assert.ok(!state.includes("language: String(settings?.language || 'ru')"));
|
||||
assert.ok(page.includes('getLanguages().forEach'));
|
||||
assert.ok(page.includes('await saveEntryLanguage(code)'));
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const uiRoot = fileURLToPath(new URL('../', import.meta.url));
|
||||
const russian = JSON.parse(readFileSync(join(uiRoot, 'js/i18n/locales/ru.json'), 'utf8'));
|
||||
const english = JSON.parse(readFileSync(join(uiRoot, 'js/i18n/locales/en.json'), 'utf8'));
|
||||
|
||||
function flatten(node, prefix = '') {
|
||||
return Object.entries(node).flatMap(([name, value]) => {
|
||||
const key = prefix ? `${prefix}.${name}` : name;
|
||||
return typeof value === 'string' ? [[key, value]] : flatten(value, key);
|
||||
});
|
||||
}
|
||||
|
||||
function javascriptFiles(directory) {
|
||||
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
||||
const full = join(directory, entry.name);
|
||||
return entry.isDirectory() ? javascriptFiles(full) : (entry.name.endsWith('.js') ? [full] : []);
|
||||
});
|
||||
}
|
||||
|
||||
test('оба словаря содержат одинаковые ключи и параметры', () => {
|
||||
const ru = new Map(flatten(russian));
|
||||
const en = new Map(flatten(english));
|
||||
assert.deepEqual([...en.keys()].sort(), [...ru.keys()].sort());
|
||||
for (const [key, value] of ru) {
|
||||
const parameters = (text) => [...text.matchAll(/\{([a-zA-Z0-9_]+)\}/gu)].map((match) => match[1]).sort();
|
||||
assert.deepEqual(parameters(en.get(key)), parameters(value), key);
|
||||
assert.ok(en.get(key).trim(), key);
|
||||
}
|
||||
});
|
||||
|
||||
test('каждое статическое обращение t/th имеет русский ключ', () => {
|
||||
const ru = new Map(flatten(russian));
|
||||
for (const file of javascriptFiles(join(uiRoot, 'js'))) {
|
||||
if (file.includes('/i18n/')) continue;
|
||||
const source = readFileSync(file, 'utf8');
|
||||
for (const match of source.matchAll(/\b(?:t|th)\('([^']+)'/gu)) {
|
||||
assert.ok(ru.has(match[1]), `${file}: ${match[1]}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const ui = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const ru = JSON.parse(fs.readFileSync(path.join(ui, 'js/i18n/locales/ru.json'), 'utf8'));
|
||||
const source = (name) => fs.readFileSync(path.join(ui, `js/${name}`), 'utf8');
|
||||
const key = (name) => name.split('.').reduce((value, part) => value?.[part], ru);
|
||||
|
||||
test('русский словарь содержит новые блоки аудита диалогов', () => {
|
||||
const required = [
|
||||
'dialogs.final.consent.remember_public_history',
|
||||
'dialogs.final.consent.public_history_warning',
|
||||
'dialogs.final.chat.delete_contact_confirm',
|
||||
'dialogs.final.chat.delete_protected_confirm',
|
||||
'dialogs.final.chat.confirm_clear_history_text',
|
||||
'dialogs.final.profile.char_limit',
|
||||
'dialogs.remaining.components.share_sheet.markup.skopirovat_ssylku',
|
||||
];
|
||||
for (const name of required) {
|
||||
assert.ok(typeof key(name) === 'string' && key(name).length, name);
|
||||
}
|
||||
assert.match(key('dialogs.final.chat.delete_contact_confirm'), /\{name\}/);
|
||||
});
|
||||
|
||||
test('окно «Поделиться»: функция t не перекрыта локальной переменной', () => {
|
||||
const share = source('components/share-sheet.js');
|
||||
assert.match(share, /import \{ t \} from '\.\.\/i18n\/index\.js'/);
|
||||
assert.doesNotMatch(share, /\b(?:const|let|var)\s+t\s*=/);
|
||||
assert.match(share, /previewText\.textContent\s*=\s*text/);
|
||||
assert.match(share, /t\('dialogs\.remaining\.components\.share_sheet\.markup\.skopirovat_ssylku'\)/);
|
||||
});
|
||||
|
||||
test('подпись редактирования канала подставляется, а не показывается как ${t(...)}', () => {
|
||||
const channel = source('pages/channel-view.js');
|
||||
assert.match(channel, /title="\$\{t\('dialogs\.modals\.channel_view\.label_001'\)\}"/);
|
||||
assert.doesNotMatch(channel, /title="\\\$\{t\(/);
|
||||
});
|
||||
|
||||
test('переводы согласий вычисляются при открытии окна, а не при загрузке модуля', () => {
|
||||
const consent = source('services/public-history-consent.js');
|
||||
const likes = source('components/like-action-sheet.js');
|
||||
const profile = source('pages/profile-edit-view.js');
|
||||
assert.match(consent, /export function getPublicHistoryRememberLabel\(\)/);
|
||||
assert.match(consent, /label:\s*getPublicHistoryRememberLabel\(\)/);
|
||||
assert.match(likes, /getPublicHistoryRememberLabel\(\)/);
|
||||
assert.doesNotMatch(likes, /PUBLIC_HISTORY_REMEMBER_LABEL/);
|
||||
assert.match(profile, /function shiningSteps\(\)/);
|
||||
assert.match(profile, /steps:\s*shiningSteps\(\)/);
|
||||
assert.doesNotMatch(profile, /const SHINING_STEPS/);
|
||||
});
|
||||
|
||||
test('динамические имена в подтверждениях чата экранируются для HTML', () => {
|
||||
const chat = source('pages/chat-view.js');
|
||||
assert.equal((chat.match(/function escapeDialogHtml\(/g) || []).length, 1);
|
||||
assert.match(chat, /escapeDialogHtml\(t\('dialogs\.final\.chat\.delete_contact_confirm'/);
|
||||
assert.match(chat, /escapeDialogHtml\(t\('dialogs\.final\.chat\.delete_protected_confirm'/);
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const russian = JSON.parse(readFileSync(new URL('../js/i18n/locales/ru.json', import.meta.url), 'utf8'));
|
||||
|
||||
export function expandRussian(source) {
|
||||
return source.replace(/t\('([a-z0-9_.]+)'\)/gu, (call, key) => {
|
||||
const value = key.split('.').reduce((node, part) => node?.[part], russian);
|
||||
return typeof value === 'string' ? JSON.stringify(value) : call;
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import test from 'node:test';
|
||||
import { expandRussian } from './i18n-source-helper.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
const read = p => readFileSync(new URL(`../../${p}`, import.meta.url), 'utf8');
|
||||
const read = p => expandRussian(readFileSync(new URL(`../../${p}`, import.meta.url), 'utf8'));
|
||||
const ui = read('shine-UI/js/pages/key-rotation-view.js');
|
||||
const app = read('shine-UI/js/app.js');
|
||||
const client = read('shine-UI/js/services/key-rotation-service.js');
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { expandRussian } from './i18n-source-helper.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
|
||||
const read = path => fs.readFileSync(`${root}/${path}`,'utf8');
|
||||
const read = path => expandRussian(fs.readFileSync(`${root}/${path}`,'utf8'));
|
||||
const registry=read('SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/JsonHandlerRegistry.java');
|
||||
const api=read('shine-UI/js/services/registration-v2-api.js');
|
||||
const ops=['GetNamespaces','CheckRegistrationLogin','CheckRegistrationEmail',
|
||||
|
||||
@@ -50,6 +50,7 @@ async function simulateCompletion({ headerFails = false } = {}) {
|
||||
},
|
||||
};
|
||||
const context = {
|
||||
t: (key) => key,
|
||||
authService,
|
||||
state,
|
||||
EMPTY_PASSWORD_WORDS: Array(12).fill(''),
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { expandRussian } from './i18n-source-helper.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
|
||||
const read = (path) => expandRussian(readFileSync(new URL(path, import.meta.url), 'utf8'));
|
||||
const upgrade = read('../js/pages/registration-upgrade-view.js');
|
||||
const direct = read('../js/pages/registration-payment-view.js');
|
||||
const styles = read('../styles/features/preauth.css');
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { expandRussian } from './i18n-source-helper.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
const read = relative => fs.readFileSync(new URL(relative, import.meta.url), 'utf8');
|
||||
const read = relative => expandRussian(fs.readFileSync(new URL(relative, import.meta.url), 'utf8'));
|
||||
test('выбор аккаунта перед шагом 1, всего три шага', () => {
|
||||
const choice = read('../js/pages/registration-choice-view.js');
|
||||
const login = read('../js/pages/register-view.js');
|
||||
|
||||
@@ -33,7 +33,9 @@ test('в настройках только бесплатным предлага
|
||||
const settings = read('shine-UI/js/pages/settings-view.js');
|
||||
assert.match(settings, /info.registrationStatus !== 'FREE_CERT'/);
|
||||
assert.match(settings, /id="settings-account-tier" hidden/);
|
||||
assert.match(settings, /Бесплатный аккаунт с ограниченными возможностями/);
|
||||
assert.match(settings, /t\('dialogs\.modals\.settings_view\.label_004'\)/);
|
||||
const ru = JSON.parse(read('shine-UI/js/i18n/locales/ru.json'));
|
||||
assert.match(ru.dialogs.modals.settings_view.label_004, /Бесплатный аккаунт с ограниченными возможностями/);
|
||||
assert.doesNotMatch(settings, /settings-solana-registered/);
|
||||
});
|
||||
test('миграция БД делает статусы действительно едиными', () => {
|
||||
|
||||
Reference in New Issue
Block a user