refactor(web): migrate to Bun and TypeScript with README screenshots

This commit is contained in:
Loki 2026-10-24 15:34:41 +02:00
parent 87372041dd
commit d6a9745df0
Signed by: boba
GPG key ID: 253067914055423B
28 changed files with 3152 additions and 386 deletions

View file

@ -1,27 +0,0 @@
export class ApiError extends Error {
constructor(status, code) { super(code); this.name = 'ApiError'; this.status = status; }
}
export async function request(path, { signal, method = 'GET', csrf, fetcher = fetch } = {}) {
if (!path.startsWith('/v1/')) throw new TypeError('Only same-origin VNOX API paths are allowed');
const response = await fetcher(path, {
method, signal, credentials: 'same-origin', cache: 'no-store',
headers: { Accept: 'application/json', ...(csrf ? { 'X-CSRF-Token': csrf } : {}) },
});
if (!response.ok) throw new ApiError(response.status, 'request_failed');
if (response.status === 204) return null;
return response.json();
}
export function isSession(value) {
return value?.authenticated === false || (value?.authenticated === true
&& typeof value.csrf_token === 'string' && value.csrf_token.length > 0
&& typeof value.user?.user_id === 'string' && typeof value.user?.handle === 'string'
&& typeof value.user?.display_name === 'string');
}
export function safeAvatar(value) {
if (typeof value !== 'string') return null;
try {
const url = new URL(value);
return url.protocol === 'https:' && url.hostname === 'avatars.githubusercontent.com'
&& !url.username && !url.password && !url.port ? url.href : null;
} catch { return null; }
}

90
src/api.ts Normal file
View file

@ -0,0 +1,90 @@
export interface User {
user_id: string;
handle: string;
display_name: string;
avatar_url?: string | null;
}
export type Session =
| { authenticated: false }
| { authenticated: true; user: User; csrf_token: string };
export interface HubInfo {
capabilities: { github_auth: string };
}
export interface RequestOptions {
signal?: AbortSignal;
method?: "GET" | "POST";
csrf?: string;
fetcher?: (input: string, options: RequestInit) => Promise<Response>;
}
export class ApiError extends Error {
readonly status: number;
constructor(status: number, code: string) {
super(code);
this.name = "ApiError";
this.status = status;
}
}
export async function request(
path: string,
{ signal, method = "GET", csrf, fetcher = fetch }: RequestOptions = {},
): Promise<unknown> {
if (!path.startsWith("/v1/"))
throw new TypeError("Only same-origin VNOX API paths are allowed");
const response = await fetcher(path, {
method,
signal,
credentials: "same-origin",
cache: "no-store",
headers: {
Accept: "application/json",
...(csrf ? { "X-CSRF-Token": csrf } : {}),
},
});
if (!response.ok) throw new ApiError(response.status, "request_failed");
if (response.status === 204) return null;
return response.json();
}
function record(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
export function isSession(value: unknown): value is Session {
if (!record(value)) return false;
if (value.authenticated === false) return true;
if (
value.authenticated !== true ||
typeof value.csrf_token !== "string" ||
value.csrf_token.length === 0 ||
!record(value.user)
)
return false;
return (
typeof value.user.user_id === "string" &&
typeof value.user.handle === "string" &&
typeof value.user.display_name === "string" &&
(value.user.avatar_url === undefined ||
value.user.avatar_url === null ||
typeof value.user.avatar_url === "string")
);
}
export function isInfo(value: unknown): value is HubInfo {
return (
record(value) &&
record(value.capabilities) &&
typeof value.capabilities.github_auth === "string"
);
}
export function safeAvatar(value: unknown): string | null {
if (typeof value !== "string") return null;
try {
const url = new URL(value);
return url.protocol === "https:" &&
url.hostname === "avatars.githubusercontent.com" &&
!url.username &&
!url.password &&
!url.port
? url.href
: null;
} catch {
return null;
}
}

View file

@ -1,165 +0,0 @@
import { detectLanguage, translate } from './i18n.js';
import { request, isSession, safeAvatar } from './api.js';
let savedLanguage;
try { savedLanguage = localStorage.getItem('vnox-web-language'); } catch { /* Storage is optional. */ }
let language = detectLanguage(savedLanguage, navigator.languages ?? [navigator.language]);
const accountPage = /^\/account\/?$/.test(location.pathname);
const main = document.querySelector('main');
let activeTab = 'text';
let activeTheme = 'dark';
let controller;
let currentSession;
let githubEnabled = false;
let sessionState = 'loading';
let infoState = 'loading';
let logoutState = 'idle';
const t = key => translate(language, key);
const icon = (name, size = 20) => {
const paths = {
github: '<path d="M9 19c-4 1-4-2-6-2m12 4v-3.4a3 3 0 0 0-.8-2.3c2.7-.3 5.5-1.3 5.5-6A4.7 4.7 0 0 0 18.4 6a4.4 4.4 0 0 0-.1-3.3s-1-.3-3.4 1.3a11.6 11.6 0 0 0-6.2 0C6.3 2.4 5.3 2.7 5.3 2.7A4.4 4.4 0 0 0 5.2 6 4.7 4.7 0 0 0 4 9.3c0 4.7 2.8 5.7 5.5 6a3 3 0 0 0-.8 2.3V21"/>',
voice: '<path d="m11 5-5 4H3v6h3l5 4V5Z"/><path d="M15 8a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14"/>',
mic: '<rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"/>',
chat: '<path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8v.5Z"/>',
external: '<path d="M15 3h6v6m0-6L10 14"/><path d="M10 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5"/>',
check: '<path d="m5 12 4 4L19 6"/>',
copy: '<rect x="8" y="8" width="13" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>',
back: '<path d="m12 19-7-7 7-7m-7 7h14"/>',
};
return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] ?? paths.chat}</svg>`;
};
const tr = (key, tag = 'span', attrs = '') => `<${tag} data-i18n="${key}" ${attrs}>${t(key)}</${tag}>`;
const external = (href, key) => `<a class="text-link" href="${href}" target="_blank" rel="noopener noreferrer">${tr(key)}${icon('external', 15)}</a>`;
function landing() {
main.innerHTML = `
<section class="hero shell" aria-labelledby="hero-title">
<div class="hero-copy"><p class="development">${tr('development')}</p>${tr('heroTitle', 'h1', 'id="hero-title"')}${tr('heroText', 'p', 'class="hero-description"')}
<div class="hero-actions"><a class="button primary" href="/account">${tr('openCentral')}</a><a class="button quiet" href="#project">${tr('explore')}</a></div>${tr('earlyNote','p','class="small hero-note"')}</div>
<div class="diagram-wrap"><div class="diagram-meta">${tr('diagramLabel')}<span class="diagram-dots" aria-hidden="true"><i></i><i></i><i></i></span></div>
<div class="product-diagram" data-preview-theme="dark"><div class="diagram-sidebar"><img src="/assets/vnox-mark.svg" alt="" width="32" height="32"><div class="diagram-community">${tr('community')}</div><div class="diagram-channel selected"># ${tr('general')}</div><div class="diagram-channel"># ${tr('ideas')}</div><div class="diagram-voice">${icon('voice',16)}${tr('voiceRoom')}</div><div class="diagram-people"><span class="person-dot"></span>${tr('you')}<span class="person-dot second"></span>${tr('friend')}</div><div class="diagram-self"><span class="mini-avatar">V</span>${tr('you')}${icon('mic',15)}</div></div>
<div class="diagram-main"><div class="diagram-header"># ${tr('general')}<span>${icon('chat',17)}</span></div><div id="diagram-content"></div><div class="diagram-call"><span class="connection-dot"></span>${tr('voiceConnected')}${icon('mic',16)}</div></div></div>
<div class="diagram-tabs" role="tablist" aria-label="${t('preview')}" data-i18n-aria="preview"><button role="tab" aria-selected="true" aria-controls="diagram-content" id="tab-text" data-tab="text">${tr('textTab')}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-voice" data-tab="voice" tabindex="-1">${tr('voiceTab')}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-theme" data-tab="theme" tabindex="-1">${tr('themeTab')}</button></div>${tr('diagramNote','p','class="small diagram-note"')}
</div>
</section>
<section class="project-section shell" id="project" aria-labelledby="project-title"><div class="section-intro">${tr('projectTitle','h2','id="project-title"')}${tr('projectText','p')}<div class="source-links">${external('https://git.wihuk.pro/boba/VNOX-Client','clientCode')}${external('https://git.wihuk.pro/boba/VNOX-Server','serverCode')}</div></div><div class="project-points"><article><div class="point-icon">${icon('chat',24)}</div><div>${tr('projectNative','h3')}${tr('projectNativeText','p')}</div></article><article><div class="point-icon">${icon('voice',24)}</div><div>${tr('projectServer','h3')}${tr('projectServerText','p')}</div></article><article><img src="/assets/vnox-mark.svg" alt="" width="40" height="40"><div>${tr('projectCentral','h3')}${tr('projectCentralText','p')}</div></article></div></section>
<section class="client-section" id="client" aria-labelledby="client-title"><div class="shell"><div class="client-heading">${tr('clientTitle','h2','id="client-title"')}${tr('clientText','p')}</div><figure class="client-image"><img src="/assets/client-settings.png" width="1280" height="800" alt="${t('clientScreenshot')}" data-i18n-alt="clientScreenshot" loading="lazy">${tr('screenshotCaption','figcaption')}</figure><div class="client-details"><article>${tr('appearanceTitle','h3')}${tr('appearanceText','p')}</article><article>${tr('identityTitle','h3')}${tr('identityText','p')}</article></div></div></section>
<section class="roadmap shell" id="roadmap" aria-labelledby="roadmap-title"><div class="roadmap-heading">${tr('roadmapTitle','h2','id="roadmap-title"')}${tr('roadmapText','p')}</div><div class="roadmap-columns"><article><h3><span class="connection-dot" aria-hidden="true"></span>${tr('available')}</h3><ul><li>${tr('availableOne')}</li><li>${tr('availableTwo')}</li><li>${tr('availableThree')}</li><li>${tr('availableFour')}</li><li>${tr('availableFive')}</li></ul></article><article><h3><span class="planned-dot" aria-hidden="true"></span>${tr('next')}</h3><ul><li>${tr('nextOne')}</li><li>${tr('nextTwo')}</li><li>${tr('nextThree')}</li></ul></article></div>${tr('downloadNote','p','class="release-note"')}</section>
<section class="faq shell" aria-labelledby="faq-title">${tr('faqTitle','h2','id="faq-title"')}<div>${['Server','Central','Release'].map(key=>`<details><summary>${tr(`faq${key}`)}<span aria-hidden="true">+</span></summary>${tr(`faq${key}Answer`,'p')}</details>`).join('')}</div></section>
<section class="status-section shell" aria-label="${t('statusNote')}" data-i18n-aria="statusNote"><div><span id="service-dot" class="status-dot"></span><p id="service-status" role="status">${t('statusLoading')}</p></div><a href="/account" class="text-link">${tr('openCentral')}${icon('external',15)}</a></section>`;
renderDiagram();
main.querySelectorAll('[data-tab]').forEach(button => {
button.addEventListener('click', () => { activeTab = button.dataset.tab; renderDiagram(); });
button.addEventListener('keydown', event => {
const tabs = [...main.querySelectorAll('[data-tab]')];
let index = tabs.indexOf(button);
if (event.key === 'ArrowRight') index = (index + 1) % tabs.length;
else if (event.key === 'ArrowLeft') index = (index + tabs.length - 1) % tabs.length;
else if (event.key === 'Home') index = 0;
else if (event.key === 'End') index = tabs.length - 1;
else return;
event.preventDefault(); activeTab = tabs[index].dataset.tab; renderDiagram(); tabs[index].focus();
});
});
}
function renderDiagram() {
const content = document.querySelector('#diagram-content');
if (!content) return;
main.querySelectorAll('[data-tab]').forEach(button => {
const active = button.dataset.tab === activeTab;
button.setAttribute('aria-selected', String(active));button.tabIndex = active ? 0 : -1;
});
content.setAttribute('role','tabpanel');content.setAttribute('aria-labelledby', `tab-${activeTab}`);
if (activeTab === 'text') content.innerHTML = `<div class="illustration-chat"><div class="message-heading"><span class="chat-avatar">V</span><div>${tr('community','strong')}<div class="message-lines" aria-hidden="true"><i></i><i></i></div></div></div>${tr('messageSample','p')}<div class="illustration-composer" aria-hidden="true"><span>+</span><i></i>${icon('chat',15)}</div>${tr('messageNote','p','class="diagram-caption"')}</div>`;
if (activeTab === 'voice') content.innerHTML = `<div class="illustration-voice"><div class="voice-orbit"><span class="voice-avatar">V</span><div class="waveform" aria-hidden="true">${Array.from({length:11},()=>'<i></i>').join('')}</div><span class="voice-avatar friend-avatar">${icon('voice',30)}</span></div>${tr('voiceExplain','p')}<div class="voice-controls" aria-hidden="true"><span>${icon('mic')}</span><span>${icon('voice')}</span></div>${tr('voiceCaption','p','class="diagram-caption"')}</div>`;
if (activeTab === 'theme') {
content.innerHTML = `<div class="illustration-themes">${tr('themeCaption','h3')}<div class="theme-options" role="group" aria-label="${t('previewTheme')}" data-i18n-aria="previewTheme">${['light','dark','black','custom'].map(theme=>`<button class="theme-option ${theme}" data-theme="${theme}" aria-pressed="${activeTheme===theme}"><span class="theme-sample" aria-hidden="true"><i></i><i></i><i></i></span>${tr(theme)}</button>`).join('')}</div></div>`;
content.querySelectorAll('[data-theme]').forEach(button => button.addEventListener('click',()=>{
activeTheme = button.dataset.theme;
document.querySelector('.product-diagram').dataset.previewTheme = activeTheme;
content.querySelectorAll('[data-theme]').forEach(item=>item.setAttribute('aria-pressed',String(item===button)));
}));
}
}
function account() {
main.innerHTML = `<section class="account-section shell"><a href="/" class="text-link back-link">${icon('back',17)}${tr('back')}</a><div class="account-layout"><div class="account-intro"><img class="account-mark" src="/assets/vnox-mark.svg" alt="" width="76" height="76">${tr('accountHeading','h1')}${tr('accountIntro','p')}<div class="account-explanation">${tr('accountStage','p')}</div></div><div id="account-content" class="account-panel" aria-live="polite"></div></div></section>`;
renderAccount();
}
function renderAccount() {
const panel = document.querySelector('#account-content');
if (!panel) return;
panel.replaceChildren();
if (sessionState === 'loading') { panel.innerHTML = `<div class="account-loading"><span class="loading-ring" aria-hidden="true"></span>${tr('sessionLoading','p')}</div>`;return; }
if (sessionState === 'error') {
panel.innerHTML = `${tr('accountError','h2')}${tr('accountErrorText','p')}<button class="button primary" id="retry-session">${tr('retry')}</button>`;
panel.querySelector('#retry-session').addEventListener('click',refresh);return;
}
if (currentSession?.authenticated) {
panel.innerHTML = `<div class="profile-heading"><div class="profile-avatar" id="profile-avatar" aria-hidden="true">V</div><div>${tr('profileTitle','h2')}<p id="profile-name"></p></div></div>${tr('profileIntro','p')}<dl class="profile-fields"><div><dt>${tr('handle')}</dt><dd id="profile-handle"></dd></div><div><dt>${tr('userId')}</dt><dd id="profile-id"></dd></div><div><dt>${tr('provider')}</dt><dd>GitHub</dd></div></dl><div class="profile-actions"><button class="button secondary" id="copy-id">${icon('copy',17)}${tr('copy')}</button><button class="button quiet" id="logout" ${logoutState==='pending'?'disabled':''}>${tr(logoutState==='pending'?'loggingOut':'logout')}</button></div><p class="form-message" id="profile-message" role="status"></p>`;
const user = currentSession.user;
panel.querySelector('#profile-name').textContent = user.display_name || t('profileFallback');
panel.querySelector('#profile-handle').textContent = user.handle;
panel.querySelector('#profile-id').textContent = user.user_id;
const avatar = safeAvatar(user.avatar_url);
if (avatar) { const image = document.createElement('img');image.src=avatar;image.alt='';image.referrerPolicy='no-referrer';image.addEventListener('error',()=>image.remove(),{once:true});panel.querySelector('#profile-avatar').append(image); }
panel.querySelector('#copy-id').addEventListener('click',async()=>{
try { await navigator.clipboard.writeText(user.user_id); panel.querySelector('#profile-message').textContent=t('copied'); }
catch { panel.querySelector('#profile-message').textContent=t('copyError'); }
});
panel.querySelector('#logout').addEventListener('click',logout);
if (logoutState==='error') panel.querySelector('#profile-message').textContent=t('logoutError');
return;
}
panel.innerHTML = `<div class="login-provider">${icon('github',33)}</div>${tr('loginTitle','h2')}${tr('loginText','p')}<a class="button primary github-login ${githubEnabled?'':'unavailable'}" ${githubEnabled?'href="/v1/auth/github/start"':'aria-disabled="true" tabindex="-1"'}>${icon('github',21)}${tr('loginButton')}</a><p id="login-availability" class="form-message" role="status"></p><button class="text-button" id="retry-info" ${infoState==='error'?'':'hidden'}>${tr('retry')}</button><div class="privacy-note">${icon('check',16)}${tr('privacy','p')}</div>`;
panel.querySelector('#login-availability').textContent = infoState==='loading'?t('loginLoading'):infoState==='error'?t('loginUnavailable'):githubEnabled?'':t('loginDisabled');
panel.querySelector('#retry-info').addEventListener('click',refresh);
}
async function logout() {
if (!currentSession?.authenticated || logoutState==='pending') return;
const csrf = currentSession.csrf_token;
logoutState='pending';renderAccount();
try {
await request('/v1/auth/logout',{method:'POST',csrf,signal:AbortSignal.timeout(15000)});
currentSession={authenticated:false};logoutState='idle';renderAccount();
} catch(error) {
if (error.status===401) { currentSession={authenticated:false};logoutState='idle';renderAccount(); }
else { logoutState='error';renderAccount(); }
}
}
function updateStatus() {
const status = document.querySelector('#service-status');
if (status) { status.textContent = t(infoState==='loading'?'statusLoading':infoState==='ready'?'statusReady':'statusUnavailable');document.querySelector('#service-dot').dataset.state=infoState; }
}
async function refresh() {
controller?.abort();controller=new AbortController();
const currentController = controller;
const signal = AbortSignal.any([currentController.signal,AbortSignal.timeout(15000)]);
infoState='loading';
if (accountPage) { sessionState='loading';renderAccount(); } else updateStatus();
const info = request('/v1/info',{signal}).then(value=>{
if (controller !== currentController) return;
if (typeof value?.capabilities?.github_auth !== 'string') throw new Error('invalid_info');
githubEnabled=value.capabilities.github_auth==='enabled';infoState='ready';
}).catch(()=>{if(!currentController.signal.aborted){githubEnabled=false;infoState='error';}}).finally(()=>{if(controller===currentController){updateStatus();if(accountPage)renderAccount();}});
if (accountPage) {
await Promise.allSettled([info,request('/v1/auth/session',{signal}).then(value=>{
if (controller !== currentController) return;
if (!isSession(value)) throw new Error('invalid_session');
currentSession=value;sessionState='ready';
}).catch(()=>{if(!currentController.signal.aborted)sessionState='error';}).finally(()=>{if(controller===currentController)renderAccount();})]);
} else await info;
}
function setLanguage(next) {
language=next;
try { localStorage.setItem('vnox-web-language',next); } catch { /* No authentication data is persisted. */ }
document.documentElement.lang=next;
document.title=t(accountPage?'accountTitle':'title');
document.querySelector('meta[name="description"]').content=t('description');
document.querySelectorAll('[data-i18n]').forEach(element=>element.textContent=t(element.dataset.i18n));
for(const [attribute,dataKey] of [['aria-label','i18nAria'],['alt','i18nAlt']]) document.querySelectorAll(`[data-${attribute==='alt'?'i18n-alt':'i18n-aria'}]`).forEach(element=>element.setAttribute(attribute,t(element.dataset[dataKey])));
document.querySelectorAll('[data-language]').forEach(button=>button.setAttribute('aria-pressed',String(button.dataset.language===next)));
if (accountPage) renderAccount();else {renderDiagram();updateStatus();}
}
if(accountPage) account();else landing();
document.querySelectorAll('[data-language]').forEach(button=>button.addEventListener('click',()=>setLanguage(button.dataset.language)));
setLanguage(language);refresh();
window.addEventListener('pageshow',event=>{if(event.persisted)refresh();});

338
src/app.ts Normal file
View file

@ -0,0 +1,338 @@
import type { Language, MessageKey } from "./i18n";
import type { Session } from "./api";
import { detectLanguage, translate } from "./i18n";
import { request, isSession, isInfo, safeAvatar, ApiError } from "./api";
let savedLanguage: string | null | undefined;
try {
savedLanguage = localStorage.getItem("vnox-web-language");
} catch {
/* Storage is optional. */
}
let language = detectLanguage(
savedLanguage,
navigator.languages ?? [navigator.language],
);
const accountPage = /^\/account\/?$/.test(location.pathname);
function find<T extends Element = HTMLElement>(
selector: string,
root: ParentNode = document,
): T {
const element = root.querySelector<T>(selector);
if (!element) throw new Error(`Missing required element: ${selector}`);
return element;
}
const main = find("main");
type Tab = "text" | "voice" | "theme";
type Theme = "light" | "dark" | "black" | "custom";
let activeTab: Tab = "text";
let activeTheme: Theme = "dark";
let controller: AbortController | undefined;
let currentSession: Session | null = null;
let githubEnabled = false;
let sessionState: "loading" | "ready" | "error" = "loading";
let infoState: "loading" | "ready" | "error" = "loading";
let logoutState: "idle" | "pending" | "error" = "idle";
const t = (key: MessageKey) => translate(language, key);
const icon = (
name:
| "github"
| "voice"
| "mic"
| "chat"
| "external"
| "check"
| "copy"
| "back",
size = 20,
) => {
const paths = {
github:
'<path d="M9 19c-4 1-4-2-6-2m12 4v-3.4a3 3 0 0 0-.8-2.3c2.7-.3 5.5-1.3 5.5-6A4.7 4.7 0 0 0 18.4 6a4.4 4.4 0 0 0-.1-3.3s-1-.3-3.4 1.3a11.6 11.6 0 0 0-6.2 0C6.3 2.4 5.3 2.7 5.3 2.7A4.4 4.4 0 0 0 5.2 6 4.7 4.7 0 0 0 4 9.3c0 4.7 2.8 5.7 5.5 6a3 3 0 0 0-.8 2.3V21"/>',
voice:
'<path d="m11 5-5 4H3v6h3l5 4V5Z"/><path d="M15 8a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14"/>',
mic: '<rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"/>',
chat: '<path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8v.5Z"/>',
external:
'<path d="M15 3h6v6m0-6L10 14"/><path d="M10 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5"/>',
check: '<path d="m5 12 4 4L19 6"/>',
copy: '<rect x="8" y="8" width="13" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>',
back: '<path d="m12 19-7-7 7-7m-7 7h14"/>',
};
return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] ?? paths.chat}</svg>`;
};
const tr = (key: MessageKey, tag = "span", attrs = "") =>
`<${tag} data-i18n="${key}" ${attrs}>${t(key)}</${tag}>`;
const external = (href: string, key: MessageKey) =>
`<a class="text-link" href="${href}" target="_blank" rel="noopener noreferrer">${tr(key)}${icon("external", 15)}</a>`;
function landing() {
main.innerHTML = `
<section class="hero shell" aria-labelledby="hero-title">
<div class="hero-copy"><p class="development">${tr("development")}</p>${tr("heroTitle", "h1", 'id="hero-title"')}${tr("heroText", "p", 'class="hero-description"')}
<div class="hero-actions"><a class="button primary" href="/account">${tr("openCentral")}</a><a class="button quiet" href="#project">${tr("explore")}</a></div>${tr("earlyNote", "p", 'class="small hero-note"')}</div>
<div class="diagram-wrap"><div class="diagram-meta">${tr("diagramLabel")}<span class="diagram-dots" aria-hidden="true"><i></i><i></i><i></i></span></div>
<div class="product-diagram" data-preview-theme="dark"><div class="diagram-sidebar"><img src="/assets/vnox-mark.svg" alt="" width="32" height="32"><div class="diagram-community">${tr("community")}</div><div class="diagram-channel selected"># ${tr("general")}</div><div class="diagram-channel"># ${tr("ideas")}</div><div class="diagram-voice">${icon("voice", 16)}${tr("voiceRoom")}</div><div class="diagram-people"><span class="person-dot"></span>${tr("you")}<span class="person-dot second"></span>${tr("friend")}</div><div class="diagram-self"><span class="mini-avatar">V</span>${tr("you")}${icon("mic", 15)}</div></div>
<div class="diagram-main"><div class="diagram-header"># ${tr("general")}<span>${icon("chat", 17)}</span></div><div id="diagram-content"></div><div class="diagram-call"><span class="connection-dot"></span>${tr("voiceConnected")}${icon("mic", 16)}</div></div></div>
<div class="diagram-tabs" role="tablist" aria-label="${t("preview")}" data-i18n-aria="preview"><button role="tab" aria-selected="true" aria-controls="diagram-content" id="tab-text" data-tab="text">${tr("textTab")}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-voice" data-tab="voice" tabindex="-1">${tr("voiceTab")}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-theme" data-tab="theme" tabindex="-1">${tr("themeTab")}</button></div>${tr("diagramNote", "p", 'class="small diagram-note"')}
</div>
</section>
<section class="project-section shell" id="project" aria-labelledby="project-title"><div class="section-intro">${tr("projectTitle", "h2", 'id="project-title"')}${tr("projectText", "p")}<div class="source-links">${external("https://git.wihuk.pro/boba/VNOX-Client", "clientCode")}${external("https://git.wihuk.pro/boba/VNOX-Server", "serverCode")}</div></div><div class="project-points"><article><div class="point-icon">${icon("chat", 24)}</div><div>${tr("projectNative", "h3")}${tr("projectNativeText", "p")}</div></article><article><div class="point-icon">${icon("voice", 24)}</div><div>${tr("projectServer", "h3")}${tr("projectServerText", "p")}</div></article><article><img src="/assets/vnox-mark.svg" alt="" width="40" height="40"><div>${tr("projectCentral", "h3")}${tr("projectCentralText", "p")}</div></article></div></section>
<section class="client-section" id="client" aria-labelledby="client-title"><div class="shell"><div class="client-heading">${tr("clientTitle", "h2", 'id="client-title"')}${tr("clientText", "p")}</div><figure class="client-image"><img src="/assets/client-settings.png" width="1280" height="800" alt="${t("clientScreenshot")}" data-i18n-alt="clientScreenshot" loading="lazy">${tr("screenshotCaption", "figcaption")}</figure><div class="client-details"><article>${tr("appearanceTitle", "h3")}${tr("appearanceText", "p")}</article><article>${tr("identityTitle", "h3")}${tr("identityText", "p")}</article></div></div></section>
<section class="roadmap shell" id="roadmap" aria-labelledby="roadmap-title"><div class="roadmap-heading">${tr("roadmapTitle", "h2", 'id="roadmap-title"')}${tr("roadmapText", "p")}</div><div class="roadmap-columns"><article><h3><span class="connection-dot" aria-hidden="true"></span>${tr("available")}</h3><ul><li>${tr("availableOne")}</li><li>${tr("availableTwo")}</li><li>${tr("availableThree")}</li><li>${tr("availableFour")}</li><li>${tr("availableFive")}</li></ul></article><article><h3><span class="planned-dot" aria-hidden="true"></span>${tr("next")}</h3><ul><li>${tr("nextOne")}</li><li>${tr("nextTwo")}</li><li>${tr("nextThree")}</li></ul></article></div>${tr("downloadNote", "p", 'class="release-note"')}</section>
<section class="faq shell" aria-labelledby="faq-title">${tr("faqTitle", "h2", 'id="faq-title"')}<div>${(["Server", "Central", "Release"] as const).map((key) => `<details><summary>${tr(`faq${key}`)}<span aria-hidden="true">+</span></summary>${tr(`faq${key}Answer`, "p")}</details>`).join("")}</div></section>
<section class="status-section shell" aria-label="${t("statusNote")}" data-i18n-aria="statusNote"><div><span id="service-dot" class="status-dot"></span><p id="service-status" role="status">${t("statusLoading")}</p></div><a href="/account" class="text-link">${tr("openCentral")}${icon("external", 15)}</a></section>`;
renderDiagram();
main.querySelectorAll<HTMLElement>("[data-tab]").forEach((button) => {
button.addEventListener("click", () => {
activeTab = button.dataset.tab as Tab;
renderDiagram();
});
button.addEventListener("keydown", (event) => {
const tabs = [...main.querySelectorAll<HTMLElement>("[data-tab]")];
let index = tabs.indexOf(button);
if (event.key === "ArrowRight") index = (index + 1) % tabs.length;
else if (event.key === "ArrowLeft")
index = (index + tabs.length - 1) % tabs.length;
else if (event.key === "Home") index = 0;
else if (event.key === "End") index = tabs.length - 1;
else return;
event.preventDefault();
activeTab = tabs[index]!.dataset.tab as Tab;
renderDiagram();
tabs[index]!.focus();
});
});
}
function renderDiagram() {
const content = document.querySelector("#diagram-content");
if (!content) return;
main.querySelectorAll<HTMLElement>("[data-tab]").forEach((button) => {
const active = button.dataset.tab === activeTab;
button.setAttribute("aria-selected", String(active));
button.tabIndex = active ? 0 : -1;
});
content.setAttribute("role", "tabpanel");
content.setAttribute("aria-labelledby", `tab-${activeTab}`);
if (activeTab === "text")
content.innerHTML = `<div class="illustration-chat"><div class="message-heading"><span class="chat-avatar">V</span><div>${tr("community", "strong")}<div class="message-lines" aria-hidden="true"><i></i><i></i></div></div></div>${tr("messageSample", "p")}<div class="illustration-composer" aria-hidden="true"><span>+</span><i></i>${icon("chat", 15)}</div>${tr("messageNote", "p", 'class="diagram-caption"')}</div>`;
if (activeTab === "voice")
content.innerHTML = `<div class="illustration-voice"><div class="voice-orbit"><span class="voice-avatar">V</span><div class="waveform" aria-hidden="true">${Array.from({ length: 11 }, () => "<i></i>").join("")}</div><span class="voice-avatar friend-avatar">${icon("voice", 30)}</span></div>${tr("voiceExplain", "p")}<div class="voice-controls" aria-hidden="true"><span>${icon("mic")}</span><span>${icon("voice")}</span></div>${tr("voiceCaption", "p", 'class="diagram-caption"')}</div>`;
if (activeTab === "theme") {
content.innerHTML = `<div class="illustration-themes">${tr("themeCaption", "h3")}<div class="theme-options" role="group" aria-label="${t("previewTheme")}" data-i18n-aria="previewTheme">${(["light", "dark", "black", "custom"] as const).map((theme) => `<button class="theme-option ${theme}" data-theme="${theme}" aria-pressed="${activeTheme === theme}"><span class="theme-sample" aria-hidden="true"><i></i><i></i><i></i></span>${tr(theme)}</button>`).join("")}</div></div>`;
content.querySelectorAll<HTMLElement>("[data-theme]").forEach((button) =>
button.addEventListener("click", () => {
activeTheme = button.dataset.theme as Theme;
find(".product-diagram").dataset.previewTheme = activeTheme;
content
.querySelectorAll<HTMLElement>("[data-theme]")
.forEach((item) =>
item.setAttribute("aria-pressed", String(item === button)),
);
}),
);
}
}
function account() {
main.innerHTML = `<section class="account-section shell"><a href="/" class="text-link back-link">${icon("back", 17)}${tr("back")}</a><div class="account-layout"><div class="account-intro"><img class="account-mark" src="/assets/vnox-mark.svg" alt="" width="76" height="76">${tr("accountHeading", "h1")}${tr("accountIntro", "p")}<div class="account-explanation">${tr("accountStage", "p")}</div></div><div id="account-content" class="account-panel" aria-live="polite"></div></div></section>`;
renderAccount();
}
function renderAccount() {
const panel = document.querySelector("#account-content");
if (!panel) return;
panel.replaceChildren();
if (sessionState === "loading") {
panel.innerHTML = `<div class="account-loading"><span class="loading-ring" aria-hidden="true"></span>${tr("sessionLoading", "p")}</div>`;
return;
}
if (sessionState === "error") {
panel.innerHTML = `${tr("accountError", "h2")}${tr("accountErrorText", "p")}<button class="button primary" id="retry-session">${tr("retry")}</button>`;
find("#retry-session", panel).addEventListener("click", refresh);
return;
}
if (currentSession?.authenticated) {
panel.innerHTML = `<div class="profile-heading"><div class="profile-avatar" id="profile-avatar" aria-hidden="true">V</div><div>${tr("profileTitle", "h2")}<p id="profile-name"></p></div></div>${tr("profileIntro", "p")}<dl class="profile-fields"><div><dt>${tr("handle")}</dt><dd id="profile-handle"></dd></div><div><dt>${tr("userId")}</dt><dd id="profile-id"></dd></div><div><dt>${tr("provider")}</dt><dd>GitHub</dd></div></dl><div class="profile-actions"><button class="button secondary" id="copy-id">${icon("copy", 17)}${tr("copy")}</button><button class="button quiet" id="logout" ${logoutState === "pending" ? "disabled" : ""}>${tr(logoutState === "pending" ? "loggingOut" : "logout")}</button></div><p class="form-message" id="profile-message" role="status"></p>`;
const user = currentSession.user;
find("#profile-name", panel).textContent =
user.display_name || t("profileFallback");
find("#profile-handle", panel).textContent = user.handle;
find("#profile-id", panel).textContent = user.user_id;
const avatar = safeAvatar(user.avatar_url);
if (avatar) {
const image = document.createElement("img");
image.src = avatar;
image.alt = "";
image.referrerPolicy = "no-referrer";
image.addEventListener("error", () => image.remove(), { once: true });
find("#profile-avatar", panel).append(image);
}
find("#copy-id", panel).addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(user.user_id);
find("#profile-message", panel).textContent = t("copied");
} catch {
find("#profile-message", panel).textContent = t("copyError");
}
});
find("#logout", panel).addEventListener("click", logout);
if (logoutState === "error")
find("#profile-message", panel).textContent = t("logoutError");
return;
}
panel.innerHTML = `<div class="login-provider">${icon("github", 33)}</div>${tr("loginTitle", "h2")}${tr("loginText", "p")}<a class="button primary github-login ${githubEnabled ? "" : "unavailable"}" ${githubEnabled ? 'href="/v1/auth/github/start"' : 'aria-disabled="true" tabindex="-1"'}>${icon("github", 21)}${tr("loginButton")}</a><p id="login-availability" class="form-message" role="status"></p><button class="text-button" id="retry-info" ${infoState === "error" ? "" : "hidden"}>${tr("retry")}</button><div class="privacy-note">${icon("check", 16)}${tr("privacy", "p")}</div>`;
find("#login-availability", panel).textContent =
infoState === "loading"
? t("loginLoading")
: infoState === "error"
? t("loginUnavailable")
: githubEnabled
? ""
: t("loginDisabled");
find("#retry-info", panel).addEventListener("click", refresh);
}
async function logout() {
if (!currentSession?.authenticated || logoutState === "pending") return;
const csrf = currentSession.csrf_token;
logoutState = "pending";
renderAccount();
try {
await request("/v1/auth/logout", {
method: "POST",
csrf,
signal: AbortSignal.timeout(15000),
});
currentSession = { authenticated: false };
logoutState = "idle";
renderAccount();
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
currentSession = { authenticated: false };
logoutState = "idle";
renderAccount();
} else {
logoutState = "error";
renderAccount();
}
}
}
function updateStatus() {
const status = document.querySelector("#service-status");
if (status) {
status.textContent = t(
infoState === "loading"
? "statusLoading"
: infoState === "ready"
? "statusReady"
: "statusUnavailable",
);
find("#service-dot").dataset.state = infoState;
}
}
async function refresh() {
controller?.abort();
controller = new AbortController();
const currentController = controller;
const signal = AbortSignal.any([
currentController.signal,
AbortSignal.timeout(15000),
]);
infoState = "loading";
if (accountPage) {
sessionState = "loading";
renderAccount();
} else updateStatus();
const info = request("/v1/info", { signal })
.then((value) => {
if (controller !== currentController) return;
if (!isInfo(value)) throw new Error("invalid_info");
githubEnabled = value.capabilities.github_auth === "enabled";
infoState = "ready";
})
.catch(() => {
if (!currentController.signal.aborted) {
githubEnabled = false;
infoState = "error";
}
})
.finally(() => {
if (controller === currentController) {
updateStatus();
if (accountPage) renderAccount();
}
});
if (accountPage) {
await Promise.allSettled([
info,
request("/v1/auth/session", { signal })
.then((value) => {
if (controller !== currentController) return;
if (!isSession(value)) throw new Error("invalid_session");
currentSession = value;
sessionState = "ready";
})
.catch(() => {
if (!currentController.signal.aborted) sessionState = "error";
})
.finally(() => {
if (controller === currentController) renderAccount();
}),
]);
} else await info;
}
function setLanguage(next: Language) {
language = next;
try {
localStorage.setItem("vnox-web-language", next);
} catch {
/* No authentication data is persisted. */
}
document.documentElement.lang = next;
document.title = t(accountPage ? "accountTitle" : "title");
find<HTMLMetaElement>('meta[name="description"]').content = t("description");
document
.querySelectorAll<HTMLElement>("[data-i18n]")
.forEach(
(element) =>
(element.textContent = t(element.dataset.i18n as MessageKey)),
);
for (const [attribute, dataKey] of [
["aria-label", "i18nAria"],
["alt", "i18nAlt"],
] as const)
document
.querySelectorAll<HTMLElement>(
`[data-${attribute === "alt" ? "i18n-alt" : "i18n-aria"}]`,
)
.forEach((element) =>
element.setAttribute(
attribute,
t(element.dataset[dataKey] as MessageKey),
),
);
document
.querySelectorAll<HTMLElement>("[data-language]")
.forEach((button) =>
button.setAttribute(
"aria-pressed",
String(button.dataset.language === next),
),
);
if (accountPage) renderAccount();
else {
renderDiagram();
updateStatus();
}
}
if (accountPage) account();
else landing();
document
.querySelectorAll<HTMLElement>("[data-language]")
.forEach((button) =>
button.addEventListener("click", () =>
setLanguage(button.dataset.language as Language),
),
);
setLanguage(language);
refresh();
window.addEventListener("pageshow", (event) => {
if (event.persisted) refresh();
});

View file

@ -1,31 +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.',
},
};
export function detectLanguage(saved, languages = []) {
if (saved === 'ru' || saved === 'en') return saved;
return languages.some(value => /^ru(?:-|$)/i.test(value)) ? 'ru' : 'en';
}
export function translate(language, key) { return messages[language]?.[key] ?? messages.en[key] ?? key; }

284
src/i18n.ts Normal file
View file

@ -0,0 +1,284 @@
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;
}

File diff suppressed because one or more lines are too long