From d3a6dd316b1fea88c8d6eb3f937639da10e198a1 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 16:55:05 +0200 Subject: [PATCH 1/3] feat(web): rewrite site copy in plain language and split i18n dictionaries Move RU/EN strings to src/i18n/{ru,en}.ts, add og/meta tags that follow the selected language, remove the long dash from all text, add copy guidelines and tests for key parity, HTML fallback text and dash-free sources and bundle. --- README.md | 6 +- docs/copy-guidelines.md | 12 ++ docs/verification.md | 2 +- public/index.html | 21 ++- src/app.ts | 8 ++ src/i18n.ts | 284 ---------------------------------------- src/i18n/en.ts | 114 ++++++++++++++++ src/i18n/index.ts | 19 +++ src/i18n/ru.ts | 116 ++++++++++++++++ tests/browser_qa.py | 8 +- tests/copy.test.ts | 102 +++++++++++++++ 11 files changed, 397 insertions(+), 295 deletions(-) create mode 100644 docs/copy-guidelines.md delete mode 100644 src/i18n.ts create mode 100644 src/i18n/en.ts create mode 100644 src/i18n/index.ts create mode 100644 src/i18n/ru.ts create mode 100644 tests/copy.test.ts diff --git a/README.md b/README.md index 3547ca5..a59eac3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# VNOX — Web +# VNOX Web > Public project website and account frontend for VNOX Central. @@ -65,7 +65,7 @@ Optional browser QA: `python3 tests/browser_qa.py` uses an existing local Playwr ```text public/ HTML entry point and self-hosted assets -src/ Typed application, API helpers, RU/EN catalogs and CSS +src/ Typed application, API helpers, CSS; src/i18n/ holds the ru.ts and en.ts string dictionaries scripts/ Bun browser bundling, static build and loopback preview tests/ Bun regression tests and optional browser QA docs/ Design, deployment notes and repository-hosted screenshots @@ -86,7 +86,7 @@ The Hub sets Secure, HttpOnly cookies. Tokens are never stored in browser storag ## Contributing -Keep RU/EN catalog keys aligned, render profile values as text and retain keyboard navigation and reduced-motion support. Use descriptive Conventional Commits such as `fix(web): preserve account state when changing language`. Run type checks, tests, formatting checks and a production build before submitting a focused PR; include screenshots for visual changes. See [verification notes](docs/verification.md) for browser QA and current limits. +Keep RU/EN catalog keys aligned (`src/i18n/ru.ts` and `en.ts`; a test enforces it), follow the [copy guidelines](docs/copy-guidelines.md), never use the long dash character, render profile values as text and retain keyboard navigation and reduced-motion support. Use descriptive Conventional Commits such as `fix(web): preserve account state when changing language`. Run type checks, tests, formatting checks and a production build before submitting a focused PR; include screenshots for visual changes. See [verification notes](docs/verification.md) for browser QA and current limits. ## License diff --git a/docs/copy-guidelines.md b/docs/copy-guidelines.md new file mode 100644 index 0000000..9e210a1 --- /dev/null +++ b/docs/copy-guidelines.md @@ -0,0 +1,12 @@ +# Copy guidelines + +Short notes for writing site text in Russian and English. Based on README and landing-page advice from The Turing Way, openSUSE and others, Maxim Ilyakhov's "Пиши, сокращай" (Glavred stop-words), and articles on typical machine-written copy. + +- Say what the thing is and for whom in the first sentence. List real things (channels, DMs, roles, encrypted voice) instead of slogans. +- Write only what the code does today. Planned items go under "next", never in the main description. +- Cut hype and filler: no "revolutionary", "seamless", "ecosystem", "powerful", "unlock"; in Russian no "осуществлять", "является", "данный", "в рамках", "обеспечивает возможность". +- Avoid the "not X, but Y" construction, triplets for rhythm, and openers like "Let's take a look". One plain sentence beats two clever ones. +- Prefer verbs and short sentences. Do not translate word for word: write the Russian and English versions separately, each as a person would say it. +- Use a full stop, comma, colon or brackets. The long dash character is banned in all site text; `tests/copy.test.ts` greps sources, docs and the built bundle for it. +- Titles and og/meta text follow the same rule, for example "VNOX: voice and text chat on your own server". +- Every user-visible string lives in `src/i18n/ru.ts` and `en.ts`. Keys must match; a test checks it. diff --git a/docs/verification.md b/docs/verification.md index 8846554..3aeb14a 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -25,6 +25,6 @@ Local QA screenshots were visually inspected in `/tmp/vnox-web-qa/`. Any authent These frontend tests do not authorize a real GitHub user, verify provider consent or exercise Hub database/session internals. A live end-to-end GitHub authorization requires the account owner to complete provider consent. The loopback preview intentionally has no backend. Production deployment and HTTPS/security-header checks belong to the site's operator and must preserve the Hub's OAuth callback and cookie configuration. -## Production verification — 24 October 2026 +## Production verification: 24 October 2026 Published source commit `622f396364bb` to [central.loki-code.dev](https://central.loki-code.dev), static release `622f396364bb-9b77c9dbd02c`. Live Chromium checks passed for desktop landing, anonymous account/GitHub entry, mobile account layout, CSS MIME and JavaScript console. Hub readiness/info, logo assets and authentication endpoints remain available at the same origin. CSP uses self-hosted scripts/styles, no external fonts, same-origin API connections and a specific GitHub avatar image origin. OAuth callback query logging remains disabled. A real user's GitHub consent/code exchange remains a manual verification step. diff --git a/public/index.html b/public/index.html index 6af066d..67c33f7 100644 --- a/public/index.html +++ b/public/index.html @@ -6,9 +6,22 @@ - VNOX — Своя связь + + + + + + + + VNOX: голосовой и текстовый чат на своём сервере @@ -49,9 +62,7 @@ >VNOX -

- Сделано для разговоров, которые хочется продолжать. -

+

Клиент и сервер написаны на Rust.

('meta[name="description"]').content = t("description"); + find('meta[property="og:title"]').content = pageTitle; + find('meta[property="og:description"]').content = + t("description"); + find('meta[property="og:locale"]').content = + next === "ru" ? "ru_RU" : "en_US"; + find('meta[property="og:locale:alternate"]').content = + next === "ru" ? "en_US" : "ru_RU"; document .querySelectorAll("[data-i18n]") .forEach( diff --git a/src/i18n.ts b/src/i18n.ts deleted file mode 100644 index e36272f..0000000 --- a/src/i18n.ts +++ /dev/null @@ -1,284 +0,0 @@ -export const messages = { - ru: { - skip: "Перейти к содержимому", - nav: "Основная навигация", - navProject: "Проект", - navClient: "Клиент", - navRoadmap: "Дальше", - language: "Язык", - account: "Аккаунт", - footer: "Сделано для разговоров, которые хочется продолжать.", - source: "Исходный код", - title: "VNOX — Своя связь", - accountTitle: "Аккаунт — VNOX Central", - description: - "VNOX — голос и чат для своих сообществ. Нативный клиент, собственный сервер и открытый код.", - development: "В открытой разработке", - heroTitle: "Свои люди.\nСвоя связь.", - heroText: - "Место для вашего сообщества. Обсуждайте планы, оставайтесь в голосе и управляйте своим сервером сами.", - openCentral: "Открыть Vnox Central", - explore: "О проекте", - earlyNote: "Ранняя версия. Разрабатываем открыто, без обещаний на вырост.", - diagramLabel: "Схема общения", - diagramNote: "Иллюстрация устройства клиента", - textTab: "Текст", - voiceTab: "Голос", - themeTab: "Внешний вид", - community: "Ваше сообщество", - general: "общий", - ideas: "идеи", - voiceRoom: "Вечерний войс", - voiceConnected: "Голос остаётся с вами", - voiceExplain: "Переключайте текстовые каналы, не выходя из разговора.", - you: "Вы", - friend: "Друг", - messageSample: "Общий чат для идей, ссылок и планов.", - messageNote: "Чат и голос доступны в одном окне.", - voiceCaption: "Отдельное управление микрофоном и звуком.", - themeCaption: "Четыре варианта. Один ваш.", - light: "Светлая", - dark: "Тёмная", - black: "Мега-тёмная", - custom: "Своя", - preview: "Предпросмотр", - previewTheme: "Тема иллюстрации", - projectTitle: "Одно приложение.\nВаш сервер.", - projectText: - "VNOX объединяет текст и голос в нативном клиенте. Сервер сообщества запускается одним приложением и остаётся под управлением его владельца.", - projectNative: "Нативный клиент", - projectNativeText: - "Написан на Rust и Slint. Настройки звука, профиля и внешнего вида собраны в одном месте.", - projectServer: "Сервер сообщества", - projectServerText: - "Текстовые каналы и голос в одном серверном приложении. Владелец выбирает, где его запускать.", - projectCentral: "Vnox Central", - projectCentralText: - "Центральный сервис для аккаунта. Каталог серверов и друзья — следующие этапы разработки.", - clientCode: "Код клиента", - serverCode: "Код сервера", - clientTitle: "Удобство начинается\nс простых вещей.", - clientText: - "Светлая, тёмная, мега-тёмная или собственная тема. Размер текста, звук и профиль — там, где их ожидаешь найти.", - clientScreenshot: - "Настройки внешнего вида нативного клиента VNOX: четыре темы и размер текста.", - screenshotCaption: - "Настоящий снимок нативного клиента. Интерфейс продолжает развиваться.", - appearanceTitle: "Внешний вид — ваш", - appearanceText: - "Своя палитра через поддерживаемые CSS-переменные. Без загрузки внешних ресурсов.", - identityTitle: "Профиль без суеты", - identityText: - "Выберите фотографию, настройте масштаб и положение в круглом предпросмотре.", - roadmapTitle: "Сначала надёжная связь.\nПотом всё остальное.", - roadmapText: - "Проект ещё в разработке. Здесь разделены доступные части и то, над чем мы работаем.", - available: "Уже в коде", - next: "В работе и планах", - availableOne: "Нативный клиент, каналы и голос", - availableTwo: "Настройки, темы и редактор аватара", - availableThree: "Центральный сервис и защищённое соединение", - availableFour: "Веб-аккаунт GitHub и интерфейс RU / EN", - availableFive: "Входящие и подписанные исходящие вебхуки на сервере", - nextOne: "Управление вебхуками в клиенте", - nextTwo: "Трансляция экрана с раздельным звуком", - nextThree: "Друзья и поиск серверов", - downloadNote: - "Публичные сборки появятся после проверки совместимости клиента и сервера. Пока доступны исходники.", - faqTitle: "До первого разговора", - faqServer: "Нужен ли отдельный голосовой сервер?", - faqServerAnswer: - "Нет. Для сообщества планируется одно серверное приложение, которое включает чат и голос.", - faqCentral: "Зачем нужен Vnox Central?", - faqCentralAnswer: - "Для общего аккаунта и будущих социальных функций. Само сообщество размещает свой сервер отдельно.", - faqRelease: "Где скачать клиент?", - faqReleaseAnswer: - "Проверенного публичного релиза пока нет. Код клиента и сервера открыт; инструкции по сборке находятся в их репозиториях.", - statusLoading: "Проверяем Vnox Central…", - statusReady: "Vnox Central отвечает", - statusUnavailable: "Не удалось связаться с Vnox Central", - statusNote: "Состояние центрального сервиса", - retry: "Повторить", - back: "На главную", - accountHeading: "Ваш Vnox Central.", - accountIntro: - "Один аккаунт для будущих сообществ. Начните с безопасного входа через GitHub.", - loginTitle: "Продолжить с GitHub", - loginText: - "VNOX получает ваш публичный профиль GitHub. Доступ к репозиториям для входа не запрашивается.", - loginButton: "Войти через GitHub", - loginLoading: "Проверяем возможность входа…", - loginDisabled: "Вход через GitHub пока не включён на сервере.", - loginUnavailable: - "Не удалось проверить доступность входа. Повторите попытку.", - privacy: - "Авторизация происходит на github.com. Пароль GitHub остаётся у GitHub.", - accountStage: - "Центральный аккаунт пока не привязывается к локальным ключам настольного клиента. Друзья, серверы и сообщения появятся позже.", - sessionLoading: "Загружаем аккаунт…", - profileTitle: "Вы на связи.", - profileIntro: - "Вход через GitHub выполнен. Это ваш центральный аккаунт VNOX.", - handle: "Имя аккаунта", - userId: "ID аккаунта", - provider: "Способ входа", - logout: "Выйти из аккаунта", - loggingOut: "Выходим…", - logoutError: "Не удалось выйти. Повторите попытку.", - sessionExpired: "Сессия завершилась. Войдите снова.", - profileFallback: "Пользователь VNOX", - accountError: "Аккаунт сейчас недоступен", - accountErrorText: - "Не удалось загрузить сессию. Проверьте соединение и повторите попытку.", - copy: "Скопировать ID", - copied: "ID скопирован", - copyError: "Не удалось скопировать ID. Выделите его вручную.", - }, - en: { - skip: "Skip to content", - nav: "Main navigation", - navProject: "Project", - navClient: "Client", - navRoadmap: "What’s next", - language: "Language", - account: "Account", - footer: "Made for conversations you want to continue.", - source: "Source code", - title: "VNOX — Your own connection", - accountTitle: "Account — VNOX Central", - description: - "VNOX brings voice and chat to your community. Native client, your own server, open source.", - development: "In open development", - heroTitle: "Your people.\nYour connection.", - heroText: - "A place for your community. Share your plans, stay in voice and run your server on your terms.", - openCentral: "Open Vnox Central", - explore: "Explore the project", - earlyNote: "An early version, developed in the open.", - diagramLabel: "How you stay connected", - diagramNote: "An illustration of the client layout", - textTab: "Text", - voiceTab: "Voice", - themeTab: "Appearance", - community: "Your community", - general: "general", - ideas: "ideas", - voiceRoom: "Evening voice", - voiceConnected: "Voice stays with you", - voiceExplain: "Browse text channels without leaving the conversation.", - you: "You", - friend: "Friend", - messageSample: "A shared chat for ideas, links and plans.", - messageNote: "Chat and voice, together in one window.", - voiceCaption: "Separate controls for your microphone and sound.", - themeCaption: "Four options. One that’s yours.", - light: "Light", - dark: "Dark", - black: "Mega dark", - custom: "Custom", - preview: "Preview", - previewTheme: "Illustration theme", - projectTitle: "One application.\nYour own server.", - projectText: - "VNOX brings text and voice together in a native client. One server application runs your community, under its owner’s control.", - projectNative: "Native client", - projectNativeText: - "Built with Rust and Slint. Audio, profile and appearance settings, all in one place.", - projectServer: "Community server", - projectServerText: - "Text channels and voice in one server application. Its owner chooses where to run it.", - projectCentral: "Vnox Central", - projectCentralText: - "The central service for your account. Server discovery and friends are the next stages.", - clientCode: "Client source", - serverCode: "Server source", - clientTitle: "Comfort starts\nwith simple things.", - clientText: - "Light, dark, mega dark or your own theme. Text size, audio and your profile, right where you expect them.", - clientScreenshot: - "Appearance settings in the native VNOX client, with four themes and a text size slider.", - screenshotCaption: - "A real screenshot of the native client. The interface is still evolving.", - appearanceTitle: "Make it yours", - appearanceText: - "Create your palette with supported CSS variables. No external resources are loaded.", - identityTitle: "A profile without the fuss", - identityText: - "Choose a photo, then adjust its zoom and position inside a circular preview.", - roadmapTitle: "Reliable conversation first.\nThe rest comes next.", - roadmapText: - "VNOX is still being developed. Here is what exists in the code and what we’re building next.", - available: "Already in the code", - next: "In progress and planned", - availableOne: "Native client, channels and voice", - availableTwo: "Settings, themes and avatar editor", - availableThree: "Central service and HTTPS", - availableFour: "GitHub web account and RU / EN interface", - availableFive: "Incoming and signed outgoing server webhooks", - nextOne: "Webhook management in the client", - nextTwo: "Screen broadcasting with separate audio sources", - nextThree: "Friends and server discovery", - downloadNote: - "Public builds will follow client and server compatibility checks. Source code is available now.", - faqTitle: "Before the first conversation", - faqServer: "Do I need a separate voice server?", - faqServerAnswer: - "No. A community is intended to run one server application with both chat and voice.", - faqCentral: "What is Vnox Central for?", - faqCentralAnswer: - "Your shared account and future social features. Each community hosts its own server separately.", - faqRelease: "Where can I download the client?", - faqReleaseAnswer: - "There is no verified public release yet. Client and server code is open, with build instructions in their repositories.", - statusLoading: "Checking Vnox Central…", - statusReady: "Vnox Central is responding", - statusUnavailable: "Could not reach Vnox Central", - statusNote: "Central service status", - retry: "Try again", - back: "Back to home", - accountHeading: "Your Vnox Central.", - accountIntro: - "One account for future communities. Start with secure GitHub sign-in.", - loginTitle: "Continue with GitHub", - loginText: - "VNOX receives your public GitHub profile. Signing in does not request access to your repositories.", - loginButton: "Sign in with GitHub", - loginLoading: "Checking sign-in availability…", - loginDisabled: "GitHub sign-in is not enabled on the server yet.", - loginUnavailable: "Could not check sign-in availability. Try again.", - privacy: - "You authorize on github.com. Your GitHub password stays with GitHub.", - accountStage: - "Your central account is not yet linked to the desktop client’s local keys. Friends, servers and messages will follow.", - sessionLoading: "Loading your account…", - profileTitle: "You’re connected.", - profileIntro: "Signed in with GitHub. This is your central VNOX account.", - handle: "Account handle", - userId: "Account ID", - provider: "Signed in with", - logout: "Sign out", - loggingOut: "Signing out…", - logoutError: "Could not sign out. Try again.", - sessionExpired: "Your session ended. Sign in again.", - profileFallback: "VNOX user", - accountError: "Your account is currently unavailable", - accountErrorText: - "Could not load your session. Check your connection and try again.", - copy: "Copy account ID", - copied: "Account ID copied", - copyError: "Could not copy the ID. Select it manually.", - }, -} as const; -export type Language = keyof typeof messages; -export type MessageKey = keyof typeof messages.en; -export function detectLanguage( - saved: unknown, - languages: readonly string[] = [], -): Language { - if (saved === "ru" || saved === "en") return saved; - return languages.some((value) => /^ru(?:-|$)/i.test(value)) ? "ru" : "en"; -} -export function translate(language: Language, key: MessageKey): string { - return messages[language]?.[key] ?? messages.en[key] ?? key; -} diff --git a/src/i18n/en.ts b/src/i18n/en.ts new file mode 100644 index 0000000..32041cc --- /dev/null +++ b/src/i18n/en.ts @@ -0,0 +1,114 @@ +export const en = { + skip: "Skip to content", + nav: "Main navigation", + navProject: "Project", + navClient: "Client", + navRoadmap: "What’s next", + language: "Language", + account: "Account", + footer: "Client and server are written in Rust.", + source: "Source code", + title: "VNOX: voice and text chat on your own server", + accountTitle: "Account | VNOX Central", + description: "Voice and text chat you run yourself. Rust desktop client, channels, direct messages, friends, roles and encrypted UDP voice. Open source, GPLv3.", + development: "Early version, code is open", + heroTitle: "Voice and text chat\non your own server.", + heroText: "A desktop client written in Rust and a server you run yourself. Channels, direct messages, friends, roles and voice.", + openCentral: "Open Vnox Central", + explore: "Explore the project", + earlyNote: "Not production ready. What already works is listed below.", + diagramLabel: "What the client looks like", + diagramNote: "A schematic illustration, not a screenshot", + textTab: "Text", + voiceTab: "Voice", + themeTab: "Appearance", + community: "Your community", + general: "general", + ideas: "ideas", + voiceRoom: "Evening voice", + voiceConnected: "You are in a voice channel", + voiceExplain: "You can browse text channels without leaving voice.", + you: "You", + friend: "Friend", + messageSample: "A shared channel for ideas, links and plans.", + messageNote: "Text and voice in one window.", + voiceCaption: "Microphone modes: push to talk, voice activity or always on.", + themeCaption: "Light, dark, mega dark and your own.", + light: "Light", + dark: "Dark", + black: "Mega dark", + custom: "Custom", + preview: "Preview", + previewTheme: "Illustration theme", + projectTitle: "One client,\nyour own server.", + projectText: "VNOX is a chat with text and voice. You run the server on your own hardware, so the data and the users stay with you.", + projectNative: "Native client", + projectNativeText: "Written in Rust and Slint, no Electron or web view. Sign-in uses an Ed25519 key, so the server stores no passwords.", + projectServer: "Community server", + projectServerText: "The gateway (TCP) handles chat, guilds and roles, and the voice node (UDP) relays audio. There is also a combined daemon that runs both.", + projectCentral: "Vnox Central", + projectCentralText: "A web account with GitHub sign-in. It is not linked to the desktop client key yet.", + clientCode: "Client source", + serverCode: "Server source", + clientTitle: "Appearance settings", + clientText: "Four themes (light, dark, mega dark and custom), text size, audio and profile.", + clientScreenshot: "Appearance settings in the VNOX client: four themes and a text size slider.", + screenshotCaption: "A real screenshot of the client. The interface is still changing.", + appearanceTitle: "Your own theme", + appearanceText: "Set your own palette with CSS variables. No external resources are loaded.", + identityTitle: "Avatar", + identityText: "Pick a photo, then set its zoom and position in a round preview.", + roadmapTitle: "What exists and what is next", + roadmapText: "The project is in development. On the left is what is already in the code, on the right what we are still building.", + available: "Already in the code", + next: "In progress and planned", + availableOne: "Client, text channels and voice", + availableTwo: "Direct messages, friends, guilds and roles", + availableThree: "Voice encryption (ChaCha20-Poly1305) and key-based sign-in", + availableFour: "Web account through GitHub, site in Russian and English", + availableFive: "Incoming and signed outgoing webhooks on the server", + nextOne: "Webhook management in the client", + nextTwo: "Screen sharing with separate audio", + nextThree: "Server discovery and linking Central to the client key", + downloadNote: "There are no prebuilt downloads yet. You can build the client and server from source.", + faqTitle: "FAQ", + faqServer: "Do I need a separate voice server?", + faqServerAnswer: "No. The gateway and the voice node can run as one daemon (serverd).", + faqCentral: "What is Vnox Central for?", + faqCentralAnswer: "It is a web account with GitHub sign-in. A community server runs on its own and does not depend on Central.", + faqRelease: "Where can I download the client?", + faqReleaseAnswer: "Nowhere yet. The client and server sources are open, and build instructions are in their repositories.", + statusLoading: "Checking Vnox Central…", + statusReady: "Vnox Central is up", + statusUnavailable: "Could not reach Vnox Central", + statusNote: "Central service status", + retry: "Try again", + back: "Back to home", + accountHeading: "Your Vnox Central account", + accountIntro: "For now you can sign in with GitHub. There is nothing else to do with the account yet.", + loginTitle: "Continue with GitHub", + loginText: "VNOX gets your public GitHub profile. It does not ask for access to your repositories.", + loginButton: "Sign in with GitHub", + loginLoading: "Checking sign-in availability…", + loginDisabled: "GitHub sign-in is turned off on the server.", + loginUnavailable: "Could not check sign-in availability. Try again.", + privacy: "You sign in on github.com. Your GitHub password stays with GitHub.", + accountStage: "The account is not linked to the desktop client keys yet. Friends, servers and messages will be added later.", + sessionLoading: "Loading your account…", + profileTitle: "You are signed in", + profileIntro: "Signed in with GitHub. This is your VNOX Central account.", + handle: "Account handle", + userId: "Account ID", + provider: "Signed in with", + logout: "Sign out", + loggingOut: "Signing out…", + logoutError: "Could not sign out. Try again.", + profileFallback: "VNOX user", + accountError: "Your account is currently unavailable", + accountErrorText: + "Could not load your session. Check your connection and try again.", + copy: "Copy account ID", + copied: "Account ID copied", + copyError: "Could not copy the ID. Select it manually.", +} as const; +export type Catalog = Record; diff --git a/src/i18n/index.ts b/src/i18n/index.ts new file mode 100644 index 0000000..d672fcf --- /dev/null +++ b/src/i18n/index.ts @@ -0,0 +1,19 @@ +import { en } from "./en"; +import { ru } from "./ru"; + +export const messages = { ru, en } as const; +export type Language = keyof typeof messages; +export type MessageKey = keyof typeof en; +export const languages = Object.keys(messages) as Language[]; + +/** Saved choice wins; otherwise Russian for ru locales, English for the rest. */ +export function detectLanguage( + saved: unknown, + languages: readonly string[] = [], +): Language { + if (saved === "ru" || saved === "en") return saved; + return languages.some((value) => /^ru(?:-|$)/i.test(value)) ? "ru" : "en"; +} +export function translate(language: Language, key: MessageKey): string { + return messages[language]?.[key] ?? messages.en[key] ?? key; +} diff --git a/src/i18n/ru.ts b/src/i18n/ru.ts new file mode 100644 index 0000000..b50b9d7 --- /dev/null +++ b/src/i18n/ru.ts @@ -0,0 +1,116 @@ +import type { Catalog } from "./en"; + +export const ru: Catalog = { + skip: "Перейти к содержимому", + nav: "Основная навигация", + navProject: "Проект", + navClient: "Клиент", + navRoadmap: "Дальше", + language: "Язык", + account: "Аккаунт", + footer: "Клиент и сервер написаны на Rust.", + source: "Исходный код", + title: "VNOX: голосовой и текстовый чат на своём сервере", + accountTitle: "Аккаунт | VNOX Central", + description: "Голосовой и текстовый чат, который вы запускаете сами. Клиент на Rust, каналы, личные сообщения, друзья, роли и шифрованный голос по UDP. Открытый код, GPLv3.", + development: "Ранняя версия, код открыт", + heroTitle: "Голос и чат\nна вашем сервере.", + heroText: "Десктопный клиент на Rust и сервер, который вы запускаете сами. Каналы, личные сообщения, друзья, роли и голос.", + openCentral: "Открыть Vnox Central", + explore: "О проекте", + earlyNote: "Не готово для продакшена. Что уже работает, написано ниже.", + diagramLabel: "Как выглядит клиент", + diagramNote: "Схематичная иллюстрация, не снимок экрана", + textTab: "Текст", + voiceTab: "Голос", + themeTab: "Внешний вид", + community: "Ваше сообщество", + general: "общий", + ideas: "идеи", + voiceRoom: "Вечерний войс", + voiceConnected: "Вы в голосовом канале", + voiceExplain: "Текстовые каналы можно листать, не выходя из голосового.", + you: "Вы", + friend: "Друг", + messageSample: "Общий канал для идей, ссылок и планов.", + messageNote: "Текст и голос в одном окне.", + voiceCaption: "Режимы микрофона: PTT, VAD или всегда включён.", + themeCaption: "Светлая, тёмная, мега-тёмная и своя.", + light: "Светлая", + dark: "Тёмная", + black: "Мега-тёмная", + custom: "Своя", + preview: "Предпросмотр", + previewTheme: "Тема иллюстрации", + projectTitle: "Один клиент,\nваш сервер.", + projectText: "VNOX это чат с текстом и голосом. Сервер вы запускаете на своём железе, а данные и пользователи остаются у вас.", + projectNative: "Нативный клиент", + projectNativeText: "Написан на Rust и Slint, без Electron и веб-вида. Вход по ключу Ed25519, без паролей на сервере.", + projectServer: "Сервер сообщества", + projectServerText: "Шлюз (TCP) отвечает за чат, гильдии и роли, голосовой узел (UDP) пересылает звук. Есть и общий демон для обоих.", + projectCentral: "Vnox Central", + projectCentralText: "Веб-аккаунт с входом через GitHub. С ключом настольного клиента он пока не связан.", + clientCode: "Код клиента", + serverCode: "Код сервера", + clientTitle: "Настройки внешнего вида", + clientText: "Четыре темы (светлая, тёмная, мега-тёмная и своя), размер текста, звук и профиль.", + clientScreenshot: "Настройки внешнего вида в клиенте VNOX: четыре темы и размер текста.", + screenshotCaption: "Настоящий снимок клиента. Интерфейс ещё меняется.", + appearanceTitle: "Своя тема", + appearanceText: "Палитру можно задать через CSS-переменные. Внешние ресурсы не загружаются.", + identityTitle: "Аватар", + identityText: "Выберите фото и подберите масштаб и положение в круглой рамке.", + roadmapTitle: "Что есть, а что будет", + roadmapText: "Проект в разработке. Слева то, что уже есть в коде, справа то, что ещё делаем.", + available: "Уже в коде", + next: "В работе и планах", + availableOne: "Клиент, текстовые каналы и голос", + availableTwo: "Личные сообщения, друзья, гильдии и роли", + availableThree: "Шифрование голоса (ChaCha20-Poly1305) и вход по ключу", + availableFour: "Веб-аккаунт через GitHub, сайт на русском и английском", + availableFive: "Входящие и подписанные исходящие вебхуки на сервере", + nextOne: "Управление вебхуками в клиенте", + nextTwo: "Трансляция экрана с отдельным звуком", + nextThree: "Поиск серверов и привязка Central к ключу клиента", + downloadNote: "Готовых сборок пока нет. Клиент и сервер можно собрать из исходников.", + faqTitle: "Частые вопросы", + faqServer: "Нужен ли отдельный голосовой сервер?", + faqServerAnswer: "Нет. Шлюз и голосовой узел можно запустить одним демоном (serverd).", + faqCentral: "Зачем нужен Vnox Central?", + faqCentralAnswer: "Это веб-аккаунт с входом через GitHub. Сервер сообщества работает отдельно и от Central не зависит.", + faqRelease: "Где скачать клиент?", + faqReleaseAnswer: "Пока нигде. Исходники клиента и сервера открыты, инструкции по сборке лежат в их репозиториях.", + statusLoading: "Проверяем Vnox Central…", + statusReady: "Vnox Central отвечает", + statusUnavailable: "Не удалось связаться с Vnox Central", + statusNote: "Состояние центрального сервиса", + retry: "Повторить", + back: "На главную", + accountHeading: "Аккаунт Vnox Central", + accountIntro: "Пока можно войти через GitHub. Больше с аккаунтом ничего не сделать.", + loginTitle: "Продолжить с GitHub", + loginText: "VNOX получает ваш публичный профиль GitHub. Доступ к репозиториям не запрашивается.", + loginButton: "Войти через GitHub", + loginLoading: "Проверяем возможность входа…", + loginDisabled: "Вход через GitHub на сервере пока выключен.", + loginUnavailable: + "Не удалось проверить доступность входа. Повторите попытку.", + privacy: "Вход проходит на github.com. Пароль от GitHub остаётся у GitHub.", + accountStage: "Аккаунт пока не связан с ключами настольного клиента. Друзья, серверы и сообщения в нём появятся позже.", + sessionLoading: "Загружаем аккаунт…", + profileTitle: "Вы вошли", + profileIntro: "Вход через GitHub выполнен. Это ваш аккаунт VNOX Central.", + handle: "Имя аккаунта", + userId: "ID аккаунта", + provider: "Способ входа", + logout: "Выйти из аккаунта", + loggingOut: "Выходим…", + logoutError: "Не удалось выйти. Повторите попытку.", + profileFallback: "Пользователь VNOX", + accountError: "Аккаунт сейчас недоступен", + accountErrorText: + "Не удалось загрузить сессию. Проверьте соединение и повторите попытку.", + copy: "Скопировать ID", + copied: "ID скопирован", + copyError: "Не удалось скопировать ID. Выделите его вручную.", +}; diff --git a/tests/browser_qa.py b/tests/browser_qa.py index 41479aa..707e629 100644 --- a/tests/browser_qa.py +++ b/tests/browser_qa.py @@ -44,7 +44,11 @@ with sync_playwright() as p: page.locator('[data-theme="light"]').click() assert page.locator('.product-diagram').get_attribute('data-preview-theme') == 'light' page.locator('[data-language="en"]').click() - assert page.locator('h1').inner_text() == 'Your people.\nYour connection.' + assert page.locator('h1').inner_text() == 'Voice and text chat\non your own server.' + assert page.evaluate('document.documentElement.lang') == 'en' + assert page.title() == 'VNOX: voice and text chat on your own server' + assert page.locator('meta[property="og:title"]').get_attribute('content') == page.title() + assert '\u2014' not in page.content() assert page.locator('[data-tab="theme"]').get_attribute('aria-selected') == 'true' assert page.locator('[data-theme="light"]').get_attribute('aria-pressed') == 'true' for locale in ['en', 'ru']: @@ -60,7 +64,7 @@ with sync_playwright() as p: page.screenshot(path=str(artifacts / 'account-login-mobile.png'), full_page=True) state['info'] = {'capabilities': {'github_auth': 'not_enabled'}} page.reload() - page.locator('#login-availability').filter(has_text='не включён').wait_for() + page.locator('#login-availability').filter(has_text='выключен').wait_for() assert page.locator('.github-login').get_attribute('href') is None state['info_status'] = 503 page.reload() diff --git a/tests/copy.test.ts b/tests/copy.test.ts new file mode 100644 index 0000000..d0155a7 --- /dev/null +++ b/tests/copy.test.ts @@ -0,0 +1,102 @@ +import { test } from "bun:test"; +import assert from "node:assert/strict"; +import { readdir, readFile, stat } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { en } from "../src/i18n/en"; +import { ru } from "../src/i18n/ru"; +import { messages, languages } from "../src/i18n"; +import { browserBundle } from "../scripts/browser"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const LONG_DASH = String.fromCharCode(0x2014); +const text = (path: string) => readFile(root + path, "utf8"); + +async function walk(dir: string): Promise { + const out: string[] = []; + for (const entry of await readdir(root + dir, { withFileTypes: true })) { + const path = `${dir}/${entry.name}`; + if (entry.isDirectory()) out.push(...(await walk(path))); + else if (/\.(ts|css|html|md|svg|conf|py|json)$/.test(entry.name)) + out.push(path); + } + return out; +} + +test("ru and en dictionaries have identical, non-empty keys", () => { + assert.deepEqual(Object.keys(ru).sort(), Object.keys(en).sort()); + assert.deepEqual([...languages].sort(), ["en", "ru"]); + for (const catalog of Object.values(messages)) + for (const [key, value] of Object.entries(catalog)) + assert.ok(value.trim().length > 0, key); +}); + +test("every translation key used in code exists and every key is used", async () => { + const code = (await text("src/app.ts")) + (await text("public/index.html")); + const used = new Set(); + for (const m of code.matchAll( + /(?:data-i18n(?:-aria|-alt)?="|\btr\(\s*|\bt\(\s*)["`]?([A-Za-z]+)/g, + )) + used.add(m[1]!); + // Keys built from a template, e.g. faq${key} and faq${key}Answer. + for (const part of ["Server", "Central", "Release"]) { + used.add(`faq${part}`); + used.add(`faq${part}Answer`); + } + for (const m of code.matchAll(/\b(?:tr|t)\(\s*"([A-Za-z]+)"/g)) used.add(m[1]!); + for (const m of code.matchAll(/\(\[((?:"[a-z]+",?\s*)+)\] as const\)/g)) + for (const k of m[1]!.matchAll(/"([a-z]+)"/g)) used.add(k[1]!); + for (const key of Object.keys(en)) { + if (!used.has(key)) { + // Keys chosen through ternaries are still named literally in app.ts. + assert.ok(code.includes(`"${key}"`), `unused key: ${key}`); + } + } + for (const key of used) + if (/^[a-z][A-Za-z]+$/.test(key) && !(key in en)) { + // Ignore non-key words matched by the loose regex. + assert.ok( + !code.includes(`data-i18n="${key}"`), + `missing key in dictionary: ${key}`, + ); + } +}); + +test("static HTML fallback text matches the Russian dictionary", async () => { + const html = await text("public/index.html"); + const flat = (value: string) => value.replace(/\s+/g, " ").trim(); + for (const m of html.matchAll( + /data-i18n="([A-Za-z]+)"[^>]*>([^<]*)${ru.title}`)); + assert.ok(html.includes(`content="${ru.description}"`)); + assert.ok(html.includes(`property="og:title"\n content="${ru.title}"`)); + assert.match(html, //); +}); + +test("the long dash is absent from sources, docs, public/ and the browser bundle", async () => { + const files = [ + "README.md", + ...(await walk("src")), + ...(await walk("public")), + ...(await walk("docs")), + ...(await walk("tests")), + ...(await walk("scripts")), + ]; + const bad: string[] = []; + for (const file of files) + if ((await text(file)).includes(LONG_DASH)) bad.push(file); + const bundle = await (await browserBundle(true)).text(); + if (bundle.includes(LONG_DASH)) bad.push("browser bundle"); + try { + await stat(root + "dist"); + for (const file of await walk("dist")) + if ((await text(file)).includes(LONG_DASH)) bad.push(file); + } catch { + /* dist/ is optional. */ + } + assert.deepEqual(bad, []); +}); From 769e25a705d673bc47ea2243844461b56cca3a47 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 17:04:46 +0200 Subject: [PATCH 2/3] style(web): apply bun fmt formatting --- src/i18n/en.ts | 57 ++++++++++++++++++++++++++++++---------------- src/i18n/ru.ts | 54 ++++++++++++++++++++++++++++--------------- tests/copy.test.ts | 7 +++--- 3 files changed, 77 insertions(+), 41 deletions(-) diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 32041cc..bbff1bb 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -10,10 +10,12 @@ export const en = { source: "Source code", title: "VNOX: voice and text chat on your own server", accountTitle: "Account | VNOX Central", - description: "Voice and text chat you run yourself. Rust desktop client, channels, direct messages, friends, roles and encrypted UDP voice. Open source, GPLv3.", + description: + "Voice and text chat you run yourself. Rust desktop client, channels, direct messages, friends, roles and encrypted UDP voice. Open source, GPLv3.", development: "Early version, code is open", heroTitle: "Voice and text chat\non your own server.", - heroText: "A desktop client written in Rust and a server you run yourself. Channels, direct messages, friends, roles and voice.", + heroText: + "A desktop client written in Rust and a server you run yourself. Channels, direct messages, friends, roles and voice.", openCentral: "Open Vnox Central", explore: "Explore the project", earlyNote: "Not production ready. What already works is listed below.", @@ -41,25 +43,35 @@ export const en = { preview: "Preview", previewTheme: "Illustration theme", projectTitle: "One client,\nyour own server.", - projectText: "VNOX is a chat with text and voice. You run the server on your own hardware, so the data and the users stay with you.", + projectText: + "VNOX is a chat with text and voice. You run the server on your own hardware, so the data and the users stay with you.", projectNative: "Native client", - projectNativeText: "Written in Rust and Slint, no Electron or web view. Sign-in uses an Ed25519 key, so the server stores no passwords.", + projectNativeText: + "Written in Rust and Slint, no Electron or web view. Sign-in uses an Ed25519 key, so the server stores no passwords.", projectServer: "Community server", - projectServerText: "The gateway (TCP) handles chat, guilds and roles, and the voice node (UDP) relays audio. There is also a combined daemon that runs both.", + projectServerText: + "The gateway (TCP) handles chat, guilds and roles, and the voice node (UDP) relays audio. There is also a combined daemon that runs both.", projectCentral: "Vnox Central", - projectCentralText: "A web account with GitHub sign-in. It is not linked to the desktop client key yet.", + projectCentralText: + "A web account with GitHub sign-in. It is not linked to the desktop client key yet.", clientCode: "Client source", serverCode: "Server source", clientTitle: "Appearance settings", - clientText: "Four themes (light, dark, mega dark and custom), text size, audio and profile.", - clientScreenshot: "Appearance settings in the VNOX client: four themes and a text size slider.", - screenshotCaption: "A real screenshot of the client. The interface is still changing.", + clientText: + "Four themes (light, dark, mega dark and custom), text size, audio and profile.", + clientScreenshot: + "Appearance settings in the VNOX client: four themes and a text size slider.", + screenshotCaption: + "A real screenshot of the client. The interface is still changing.", appearanceTitle: "Your own theme", - appearanceText: "Set your own palette with CSS variables. No external resources are loaded.", + appearanceText: + "Set your own palette with CSS variables. No external resources are loaded.", identityTitle: "Avatar", - identityText: "Pick a photo, then set its zoom and position in a round preview.", + identityText: + "Pick a photo, then set its zoom and position in a round preview.", roadmapTitle: "What exists and what is next", - roadmapText: "The project is in development. On the left is what is already in the code, on the right what we are still building.", + roadmapText: + "The project is in development. On the left is what is already in the code, on the right what we are still building.", available: "Already in the code", next: "In progress and planned", availableOne: "Client, text channels and voice", @@ -70,14 +82,18 @@ export const en = { nextOne: "Webhook management in the client", nextTwo: "Screen sharing with separate audio", nextThree: "Server discovery and linking Central to the client key", - downloadNote: "There are no prebuilt downloads yet. You can build the client and server from source.", + downloadNote: + "There are no prebuilt downloads yet. You can build the client and server from source.", faqTitle: "FAQ", faqServer: "Do I need a separate voice server?", - faqServerAnswer: "No. The gateway and the voice node can run as one daemon (serverd).", + faqServerAnswer: + "No. The gateway and the voice node can run as one daemon (serverd).", faqCentral: "What is Vnox Central for?", - faqCentralAnswer: "It is a web account with GitHub sign-in. A community server runs on its own and does not depend on Central.", + faqCentralAnswer: + "It is a web account with GitHub sign-in. A community server runs on its own and does not depend on Central.", faqRelease: "Where can I download the client?", - faqReleaseAnswer: "Nowhere yet. The client and server sources are open, and build instructions are in their repositories.", + faqReleaseAnswer: + "Nowhere yet. The client and server sources are open, and build instructions are in their repositories.", statusLoading: "Checking Vnox Central…", statusReady: "Vnox Central is up", statusUnavailable: "Could not reach Vnox Central", @@ -85,15 +101,18 @@ export const en = { retry: "Try again", back: "Back to home", accountHeading: "Your Vnox Central account", - accountIntro: "For now you can sign in with GitHub. There is nothing else to do with the account yet.", + accountIntro: + "For now you can sign in with GitHub. There is nothing else to do with the account yet.", loginTitle: "Continue with GitHub", - loginText: "VNOX gets your public GitHub profile. It does not ask for access to your repositories.", + loginText: + "VNOX gets your public GitHub profile. It does not ask for access to your repositories.", loginButton: "Sign in with GitHub", loginLoading: "Checking sign-in availability…", loginDisabled: "GitHub sign-in is turned off on the server.", loginUnavailable: "Could not check sign-in availability. Try again.", privacy: "You sign in on github.com. Your GitHub password stays with GitHub.", - accountStage: "The account is not linked to the desktop client keys yet. Friends, servers and messages will be added later.", + accountStage: + "The account is not linked to the desktop client keys yet. Friends, servers and messages will be added later.", sessionLoading: "Loading your account…", profileTitle: "You are signed in", profileIntro: "Signed in with GitHub. This is your VNOX Central account.", diff --git a/src/i18n/ru.ts b/src/i18n/ru.ts index b50b9d7..fcf6695 100644 --- a/src/i18n/ru.ts +++ b/src/i18n/ru.ts @@ -12,10 +12,12 @@ export const ru: Catalog = { source: "Исходный код", title: "VNOX: голосовой и текстовый чат на своём сервере", accountTitle: "Аккаунт | VNOX Central", - description: "Голосовой и текстовый чат, который вы запускаете сами. Клиент на Rust, каналы, личные сообщения, друзья, роли и шифрованный голос по UDP. Открытый код, GPLv3.", + description: + "Голосовой и текстовый чат, который вы запускаете сами. Клиент на Rust, каналы, личные сообщения, друзья, роли и шифрованный голос по UDP. Открытый код, GPLv3.", development: "Ранняя версия, код открыт", heroTitle: "Голос и чат\nна вашем сервере.", - heroText: "Десктопный клиент на Rust и сервер, который вы запускаете сами. Каналы, личные сообщения, друзья, роли и голос.", + heroText: + "Десктопный клиент на Rust и сервер, который вы запускаете сами. Каналы, личные сообщения, друзья, роли и голос.", openCentral: "Открыть Vnox Central", explore: "О проекте", earlyNote: "Не готово для продакшена. Что уже работает, написано ниже.", @@ -43,25 +45,34 @@ export const ru: Catalog = { preview: "Предпросмотр", previewTheme: "Тема иллюстрации", projectTitle: "Один клиент,\nваш сервер.", - projectText: "VNOX это чат с текстом и голосом. Сервер вы запускаете на своём железе, а данные и пользователи остаются у вас.", + projectText: + "VNOX это чат с текстом и голосом. Сервер вы запускаете на своём железе, а данные и пользователи остаются у вас.", projectNative: "Нативный клиент", - projectNativeText: "Написан на Rust и Slint, без Electron и веб-вида. Вход по ключу Ed25519, без паролей на сервере.", + projectNativeText: + "Написан на Rust и Slint, без Electron и веб-вида. Вход по ключу Ed25519, без паролей на сервере.", projectServer: "Сервер сообщества", - projectServerText: "Шлюз (TCP) отвечает за чат, гильдии и роли, голосовой узел (UDP) пересылает звук. Есть и общий демон для обоих.", + projectServerText: + "Шлюз (TCP) отвечает за чат, гильдии и роли, голосовой узел (UDP) пересылает звук. Есть и общий демон для обоих.", projectCentral: "Vnox Central", - projectCentralText: "Веб-аккаунт с входом через GitHub. С ключом настольного клиента он пока не связан.", + projectCentralText: + "Веб-аккаунт с входом через GitHub. С ключом настольного клиента он пока не связан.", clientCode: "Код клиента", serverCode: "Код сервера", clientTitle: "Настройки внешнего вида", - clientText: "Четыре темы (светлая, тёмная, мега-тёмная и своя), размер текста, звук и профиль.", - clientScreenshot: "Настройки внешнего вида в клиенте VNOX: четыре темы и размер текста.", + clientText: + "Четыре темы (светлая, тёмная, мега-тёмная и своя), размер текста, звук и профиль.", + clientScreenshot: + "Настройки внешнего вида в клиенте VNOX: четыре темы и размер текста.", screenshotCaption: "Настоящий снимок клиента. Интерфейс ещё меняется.", appearanceTitle: "Своя тема", - appearanceText: "Палитру можно задать через CSS-переменные. Внешние ресурсы не загружаются.", + appearanceText: + "Палитру можно задать через CSS-переменные. Внешние ресурсы не загружаются.", identityTitle: "Аватар", - identityText: "Выберите фото и подберите масштаб и положение в круглой рамке.", + identityText: + "Выберите фото и подберите масштаб и положение в круглой рамке.", roadmapTitle: "Что есть, а что будет", - roadmapText: "Проект в разработке. Слева то, что уже есть в коде, справа то, что ещё делаем.", + roadmapText: + "Проект в разработке. Слева то, что уже есть в коде, справа то, что ещё делаем.", available: "Уже в коде", next: "В работе и планах", availableOne: "Клиент, текстовые каналы и голос", @@ -72,14 +83,18 @@ export const ru: Catalog = { nextOne: "Управление вебхуками в клиенте", nextTwo: "Трансляция экрана с отдельным звуком", nextThree: "Поиск серверов и привязка Central к ключу клиента", - downloadNote: "Готовых сборок пока нет. Клиент и сервер можно собрать из исходников.", + downloadNote: + "Готовых сборок пока нет. Клиент и сервер можно собрать из исходников.", faqTitle: "Частые вопросы", faqServer: "Нужен ли отдельный голосовой сервер?", - faqServerAnswer: "Нет. Шлюз и голосовой узел можно запустить одним демоном (serverd).", + faqServerAnswer: + "Нет. Шлюз и голосовой узел можно запустить одним демоном (serverd).", faqCentral: "Зачем нужен Vnox Central?", - faqCentralAnswer: "Это веб-аккаунт с входом через GitHub. Сервер сообщества работает отдельно и от Central не зависит.", + faqCentralAnswer: + "Это веб-аккаунт с входом через GitHub. Сервер сообщества работает отдельно и от Central не зависит.", faqRelease: "Где скачать клиент?", - faqReleaseAnswer: "Пока нигде. Исходники клиента и сервера открыты, инструкции по сборке лежат в их репозиториях.", + faqReleaseAnswer: + "Пока нигде. Исходники клиента и сервера открыты, инструкции по сборке лежат в их репозиториях.", statusLoading: "Проверяем Vnox Central…", statusReady: "Vnox Central отвечает", statusUnavailable: "Не удалось связаться с Vnox Central", @@ -87,16 +102,19 @@ export const ru: Catalog = { retry: "Повторить", back: "На главную", accountHeading: "Аккаунт Vnox Central", - accountIntro: "Пока можно войти через GitHub. Больше с аккаунтом ничего не сделать.", + accountIntro: + "Пока можно войти через GitHub. Больше с аккаунтом ничего не сделать.", loginTitle: "Продолжить с GitHub", - loginText: "VNOX получает ваш публичный профиль GitHub. Доступ к репозиториям не запрашивается.", + loginText: + "VNOX получает ваш публичный профиль GitHub. Доступ к репозиториям не запрашивается.", loginButton: "Войти через GitHub", loginLoading: "Проверяем возможность входа…", loginDisabled: "Вход через GitHub на сервере пока выключен.", loginUnavailable: "Не удалось проверить доступность входа. Повторите попытку.", privacy: "Вход проходит на github.com. Пароль от GitHub остаётся у GitHub.", - accountStage: "Аккаунт пока не связан с ключами настольного клиента. Друзья, серверы и сообщения в нём появятся позже.", + accountStage: + "Аккаунт пока не связан с ключами настольного клиента. Друзья, серверы и сообщения в нём появятся позже.", sessionLoading: "Загружаем аккаунт…", profileTitle: "Вы вошли", profileIntro: "Вход через GitHub выполнен. Это ваш аккаунт VNOX Central.", diff --git a/tests/copy.test.ts b/tests/copy.test.ts index d0155a7..4f7ccc3 100644 --- a/tests/copy.test.ts +++ b/tests/copy.test.ts @@ -42,7 +42,8 @@ test("every translation key used in code exists and every key is used", async () used.add(`faq${part}`); used.add(`faq${part}Answer`); } - for (const m of code.matchAll(/\b(?:tr|t)\(\s*"([A-Za-z]+)"/g)) used.add(m[1]!); + for (const m of code.matchAll(/\b(?:tr|t)\(\s*"([A-Za-z]+)"/g)) + used.add(m[1]!); for (const m of code.matchAll(/\(\[((?:"[a-z]+",?\s*)+)\] as const\)/g)) for (const k of m[1]!.matchAll(/"([a-z]+)"/g)) used.add(k[1]!); for (const key of Object.keys(en)) { @@ -64,9 +65,7 @@ test("every translation key used in code exists and every key is used", async () test("static HTML fallback text matches the Russian dictionary", async () => { const html = await text("public/index.html"); const flat = (value: string) => value.replace(/\s+/g, " ").trim(); - for (const m of html.matchAll( - /data-i18n="([A-Za-z]+)"[^>]*>([^<]*)]*>([^<]*) Date: Sat, 24 Oct 2026 17:11:40 +0200 Subject: [PATCH 3/3] feat(web): add light client memory block and scroll animations --- README.md | 1 + docs/design.md | 2 + docs/memory-sources.md | 17 ++++ src/app.ts | 49 ++++++++-- src/i18n/en.ts | 15 +++ src/i18n/ru.ts | 15 +++ src/styles.css | 207 +++++++++++++++++++++++++++++++++++++++++ tests/browser_qa.py | 11 +++ 8 files changed, 311 insertions(+), 6 deletions(-) create mode 100644 docs/memory-sources.md diff --git a/README.md b/README.md index a59eac3..1b6c920 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ Actual screenshots of [central.loki-code.dev](https://central.loki-code.dev), ca - Responsive Russian/English project pages with the approved VNOX mark. - Interactive, clearly labelled layout illustration and a real native-client screenshot. +- A "light client" block with measured memory use (sources in [docs/memory-sources.md](docs/memory-sources.md)), scroll reveal and a counter that respects `prefers-reduced-motion`. - Account loading, signed-out, signed-in, unavailable and sign-out states. - GitHub sign-in through VNOX Hub, same-origin cookies and CSRF-protected sign-out. - Explicit early-development status; no invented releases, people or download links. diff --git a/docs/design.md b/docs/design.md index e5a0414..d6fb66c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -23,3 +23,5 @@ Central status Footer ``` Review: a giant neutral product screenshot alone would feel like any desktop-app page. The hero instead explains persistent voice while browsing text through an intentionally small, labelled diagram. Real native-client imagery appears where it supports the appearance/settings explanation. Sand is the approved V brand colour, not a secondary decorative accent. + +Motion: sections fade in on scroll (IntersectionObserver), the hero enters once, the voice waveform and connection dots pulse softly, buttons and cards lift on hover. The memory block draws a short sand bar for VNOX against a long stone bar and counts up to 120 MB when it scrolls into view. All of it is plain CSS plus a small script, and it is switched off under `prefers-reduced-motion: reduce` (the final values are shown at once). Memory numbers and their sources: `docs/memory-sources.md`. diff --git a/docs/memory-sources.md b/docs/memory-sources.md new file mode 100644 index 0000000..8c61126 --- /dev/null +++ b/docs/memory-sources.md @@ -0,0 +1,17 @@ +# Memory figures on the site + +Block "A light client" on the landing page. All numbers were measured on Linux with `/proc` (RSS and PSS summed over all processes of the app). + +| App | State | RSS | PSS | +| --- | --- | --- | --- | +| VNOX client (Rust + Slint, release build) | idle, connection screen | 121 MB | 96 MB | +| Discord in the Vesktop Electron client, 8 processes | in use | 1333 MB | 1103 MB | + +The site says "about 120 MB" for VNOX (RSS 121 MB, not rounded to 100) and "about 1.3 GB" for Discord by the same RSS metric; PSS is stated in the text. The states differ (idle vs in use), and the site says so. Bar length is 1.3 GB. + +General statement "Electron clients often use from a few hundred MB to a gigabyte and more" rests on press reports, not on our measurement: + +- PCWorld, 9 December 2025, https://www.pcworld.com/article/3005317/discord-admits-windows-11-app-hogs-ram-tries-solving-it-with-auto-restarts.html : Discord's memory use is typically around 1 GB; Discord tests an automatic restart above 4 GB. +- Windows Latest, 27 September 2026, https://www.windowslatest.com/2026/09/27/electron-is-one-of-windows-11s-biggest-ram-offenders-and-discords-game-mode-doesnt-fix-it/ : a Discord employee said normal usage should stay under 1 GB (December 2025). No measurement method is given there. + +No other product is given a number. Electron apps vary widely, so no claim is made about them as a group beyond "often". diff --git a/src/app.ts b/src/app.ts index 46d5deb..70efef2 100644 --- a/src/app.ts +++ b/src/app.ts @@ -67,7 +67,7 @@ const external = (href: string, key: MessageKey) => `${tr(key)}${icon("external", 15)}`; function landing() { main.innerHTML = ` -
+

${tr("development")}

${tr("heroTitle", "h1", 'id="hero-title"')}${tr("heroText", "p", 'class="hero-description"')} ${tr("earlyNote", "p", 'class="small hero-note"')}
${tr("diagramLabel")}
@@ -76,12 +76,14 @@ function landing() {
${tr("diagramNote", "p", 'class="small diagram-note"')}
-
${tr("projectTitle", "h2", 'id="project-title"')}${tr("projectText", "p")}
${icon("chat", 24)}
${tr("projectNative", "h3")}${tr("projectNativeText", "p")}
${icon("voice", 24)}
${tr("projectServer", "h3")}${tr("projectServerText", "p")}
${tr("projectCentral", "h3")}${tr("projectCentralText", "p")}
-
${tr("clientTitle", "h2", 'id="client-title"')}${tr("clientText", "p")}
${t(${tr("screenshotCaption", "figcaption")}
${tr("appearanceTitle", "h3")}${tr("appearanceText", "p")}
${tr("identityTitle", "h3")}${tr("identityText", "p")}
-
${tr("roadmapTitle", "h2", 'id="roadmap-title"')}${tr("roadmapText", "p")}

${tr("available")}

  • ${tr("availableOne")}
  • ${tr("availableTwo")}
  • ${tr("availableThree")}
  • ${tr("availableFour")}
  • ${tr("availableFive")}

${tr("next")}

  • ${tr("nextOne")}
  • ${tr("nextTwo")}
  • ${tr("nextThree")}
${tr("downloadNote", "p", 'class="release-note"')}
-
${tr("faqTitle", "h2", 'id="faq-title"')}
${(["Server", "Central", "Release"] as const).map((key) => `
${tr(`faq${key}`)}${tr(`faq${key}Answer`, "p")}
`).join("")}
-

${t("statusLoading")}

${tr("openCentral")}${icon("external", 15)}
`; +
${tr("projectTitle", "h2", 'id="project-title"')}${tr("projectText", "p")}
${icon("chat", 24)}
${tr("projectNative", "h3")}${tr("projectNativeText", "p")}
${icon("voice", 24)}
${tr("projectServer", "h3")}${tr("projectServerText", "p")}
${tr("projectCentral", "h3")}${tr("projectCentralText", "p")}
+
${tr("lightTitle", "h2", 'id="light-title"')}${tr("lightText", "p")}
${tr("lightVnoxName")}${tr("lightAbout")} 120 ${tr("lightUnit")}
${tr("lightElectronName")}${tr("lightElectronValue")}
${tr("lightElectronNote", "p", 'class="meter-note"')}
${tr("lightCaption", "p", 'class="small light-caption"')}${tr("lightScale", "p", 'class="small light-caption"')}
+
${tr("clientTitle", "h2", 'id="client-title"')}${tr("clientText", "p")}
${t(${tr("screenshotCaption", "figcaption")}
${tr("appearanceTitle", "h3")}${tr("appearanceText", "p")}
${tr("identityTitle", "h3")}${tr("identityText", "p")}
+
${tr("roadmapTitle", "h2", 'id="roadmap-title"')}${tr("roadmapText", "p")}

${tr("available")}

  • ${tr("availableOne")}
  • ${tr("availableTwo")}
  • ${tr("availableThree")}
  • ${tr("availableFour")}
  • ${tr("availableFive")}

${tr("next")}

  • ${tr("nextOne")}
  • ${tr("nextTwo")}
  • ${tr("nextThree")}
${tr("downloadNote", "p", 'class="release-note"')}
+
${tr("faqTitle", "h2", 'id="faq-title"')}
${(["Server", "Central", "Release"] as const).map((key) => `
${tr(`faq${key}`)}${tr(`faq${key}Answer`, "p")}
`).join("")}
+

${t("statusLoading")}

${tr("openCentral")}${icon("external", 15)}
`; renderDiagram(); + initMotion(); main.querySelectorAll("[data-tab]").forEach((button) => { button.addEventListener("click", () => { activeTab = button.dataset.tab as Tab; @@ -103,6 +105,41 @@ function landing() { }); }); } +/** Scroll reveal and the memory counter. Skipped when motion is reduced. */ +function initMotion() { + const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches; + if (reduced || !("IntersectionObserver" in window)) return; + const targets = main.querySelectorAll(".reveal"); + const counters = main.querySelectorAll("[data-count]"); + document.documentElement.classList.add("motion"); + counters.forEach((counter) => (counter.textContent = "0")); + const count = (counter: HTMLElement) => { + const goal = Number(counter.dataset.count); + const start = performance.now(); + const step = (now: number) => { + const progress = Math.min((now - start) / 1400, 1); + counter.textContent = String( + Math.round(goal * (1 - Math.pow(1 - progress, 3))), + ); + if (progress < 1) requestAnimationFrame(step); + }; + requestAnimationFrame(step); + }; + const observer = new IntersectionObserver( + (entries) => { + for (const entry of entries) { + if (!entry.isIntersecting) continue; + entry.target.classList.add("in"); + entry.target + .querySelectorAll("[data-count]") + .forEach(count); + observer.unobserve(entry.target); + } + }, + { threshold: 0.2 }, + ); + targets.forEach((target) => observer.observe(target)); +} function renderDiagram() { const content = document.querySelector("#diagram-content"); if (!content) return; diff --git a/src/i18n/en.ts b/src/i18n/en.ts index bbff1bb..92f92b6 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -54,6 +54,21 @@ export const en = { projectCentral: "Vnox Central", projectCentralText: "A web account with GitHub sign-in. It is not linked to the desktop client key yet.", + lightTitle: "A light client", + lightText: + "The Rust and Slint client does not carry a browser with it. It uses about 120 MB of memory when idle.", + lightAbout: "about", + lightUnit: "MB", + lightVnoxName: "VNOX", + lightElectronName: "Discord (Vesktop, Electron)", + lightElectronValue: "about 1.3 GB", + lightElectronNote: + "Discord in the Vesktop Electron client, 8 processes, in use: RSS 1333 MB, PSS 1103 MB (about 1.1 GB). Electron clients in general often use from a few hundred MB to a gigabyte and more.", + lightCaption: + "Measured on Linux. VNOX: connection screen, release build, RSS 121 MB, PSS 96 MB. Discord: in use.", + lightScale: + "These are two different states: VNOX idle, Discord under load. Bar length: 1.3 GB by RSS.", + lightSource: "On Electron in general: PCWorld, December 2025", clientCode: "Client source", serverCode: "Server source", clientTitle: "Appearance settings", diff --git a/src/i18n/ru.ts b/src/i18n/ru.ts index fcf6695..14b4ba8 100644 --- a/src/i18n/ru.ts +++ b/src/i18n/ru.ts @@ -56,6 +56,21 @@ export const ru: Catalog = { projectCentral: "Vnox Central", projectCentralText: "Веб-аккаунт с входом через GitHub. С ключом настольного клиента он пока не связан.", + lightTitle: "Лёгкий клиент", + lightText: + "Клиент на Rust и Slint не носит с собой браузер. В простое он занимает около 120 МБ памяти.", + lightAbout: "около", + lightUnit: "МБ", + lightVnoxName: "VNOX", + lightElectronName: "Discord (Vesktop, Electron)", + lightElectronValue: "около 1,3 ГБ", + lightElectronNote: + "Discord в клиенте Vesktop на Electron, 8 процессов, в работе: RSS 1333 МБ, PSS 1103 МБ (около 1,1 ГБ). Клиенты на Electron вообще часто занимают от нескольких сотен МБ до гигабайта и больше.", + lightCaption: + "Замер на Linux. VNOX: экран подключения, release-сборка, RSS 121 МБ, PSS 96 МБ. Discord: в работе.", + lightScale: + "Это два разных состояния: VNOX в простое, Discord под нагрузкой. Длина полосы: 1,3 ГБ по RSS.", + lightSource: "Про Electron в целом: PCWorld, декабрь 2025", clientCode: "Код клиента", serverCode: "Код сервера", clientTitle: "Настройки внешнего вида", diff --git a/src/styles.css b/src/styles.css index d80e648..2f1dc29 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1879,3 +1879,210 @@ p { .waveform i:nth-child(11n + 11) { height: 24px; } + +/* Lightweight client block */ +.light-section { + padding-block: 85px 100px; + border-top: 1px solid var(--line); + display: grid; + grid-template-columns: 1fr 1.2fr; + gap: 110px; + align-items: start; +} +.light-intro > p { + margin-top: 25px; + max-width: 40ch; +} +.light-meters { + display: flex; + flex-direction: column; + gap: 30px; +} +.meter-head { + display: flex; + justify-content: space-between; + align-items: baseline; + gap: 16px; + margin-bottom: 10px; + font-size: 0.9rem; +} +.meter-head strong { + font-size: 1.15rem; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} +.meter.vnox .meter-head strong { + color: var(--sand); +} +.meter-track { + height: 14px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: 4px; + overflow: hidden; +} +.meter-track i { + display: block; + height: 100%; + width: var(--w); + transform-origin: left; + border-radius: 3px; +} +.meter.vnox .meter-track i { + background: var(--sand); +} +.meter.electron .meter-track i { + background: #5a5752; +} +.meter-note { + font-size: 0.82rem; + margin-top: 12px; + max-width: 52ch; +} +.light-caption { + color: var(--muted); + margin: -10px 0 0; +} +@media (max-width: 1100px) { + .light-section { + gap: 60px; + } +} +@media (max-width: 800px) { + .light-section { + grid-template-columns: 1fr; + gap: 40px; + padding-block: 60px 70px; + } +} +@media (max-width: 480px) { + .meter-head { + flex-wrap: wrap; + gap: 2px 16px; + } +} + +/* Motion: everything below is off when the visitor prefers reduced motion. */ +@media (prefers-reduced-motion: no-preference) { + .motion .reveal { + opacity: 0; + transform: translateY(22px); + transition: + opacity 0.7s ease, + transform 0.7s cubic-bezier(0.2, 0.7, 0.2, 1); + } + .motion .reveal.in { + opacity: 1; + transform: none; + } + .motion .meter-track i { + transform: scaleX(0); + } + .motion .light-section.in .meter-track i { + transform: scaleX(1); + transition: transform 1.4s cubic-bezier(0.2, 0.7, 0.2, 1) 0.2s; + } + .motion .light-section.in .meter.electron .meter-track i { + transition-duration: 2.2s; + } + .enter .hero-copy > * { + animation: rise 0.7s cubic-bezier(0.2, 0.7, 0.2, 1) backwards; + } + .enter .hero-copy > :nth-child(2) { + animation-delay: 0.08s; + } + .enter .hero-copy > :nth-child(3) { + animation-delay: 0.16s; + } + .enter .hero-copy > :nth-child(4) { + animation-delay: 0.24s; + } + .enter .hero-copy > :nth-child(5) { + animation-delay: 0.32s; + } + .enter .diagram-wrap { + animation: rise 0.9s cubic-bezier(0.2, 0.7, 0.2, 1) 0.2s backwards; + } + #diagram-content > * { + animation: fade 0.35s ease; + } + .diagram-call .connection-dot, + .person-dot { + animation: pulse 2.4s ease-in-out infinite; + } + .person-dot.second { + animation-delay: 0.8s; + } + .waveform i { + animation: wave 1.2s ease-in-out infinite; + transform-origin: center; + } + .waveform i:nth-child(odd) { + animation-duration: 0.9s; + } + .waveform i:nth-child(3n) { + animation-delay: -0.4s; + } + .waveform i:nth-child(4n) { + animation-delay: -0.7s; + } + .button, + .point-icon, + .theme-option, + .client-image, + .faq summary span { + transition: + transform 0.2s ease, + background-color 0.2s ease, + border-color 0.2s ease; + } + .button:hover { + transform: translateY(-2px); + } + .button:active { + transform: none; + } + .project-points article:hover .point-icon { + transform: translateY(-3px); + background: #2e2d2b; + } + .theme-option:hover { + transform: translateY(-2px); + } + .client-image:hover { + border-color: #6b6559; + } + .roadmap-columns article { + transition: border-color 0.25s ease; + } + .roadmap-columns article:hover { + border-top-color: var(--sand); + } +} +@keyframes rise { + from { + opacity: 0; + transform: translateY(18px); + } +} +@keyframes fade { + from { + opacity: 0; + } +} +@keyframes pulse { + 50% { + opacity: 0.35; + } +} +@keyframes wave { + 50% { + transform: scaleY(0.45); + } +} +@media (prefers-reduced-motion: reduce) { + * { + animation: none !important; + transition: none !important; + } +} diff --git a/tests/browser_qa.py b/tests/browser_qa.py index 707e629..50616f1 100644 --- a/tests/browser_qa.py +++ b/tests/browser_qa.py @@ -37,6 +37,8 @@ with sync_playwright() as p: page.locator('#service-status').filter(has_text='отвечает').wait_for() page.screenshot(path=str(artifacts / 'desktop-hero.png')) page.screenshot(path=str(artifacts / 'desktop-full.png'), full_page=True) + page.locator('#light').scroll_into_view_if_needed() + page.wait_for_function("document.querySelector('.count').textContent === '120'") page.locator('[data-tab="voice"]').click() assert page.locator('.voice-orbit').count() == 1 page.locator('[data-tab="voice"]').press('ArrowRight') @@ -57,7 +59,16 @@ with sync_playwright() as p: page.set_viewport_size({'width': width, 'height': 844}) assert not page.evaluate('document.documentElement.scrollWidth > innerWidth'), (locale, width) page.set_viewport_size({'width': 390, 'height': 844}) + page.evaluate("document.querySelectorAll('.reveal').forEach(e => e.classList.add('in'))") page.screenshot(path=str(artifacts / 'mobile-full.png'), full_page=True) + reduced = browser.new_context(viewport={'width': 390, 'height': 844}, reduced_motion='reduce') + rp = reduced.new_page() + rp.goto(args.url) + rp.locator('.light-section').wait_for() + assert not rp.evaluate("document.documentElement.classList.contains('motion')") + assert rp.locator('.count').inner_text() == '120' + assert rp.evaluate("getComputedStyle(document.querySelector('.reveal')).opacity") == '1' + reduced.close() page.goto(args.url + '/account') page.locator('.github-login[href="/v1/auth/github/start"]').wait_for() assert page.locator('.github-login').get_attribute('aria-disabled') is None