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:
+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');
|
||||
},
|
||||
}));
|
||||
Reference in New Issue
Block a user