feat(web): заготовка веб-клиента на Vite + React 19 + TypeScript strict
- стек по §5.2: React 19, React Router, TanStack Query, Zustand, Tailwind CSS 4, i18next (ru/en), Vitest + Testing Library - дизайн-токены §3 docs/client-web.md (тёмная тема по умолчанию, светлая, accent) - типизированный API-клиент §8.1: единый формат ошибок, ApiError с кодом - App: экран состояния фундамента с readz/meta, локализация ошибок по code - тесты: клиент API, форматирование, рендер App (успех/ошибка кода/сеть) - eslint + prettier + tsc strict; initial JS 97.6 KB gzip
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.go]
|
||||
indent_style = tab
|
||||
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
@@ -0,0 +1,4 @@
|
||||
# Локальный кэш npm внутри репозитория: не засоряет ~/.npm и работает в песочнице.
|
||||
cache=../.cache/npm
|
||||
audit=false
|
||||
fund=false
|
||||
@@ -0,0 +1,4 @@
|
||||
dist
|
||||
node_modules
|
||||
coverage
|
||||
*.min.js
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"printWidth": 100,
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import js from '@eslint/js';
|
||||
import globals from 'globals';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist', 'coverage', 'node_modules'] },
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommendedTypeChecked],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
globals: { ...globals.browser, ...globals.es2023 },
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/consistent-type-imports': 'error',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
|
||||
],
|
||||
'no-console': ['error', { allow: ['warn', 'error'] }],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['tests/**/*.{ts,tsx}'],
|
||||
languageOptions: { globals: { ...globals.node } },
|
||||
},
|
||||
{
|
||||
files: ['eslint.config.js'],
|
||||
extends: [tseslint.configs.disableTypeChecked],
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="ru" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<meta name="description" content="glchat — self-hosted платформа общения" />
|
||||
<title>glchat</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<noscript>Для работы glchat требуется JavaScript.</noscript>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+4679
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "glchat-web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"check": "tsc --noEmit -p tsconfig.app.json",
|
||||
"lint": "eslint . && prettier --check .",
|
||||
"format": "prettier --write .",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "5.103.1",
|
||||
"i18next": "26.4.2",
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0",
|
||||
"react-i18next": "17.0.14",
|
||||
"react-router": "8.4.0",
|
||||
"zustand": "5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "10.0.1",
|
||||
"@tailwindcss/vite": "4.3.3",
|
||||
"@testing-library/jest-dom": "7.0.1",
|
||||
"@testing-library/react": "16.3.3",
|
||||
"@testing-library/user-event": "14.6.7",
|
||||
"@types/node": "26.6.2",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "19.3.0",
|
||||
"@vitejs/plugin-react": "6.1.1",
|
||||
"eslint": "10.11.0",
|
||||
"eslint-plugin-react-hooks": "7.1.1",
|
||||
"eslint-plugin-react-refresh": "0.5.7",
|
||||
"globals": "17.12.0",
|
||||
"jsdom": "30.1.0",
|
||||
"prettier": "3.9.8",
|
||||
"tailwindcss": "4.3.3",
|
||||
"typescript": "6.0.3",
|
||||
"typescript-eslint": "8.70.0",
|
||||
"vite": "8.3.0",
|
||||
"vitest": "5.0.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="glchat">
|
||||
<rect width="64" height="64" rx="14" fill="#4c5bd4" />
|
||||
<path
|
||||
d="M18 22h28a4 4 0 0 1 4 4v14a4 4 0 0 1-4 4H30l-8 8v-8h-4a4 4 0 0 1-4-4V26a4 4 0 0 1 4-4Z"
|
||||
fill="#ffffff"
|
||||
/>
|
||||
<circle cx="26" cy="33" r="3" fill="#4c5bd4" />
|
||||
<circle cx="34" cy="33" r="3" fill="#4c5bd4" />
|
||||
<circle cx="42" cy="33" r="3" fill="#4c5bd4" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 433 B |
+125
@@ -0,0 +1,125 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { fetchReadiness, readyQueryKey } from '@/api/health';
|
||||
import { fetchMeta, metaQueryKey } from '@/api/meta';
|
||||
import { Badge, Button, Card } from '@/components/ui/primitives';
|
||||
import { StatBytes, StatRow } from '@/components/ui/StatRow';
|
||||
import { errorCode } from '@/lib/format';
|
||||
import { supportedLanguages, type SupportedLanguage } from '@/i18n';
|
||||
import { useUiStore } from '@/stores/ui';
|
||||
|
||||
export function App() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const theme = useUiStore((state) => state.theme);
|
||||
const toggleTheme = useUiStore((state) => state.toggleTheme);
|
||||
const locale = i18n.resolvedLanguage ?? 'ru';
|
||||
|
||||
const meta = useQuery({
|
||||
queryKey: metaQueryKey,
|
||||
queryFn: ({ signal }) => fetchMeta(signal),
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const readiness = useQuery({
|
||||
queryKey: readyQueryKey,
|
||||
queryFn: ({ signal }) => fetchReadiness(signal),
|
||||
retry: 1,
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
|
||||
const online = readiness.isSuccess || meta.isSuccess;
|
||||
const schemaReady = readiness.data?.checks['database'] === 'ok';
|
||||
|
||||
const errorMessage = (error: unknown): string => {
|
||||
const code = errorCode(error);
|
||||
const key = `errors.${code}`;
|
||||
const translated = t(key);
|
||||
return translated === key ? t('errors.unknown', { code }) : translated;
|
||||
};
|
||||
|
||||
const changeLanguage = (language: SupportedLanguage): void => {
|
||||
window.localStorage.setItem('glchat.language', language);
|
||||
void i18n.changeLanguage(language);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex min-h-full w-full max-w-3xl flex-col gap-6 px-4 py-10">
|
||||
<header className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">{t('app.name')}</h1>
|
||||
<p className="mt-1 text-fg-muted">{t('app.tagline')}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge aria-live="polite" data-testid="connection-state">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`h-2 w-2 rounded-full ${online ? 'bg-success' : 'bg-danger'}`}
|
||||
/>
|
||||
{t(online ? 'health.online' : 'health.offline')}
|
||||
</Badge>
|
||||
<Button variant="ghost" onClick={toggleTheme}>
|
||||
{t(theme === 'dark' ? 'theme.switchToLight' : 'theme.switchToDark')}
|
||||
</Button>
|
||||
<label className="flex items-center gap-1 text-sm text-fg-muted">
|
||||
<span className="sr-only">{t('language.label')}</span>
|
||||
<select
|
||||
className="rounded-[var(--radius-sm)] border border-border/60 bg-surface-2 px-2 py-1 text-fg"
|
||||
value={locale.startsWith('en') ? 'en' : 'ru'}
|
||||
onChange={(event) => changeLanguage(event.target.value === 'en' ? 'en' : 'ru')}
|
||||
>
|
||||
{supportedLanguages.map((language) => (
|
||||
<option key={language} value={language}>
|
||||
{t(`language.${language}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<Card>
|
||||
<h2 className="text-lg font-semibold">{t('status.title')}</h2>
|
||||
<p className="mt-1 text-fg-muted">{t('status.description')}</p>
|
||||
|
||||
{meta.isPending ? (
|
||||
<p className="mt-4 text-fg-muted" role="status">
|
||||
{t('status.connecting')}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{meta.isError ? (
|
||||
<div className="mt-4 flex items-center justify-between gap-4" role="alert">
|
||||
<p className="text-danger">{errorMessage(meta.error)}</p>
|
||||
<Button variant="ghost" onClick={() => void meta.refetch()}>
|
||||
{t('status.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{meta.data ? (
|
||||
<dl className="mt-4 text-sm">
|
||||
<StatRow label={t('status.instance')} value={meta.data.name} />
|
||||
<StatRow label={t('status.version')} value={meta.data.version} />
|
||||
<StatRow label={t('status.apiVersion')} value={meta.data.api_version} />
|
||||
<StatRow
|
||||
label={t('status.schemaReady')}
|
||||
value={schemaReady ? t('status.schemaOk') : (readiness.data?.status ?? '…')}
|
||||
/>
|
||||
<StatRow
|
||||
label={t('status.maxUpload')}
|
||||
value={<StatBytes bytes={meta.data.max_upload_size} locale={locale} />}
|
||||
/>
|
||||
</dl>
|
||||
) : null}
|
||||
</Card>
|
||||
|
||||
<footer className="mt-auto flex items-center justify-between text-xs text-fg-muted">
|
||||
<span>
|
||||
{t('app.name')} · {t('footer.license')}
|
||||
</span>
|
||||
<span className="tabular-nums">{meta.data?.commit ?? ''}</span>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
export interface ApiErrorBody {
|
||||
error: {
|
||||
code: string;
|
||||
message: string;
|
||||
details?: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly code: string;
|
||||
readonly status: number;
|
||||
readonly details?: Record<string, unknown>;
|
||||
|
||||
constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
if (details !== undefined) {
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const API_PREFIX = '/api/v1';
|
||||
|
||||
export function isApiErrorPayload(value: unknown): value is ApiErrorBody['error'] {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return false;
|
||||
}
|
||||
const candidate = value as { code?: unknown; message?: unknown };
|
||||
return typeof candidate.code === 'string' && typeof candidate.message === 'string';
|
||||
}
|
||||
|
||||
export function apiErrorCode(error: unknown): string | null {
|
||||
if (error === null || typeof error !== 'object') {
|
||||
return null;
|
||||
}
|
||||
const payload = (error as { apiError?: unknown }).apiError;
|
||||
return isApiErrorPayload(payload) ? payload.code : null;
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
export function parsePayload(text: string, contentType: string | null): unknown {
|
||||
if (text.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (contentType !== null && !contentType.includes('application/json')) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const init: RequestInit = {
|
||||
method: options.method ?? 'GET',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(options.body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||
...options.headers,
|
||||
},
|
||||
};
|
||||
if (options.body !== undefined) {
|
||||
init.body = JSON.stringify(options.body);
|
||||
}
|
||||
if (options.signal !== undefined) {
|
||||
init.signal = options.signal;
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_PREFIX}${path}`, init);
|
||||
const text = await response.text();
|
||||
const payload = parsePayload(text, response.headers.get('Content-Type'));
|
||||
|
||||
if (!response.ok) {
|
||||
const envelope =
|
||||
typeof payload === 'object' && payload !== null
|
||||
? (payload as { error?: unknown }).error
|
||||
: undefined;
|
||||
if (isApiErrorPayload(envelope)) {
|
||||
const error = new ApiError(
|
||||
response.status,
|
||||
envelope.code,
|
||||
envelope.message,
|
||||
envelope.details,
|
||||
);
|
||||
Object.defineProperty(error, 'apiError', {
|
||||
value: envelope,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
throw new ApiError(response.status, 'internal.error', 'unexpected response');
|
||||
}
|
||||
return payload as T;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { request } from './client';
|
||||
|
||||
export interface ReadinessResponse {
|
||||
status: 'ready' | 'unavailable';
|
||||
version: string;
|
||||
checks: Record<string, string>;
|
||||
}
|
||||
|
||||
export const readyQueryKey = ['readyz'] as const;
|
||||
|
||||
export function fetchReadiness(signal?: AbortSignal): Promise<ReadinessResponse> {
|
||||
return request<ReadinessResponse>('/readyz', signal === undefined ? {} : { signal });
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { request } from './client';
|
||||
|
||||
export interface InstanceFeatures {
|
||||
registration_enabled: boolean;
|
||||
anti_bot_enabled: boolean;
|
||||
voice_enabled: boolean;
|
||||
web_push_enabled: boolean;
|
||||
oauth_enabled: boolean;
|
||||
passkeys_enabled: boolean;
|
||||
}
|
||||
|
||||
export interface InstanceMeta {
|
||||
name: string;
|
||||
version: string;
|
||||
commit: string;
|
||||
build_date: string;
|
||||
api_version: string;
|
||||
base_url: string;
|
||||
files_url: string;
|
||||
gateway_url: string;
|
||||
rtc_path: string;
|
||||
max_upload_size: number;
|
||||
features: InstanceFeatures;
|
||||
}
|
||||
|
||||
export const metaQueryKey = ['meta'] as const;
|
||||
|
||||
export function fetchMeta(signal?: AbortSignal): Promise<InstanceMeta> {
|
||||
return request<InstanceMeta>('/meta', signal === undefined ? {} : { signal });
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import { formatBytes } from '@/lib/format';
|
||||
|
||||
interface StatRowProps {
|
||||
label: string;
|
||||
value: ReactNode;
|
||||
}
|
||||
|
||||
export function StatRow({ label, value }: StatRowProps) {
|
||||
return (
|
||||
<div className="flex items-baseline justify-between gap-4 border-b border-border/40 py-2 last:border-b-0">
|
||||
<dt className="text-fg-muted">{label}</dt>
|
||||
<dd className="font-medium tabular-nums">{value}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatBytes({ bytes, locale }: { bytes: number; locale: string }) {
|
||||
return <span title={`${bytes} B`}>{formatBytes(bytes, locale)}</span>;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { ButtonHTMLAttributes, HTMLAttributes } from 'react';
|
||||
|
||||
type Variant = 'primary' | 'ghost';
|
||||
|
||||
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: Variant;
|
||||
}
|
||||
|
||||
const variants: Record<Variant, string> = {
|
||||
primary:
|
||||
'bg-accent text-accent-fg hover:opacity-90 border border-transparent shadow-[var(--shadow-1)]',
|
||||
ghost: 'bg-surface-2 text-fg hover:bg-surface-3 border border-border/60',
|
||||
};
|
||||
|
||||
export function Button({ variant = 'primary', className = '', ...rest }: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`inline-flex items-center justify-center gap-2 rounded-[var(--radius-md)] px-3 py-1.5 text-sm font-medium transition-colors duration-[var(--duration-fast)] disabled:cursor-not-allowed disabled:opacity-50 ${variants[variant]} ${className}`}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function Card({ className = '', ...rest }: HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
className={`rounded-[var(--radius-lg)] border border-border/60 bg-surface-1 p-5 shadow-[var(--shadow-2)] ${className}`}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function Badge({ className = '', ...rest }: HTMLAttributes<HTMLSpanElement>) {
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 rounded-full border border-border/60 bg-surface-2 px-2 py-0.5 text-xs text-fg-muted ${className}`}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import i18n from 'i18next';
|
||||
import { initReactI18next } from 'react-i18next';
|
||||
|
||||
import en from './locales/en.json';
|
||||
import ru from './locales/ru.json';
|
||||
|
||||
export const defaultNS = 'translation';
|
||||
export const supportedLanguages = ['ru', 'en'] as const;
|
||||
export type SupportedLanguage = (typeof supportedLanguages)[number];
|
||||
|
||||
const storedLanguage =
|
||||
typeof window === 'undefined' ? null : window.localStorage.getItem('glchat.language');
|
||||
|
||||
const initialLanguage: SupportedLanguage =
|
||||
storedLanguage === 'en' || storedLanguage === 'ru' ? storedLanguage : 'ru';
|
||||
|
||||
void i18n.use(initReactI18next).init({
|
||||
resources: {
|
||||
ru: { translation: ru },
|
||||
en: { translation: en },
|
||||
},
|
||||
lng: initialLanguage,
|
||||
fallbackLng: 'ru',
|
||||
interpolation: { escapeValue: false },
|
||||
returnNull: false,
|
||||
});
|
||||
|
||||
export default i18n;
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"app": {
|
||||
"name": "glchat",
|
||||
"tagline": "Self-hosted communication: text, voice, video"
|
||||
},
|
||||
"status": {
|
||||
"title": "Foundation deployed",
|
||||
"description": "The server responds, the database runs in WAL mode, migrations are applied. Chat features arrive in the next phases.",
|
||||
"connecting": "Checking server status…",
|
||||
"instance": "Instance",
|
||||
"version": "Version",
|
||||
"apiVersion": "API version",
|
||||
"schemaReady": "Database",
|
||||
"schemaOk": "ready",
|
||||
"maxUpload": "Maximum upload size",
|
||||
"checks": "Checks",
|
||||
"retry": "Retry"
|
||||
},
|
||||
"health": {
|
||||
"online": "Server is reachable",
|
||||
"offline": "Server is unreachable"
|
||||
},
|
||||
"errors": {
|
||||
"network.unreachable": "The server is not responding. Check your connection and try again.",
|
||||
"network.aborted": "The request was aborted.",
|
||||
"instance.not_ready": "The instance is still starting. Try again in a few seconds.",
|
||||
"internal.error": "Internal server error.",
|
||||
"not_found": "The requested resource was not found.",
|
||||
"unknown": "Unknown error ({{code}})."
|
||||
},
|
||||
"theme": {
|
||||
"switchToLight": "Light theme",
|
||||
"switchToDark": "Dark theme"
|
||||
},
|
||||
"language": {
|
||||
"label": "Language",
|
||||
"ru": "Русский",
|
||||
"en": "English"
|
||||
},
|
||||
"footer": {
|
||||
"source": "Source code",
|
||||
"license": "AGPL-3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"app": {
|
||||
"name": "glchat",
|
||||
"tagline": "Self-hosted общение: текст, голос, видео"
|
||||
},
|
||||
"status": {
|
||||
"title": "Фундамент развёрнут",
|
||||
"description": "Сервер отвечает, база данных в режиме WAL, миграции применены. Функции общения появятся в следующих фазах.",
|
||||
"connecting": "Проверяем состояние сервера…",
|
||||
"instance": "Инстанс",
|
||||
"version": "Версия",
|
||||
"apiVersion": "Версия API",
|
||||
"schemaReady": "База данных",
|
||||
"schemaOk": "готова",
|
||||
"maxUpload": "Максимальный размер загрузки",
|
||||
"checks": "Проверки",
|
||||
"retry": "Повторить"
|
||||
},
|
||||
"health": {
|
||||
"online": "Сервер доступен",
|
||||
"offline": "Сервер недоступен"
|
||||
},
|
||||
"errors": {
|
||||
"network.unreachable": "Сервер не отвечает. Проверьте соединение и повторите попытку.",
|
||||
"network.aborted": "Запрос отменён.",
|
||||
"instance.not_ready": "Инстанс ещё запускается. Повторите через несколько секунд.",
|
||||
"internal.error": "Внутренняя ошибка сервера.",
|
||||
"not_found": "Запрашиваемый ресурс не найден.",
|
||||
"unknown": "Неизвестная ошибка ({{code}})."
|
||||
},
|
||||
"theme": {
|
||||
"switchToLight": "Светлая тема",
|
||||
"switchToDark": "Тёмная тема"
|
||||
},
|
||||
"language": {
|
||||
"label": "Язык",
|
||||
"ru": "Русский",
|
||||
"en": "English"
|
||||
},
|
||||
"footer": {
|
||||
"source": "Исходный код",
|
||||
"license": "AGPL-3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
@import 'tailwindcss';
|
||||
|
||||
/*
|
||||
* Дизайн-токены (docs/client-web.md §3). Тёмная тема по умолчанию,
|
||||
* светлая — тот же набор токенов. Акцент сервера переопределяет --color-accent
|
||||
* в скоупе сервера.
|
||||
*/
|
||||
@theme {
|
||||
--color-bg: oklch(0.19 0.02 265);
|
||||
--color-surface-1: oklch(0.23 0.02 265);
|
||||
--color-surface-2: oklch(0.27 0.02 265);
|
||||
--color-surface-3: oklch(0.32 0.02 265);
|
||||
--color-fg: oklch(0.96 0.005 265);
|
||||
--color-fg-muted: oklch(0.72 0.01 265);
|
||||
--color-accent: oklch(0.66 0.16 265);
|
||||
--color-accent-fg: oklch(0.99 0.005 265);
|
||||
--color-danger: oklch(0.62 0.19 25);
|
||||
--color-success: oklch(0.72 0.15 150);
|
||||
--color-warning: oklch(0.79 0.14 85);
|
||||
--color-border: oklch(0.35 0.02 265);
|
||||
|
||||
--radius-sm: 6px;
|
||||
--radius-md: 10px;
|
||||
--radius-lg: 14px;
|
||||
|
||||
--shadow-1: 0 1px 2px rgb(0 0 0 / 0.3);
|
||||
--shadow-2: 0 4px 12px rgb(0 0 0 / 0.35);
|
||||
--shadow-3: 0 12px 32px rgb(0 0 0 / 0.4);
|
||||
|
||||
--duration-fast: 120ms;
|
||||
--duration-base: 200ms;
|
||||
--ease-out: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
:root[data-theme='light'] {
|
||||
--color-bg: oklch(0.98 0.003 265);
|
||||
--color-surface-1: oklch(1 0 0);
|
||||
--color-surface-2: oklch(0.96 0.004 265);
|
||||
--color-surface-3: oklch(0.92 0.006 265);
|
||||
--color-fg: oklch(0.2 0.02 265);
|
||||
--color-fg-muted: oklch(0.48 0.015 265);
|
||||
--color-border: oklch(0.87 0.008 265);
|
||||
--shadow-1: 0 1px 2px rgb(0 0 0 / 0.08);
|
||||
--shadow-2: 0 4px 12px rgb(0 0 0 / 0.1);
|
||||
--shadow-3: 0 12px 32px rgb(0 0 0 / 0.12);
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background-color: var(--color-bg);
|
||||
color: var(--color-fg);
|
||||
font-family:
|
||||
system-ui,
|
||||
-apple-system,
|
||||
'Segoe UI',
|
||||
Inter,
|
||||
sans-serif;
|
||||
font-size: 14px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { ApiError, apiErrorCode } from '@/api/client';
|
||||
|
||||
export function formatBytes(bytes: number, locale = 'ru'): string {
|
||||
if (!Number.isFinite(bytes) || bytes < 0) {
|
||||
return '—';
|
||||
}
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
let value = bytes;
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < units.length - 1) {
|
||||
value /= 1024;
|
||||
unit += 1;
|
||||
}
|
||||
const formatted = new Intl.NumberFormat(locale, {
|
||||
maximumFractionDigits: value < 10 && unit > 0 ? 1 : 0,
|
||||
}).format(value);
|
||||
return `${formatted} ${units[unit]}`;
|
||||
}
|
||||
|
||||
// instanceof is unreliable across module instances (aliases, lazy chunks),
|
||||
// so the error shape is checked structurally as well.
|
||||
function hasErrorCode(value: unknown): value is { code: string } {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
typeof (value as { code?: unknown }).code === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
export function errorCode(error: unknown): string {
|
||||
// The code from the server error envelope wins: it survives serialization
|
||||
// boundaries where instanceof checks do not.
|
||||
const envelopeCode = apiErrorCode(error);
|
||||
if (envelopeCode !== null) {
|
||||
return envelopeCode;
|
||||
}
|
||||
if (error instanceof ApiError) {
|
||||
return error.code;
|
||||
}
|
||||
if (hasErrorCode(error)) {
|
||||
return error.code;
|
||||
}
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return 'network.aborted';
|
||||
}
|
||||
return 'network.unreachable';
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
|
||||
import { App } from '@/App';
|
||||
import { applyTheme, useUiStore } from '@/stores/ui';
|
||||
import '@/i18n';
|
||||
import '@/index.css';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
applyTheme(useUiStore.getState().theme);
|
||||
|
||||
const container = document.getElementById('root');
|
||||
if (!container) {
|
||||
throw new Error('root container is missing');
|
||||
}
|
||||
|
||||
createRoot(container).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,43 @@
|
||||
import { create } from 'zustand';
|
||||
|
||||
export type Theme = 'dark' | 'light';
|
||||
|
||||
interface UiState {
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
toggleTheme: () => void;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'glchat.theme';
|
||||
|
||||
function initialTheme(): Theme {
|
||||
if (typeof window === 'undefined') {
|
||||
return 'dark';
|
||||
}
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (stored === 'light' || stored === 'dark') {
|
||||
return stored;
|
||||
}
|
||||
return 'dark';
|
||||
}
|
||||
|
||||
export function applyTheme(theme: Theme): void {
|
||||
if (typeof document === 'undefined') {
|
||||
return;
|
||||
}
|
||||
document.documentElement.dataset['theme'] = theme;
|
||||
}
|
||||
|
||||
export const useUiStore = create<UiState>((set, get) => ({
|
||||
theme: initialTheme(),
|
||||
setTheme: (theme) => {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.setItem(STORAGE_KEY, theme);
|
||||
}
|
||||
applyTheme(theme);
|
||||
set({ theme });
|
||||
},
|
||||
toggleTheme: () => {
|
||||
get().setTheme(get().theme === 'dark' ? 'light' : 'dark');
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,100 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { App } from '@/App';
|
||||
import type { InstanceMeta } from '@/api/meta';
|
||||
import '@/i18n';
|
||||
|
||||
const meta: InstanceMeta = {
|
||||
name: 'glchat',
|
||||
version: 'v0.1.0-test',
|
||||
commit: 'deadbee',
|
||||
build_date: '2026-09-19T00:00:00Z',
|
||||
api_version: 'v1',
|
||||
base_url: 'https://gl.localhost',
|
||||
files_url: 'https://files.gl.localhost',
|
||||
gateway_url: 'wss://gl.localhost/gateway',
|
||||
rtc_path: '/rtc',
|
||||
max_upload_size: 26214400,
|
||||
features: {
|
||||
registration_enabled: true,
|
||||
anti_bot_enabled: false,
|
||||
voice_enabled: false,
|
||||
web_push_enabled: false,
|
||||
oauth_enabled: false,
|
||||
passkeys_enabled: false,
|
||||
},
|
||||
};
|
||||
|
||||
const readyBody = { status: 'ready', version: 'test', checks: { database: 'ok' } };
|
||||
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
function renderApp() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('App', () => {
|
||||
it('renders instance metadata from the API', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn((input: RequestInfo | URL) => {
|
||||
const url = input instanceof Request ? input.url : String(input);
|
||||
return Promise.resolve(url.endsWith('/api/v1/meta') ? json(meta) : json(readyBody));
|
||||
}),
|
||||
);
|
||||
|
||||
renderApp();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('v0.1.0-test')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText('v1')).toBeInTheDocument();
|
||||
expect(screen.getByText('25 MB')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('connection-state')).toHaveTextContent('Сервер доступен');
|
||||
});
|
||||
|
||||
it('localizes a server error by its code and offers a retry', async () => {
|
||||
const fetchMock = vi.fn(() =>
|
||||
json({ error: { code: 'internal.error', message: 'boom' } }, 500),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
renderApp();
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Внутренняя ошибка сервера.');
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
expect(screen.getByRole('button', { name: 'Повторить' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('falls back to a network message when the server is unreachable', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')));
|
||||
|
||||
renderApp();
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Сервер не отвечает');
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
expect(screen.getByTestId('connection-state')).toHaveTextContent('Сервер недоступен');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { ApiError, request } from '@/api/client';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
describe('api client', () => {
|
||||
it('returns the parsed payload on success', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ api_version: 'v1' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(request<{ api_version: string }>('/meta')).resolves.toEqual({
|
||||
api_version: 'v1',
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/v1/meta',
|
||||
expect.objectContaining({ method: 'GET', credentials: 'same-origin' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('maps the server error envelope to ApiError', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
jsonResponse({ error: { code: 'perm.denied', message: 'no access' } }, 403),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(request('/guilds/1')).rejects.toMatchObject({
|
||||
name: 'ApiError',
|
||||
code: 'perm.denied',
|
||||
status: 403,
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to internal.error when the body is not an envelope', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response('gateway timeout', { status: 504 })),
|
||||
);
|
||||
|
||||
const error = await request('/meta').catch((reason: unknown) => reason);
|
||||
expect(error).toBeInstanceOf(ApiError);
|
||||
expect((error as ApiError).code).toBe('internal.error');
|
||||
expect((error as ApiError).status).toBe(504);
|
||||
});
|
||||
|
||||
it('sends a json body for write requests', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ ok: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await request('/guilds', { method: 'POST', body: { name: 'test' } });
|
||||
|
||||
const init = fetchMock.mock.calls[0]?.[1] as RequestInit;
|
||||
expect(init.body).toBe('{"name":"test"}');
|
||||
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { errorCode, formatBytes } from '@/lib/format';
|
||||
import { ApiError } from '@/api/client';
|
||||
|
||||
describe('formatBytes', () => {
|
||||
it('renders human readable sizes', () => {
|
||||
expect(formatBytes(512)).toBe('512 B');
|
||||
expect(formatBytes(1024)).toBe('1 KB');
|
||||
expect(formatBytes(26214400)).toBe('25 MB');
|
||||
expect(formatBytes(1073741824)).toBe('1 GB');
|
||||
});
|
||||
|
||||
it('handles invalid input', () => {
|
||||
expect(formatBytes(-1)).toBe('—');
|
||||
expect(formatBytes(Number.NaN)).toBe('—');
|
||||
});
|
||||
});
|
||||
|
||||
describe('errorCode', () => {
|
||||
it('extracts the server error code', () => {
|
||||
expect(errorCode(new ApiError(403, 'perm.denied', 'nope'))).toBe('perm.denied');
|
||||
});
|
||||
|
||||
it('maps unknown failures to a network code', () => {
|
||||
expect(errorCode(new Error('socket hang up'))).toBe('network.unreachable');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { afterEach, vi } from 'vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
// Globals stubbed with vi.stubGlobal must be dropped between tests,
|
||||
// otherwise a stub from one test leaks into the next one.
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
window.localStorage.clear();
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"types": ["vite/client", "vitest/globals", "@testing-library/jest-dom"],
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"noImplicitOverride": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"composite": true,
|
||||
"tsBuildInfoFile": "./node_modules/.cache/tsconfig.app.tsbuildinfo",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src", "tests"]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"types": ["node"],
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"composite": true,
|
||||
"tsBuildInfoFile": "./node_modules/.cache/tsconfig.node.tsbuildinfo"
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
sourcemap: false,
|
||||
target: 'es2022',
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': 'http://127.0.0.1:8080',
|
||||
'/healthz': 'http://127.0.0.1:8080',
|
||||
'/readyz': 'http://127.0.0.1:8080',
|
||||
// Gateway (WS) is added in phase 1 together with the realtime server.
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
globals: true,
|
||||
setupFiles: ['./tests/setup.ts'],
|
||||
include: ['tests/**/*.test.{ts,tsx}'],
|
||||
css: false,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user