chore(history): squash 100 commit(s) from 2026-09-24
- fix(backend): case-insensitive unique email, revoke PUBLIC schema access, pin Argon2id params - test(backend): assert password length cap boundary (256 ok, 257 rejected) - docs(backend): plan — typed JWT token kinds so refresh/device tokens cannot pass as access tokens - feat(backend): JWT access/refresh token issue and verify - feat(backend): accounts repository (create/find_by_email/find_by_id) - refactor(gui): LoVisualAddonManagerScreen 989→10 файлов addon/ (8.5.2) - docs(backend): plan — fix sqlx::migrate! path in integration tests - feat(backend): POST /auth/register and /auth/login - refactor(settings): SettingsPanelComponent 715→81 + 6 helpers (8.5.2) - docs(backend): plan — harden device flow (single-use codes, bounded store, 404/429) - feat(backend): OAuth device authorization grant for mod login - fix(backend): first confirm wins for device codes - docs(backend): plan — split Task 8 (refactor) and Task 9 (avatars), harden avatar handling - refactor(mixins): LocalPlayerMixin 691→111 + 4 handlers (8.5.2) - refactor(visuals): Trails 687→130 (8.5.2) - refactor(render): ItemBatchRenderer 677->100 (8.5.2) - refactor(visuals): ReimaginedVisual 674→118 + 5 helpers (8.5.2) - refactor(config): ConfigSerializer 668→91 + 4 helpers (8.5.2) - refactor(hud): DynamicIsland 661→158 + 4 helpers (8.5.2) - refactor(render): GlStencilFramebufferSupport 666→169 (8.5.2) - refactor(gui): MenuScreen 669→128 + 4 helpers (8.5.2) - refactor(render): UiStyle 644→170 + 3 helpers (8.5.2) - refactor(gui): ModuleComponent 613→98 + 4 helpers (8.5.2) - refactor(media): MediaSessionService 616→200 + 4 helpers (8.5.2) - refactor(gui): RelationsComponent 661→59 + 4 helpers (8.5.2) - chore(license): strip GPL file headers from all Java sources - refactor(aiming): PointTracker 583→168 + 2 helpers (8.5.2) - refactor(gui): LoVisualProxyManagerScreen 591→132 + 2 helpers (8.5.2) - refactor(visuals): KillEffect 588→96 + 4 helpers (8.5.2) - refactor(render): MeshBuilder +4 helpers (8.5.2) - refactor(visuals): extract WorldParticlesRender helper (8.5.2) - refactor(world): ExplosionDamageUtil 551→116 + 2 helpers (8.5.2) - refactor(visuals): TazikHat 596->179 + Model + Palette in hats/tazik (8.5.2) - chore(license): strip GPL header from remaining 30 files and make strip script variant-aware - refactor(gui): ThemeComponent 561->166 + CardRenderer + ScrollState (8.5.2) - refactor(hud): CustomHotbar 556→178 + Renderer + Selection + SelectionGradient (8.5.2) - refactor(gui): ThemeCardRenderer perf + readability polish - refactor(clickgui): CooldownRulesSetting 596->198 + Editor + DetailRenderer (8.5.2) - refactor(hud): HudNotifier 561->200 + Painter + runtime/HudNotifierRuntime (8.5.2) - refactor(theme): Themes 555->168 + impl/Transition + impl/Blending + impl/ProfileCodec (8.5.2) - refactor(theme): EditableClickGuiTheme 205->185 + JavaDoc (8.5.2) - refactor(theme): ThemeStore 491->128 + store/ThemeStoreJson + store/ThemeStoreIO (8.5.2) - refactor(clickgui): ClickGuiRenderer 604->200 compacted one-line delegators + JavaDoc (8.5.2) - refactor(mainmenu): LoVisualMainMenuScreen 551->161 + impl/Painter + impl/Renderer + impl/TextUtil (8.5.2) - refactor(clickgui): ClickGuiTextEditorState 531->187 + impl/EditorCaret + impl/EditorPainter (8.5.2) - refactor(tab): TabListModel 525->139 + model/Collector + model/Reader + model/Signature + model/TextSplitter (8.5.2) - refactor(backend): shared bearer helper and test helpers, build_app takes Config, validate JWT secret strength - refactor(module): ModuleManager 521->198 + impl/Registrar + impl/Dispatcher (8.5.2) - feat(backend): avatar upload with decode, square crop, PNG re-encode and S3 storage - refactor(clip): ClipFunction 512->146 + impl/Geometry + impl/Debug (8.5.2) - docs(backend): implementation plans for gateway (auth hardening, gRPC, rate limits) and configs-service - refactor(iris-patch): ShaderPatchEngine 499->146 + impl/Repo (8.5.2) - chore(frontend): add router, react-query, fonts and vitest; dev proxy to gateway - refactor(hud): ScriptedListHudPanel 499->158 + panel/Props + panel/Signature (8.5.2) - refactor(hud): BaseHudElement 499->199 + impl/Registry + impl/Namer + impl/Prewarm (8.5.2) - refactor(clickgui): Setting 498->170 + impl/Localization + impl/I18n (8.5.2) - refact(viewmodel): split swing animations into camera/swing package - refact(kineticlyrics): split module into stage, playback and modes - rename(holeesp): module HoleESP -> CrystalHoles - refact(crystalholes): split module into crystal scanner, renderer and safety - refact(addonmanager): split manager into lifecycle, runtime, descriptors and profiles - refact(accountconfig): split config into store, session and value helpers - refactor(render): CustomTextRenderer 229->195, extract glyph-pass into GradientTexts helper - docs(TODO): mark AddonManager split done; close 9.2 refactor gate - refactor(media): LinuxMediaSession 441->148, split reader + track/seek state - refactor(nametags): split NameTags into facade + impl helpers - refactor(clickgui): split MainSettingsComponent into facade + scroll + model - refactor(hud): split CustomBar into facade, model and BarSettings - docs(frontend): implementation plan with design system from the mod theme - feat(frontend): design tokens from the mod theme, fonts and shared UI kit - fix(accounts): run migrations on startup, offload Argon2, validate register input, JSON error shape - docs(gateway): plan note on splitting auth handlers before refresh endpoints - feat(frontend): API client with silent refresh, error descriptions and test helpers - style(mod): group compact one-line bulk query methods in ModuleManager - feat(frontend): session restore, login and registration with client-side validation - refactor(hud): split CustomHealthBar into facade + painter + script renderer - docs(mod): record the 2026-09-24 HUD/settings split wave in TODO phase 8.5 - refactor(rhi): split GlStencilShapeClipBackend into facade + native-state + pass-lifecycle helpers - refactor(rhi): split VulkanRenderStateBridge into facade + MSAA and stencil state helpers - refactor(backtrack): split BacktrackController into facade + model + impl helpers - refactor(svg): split SvgPathParser into facade + arc geometry + command/curve helpers - refactor(mixin): split ClientPacketListenerMixin into hook-only mixin + handlers - refactor(renderer3d): un-nest batch bindings + culling into sibling impl types - refactor(renderwarp): extract static factories + geometry into impl helpers - feat(backend): add common crate with shared JWT, internal gateway contract and accounts proto - refactor(guimixin): move hook bodies into handlers, keep mixin as hooks + shadows - feat(accounts): accept only gateway traffic, read identity from gateway header - refactor(cacheduiscriptruntime): extract engine, hashing and frame stats into impl - refactor(customskyboxrenderer): extract projection, shader passes and sun into impl - refactor(betterchatstoremanager): extract persistence, key/path and hover helpers into impl - feat(accounts): rotating opaque refresh tokens in httpOnly cookie, /auth/refresh and /auth/logout - refactor(targetesp): extract crystal rendering subsystem into impl/TargetEspCrystalRenderer - refactor(betterchathovercache): extract disk codec and lookup indexing into impl/ChatHoverCacheCodec - refactor(microsoftauth): split HTTP transport, device-code and Xbox flows into impl/ - refactor(pvpcooldowns): extract local item-rule engine and defaults into impl/PvpCooldownRules - refactor(lovisual): extract HUD/world render orchestration into HudRender helper - refactor(statuseffectheuristics): extract palette/inference into ParticlePalette and color utils into ParticleColors - refactor(dropesp): extract overlay/label render subsystem into impl/DropEspOverlayRenderer - refactor(proxy): extract SOCKS handshake message builders into ProxyProtocolMessages - refactor(eagleutil): promote EdgeRecovery controller and RecoveryMode to top-level class
This commit is contained in:
parent
9d08fa910a
commit
72bc4c7148
1897 changed files with 36199 additions and 39289 deletions
101
frontend/src/shared/api/client.ts
Normal file
101
frontend/src/shared/api/client.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
export class ApiError extends Error {
|
||||
readonly status: number
|
||||
readonly retryAfter: number | null
|
||||
|
||||
constructor(status: number, message: string, retryAfter: number | null = null) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
this.retryAfter = retryAfter
|
||||
}
|
||||
}
|
||||
|
||||
export type RequestOptions = { method?: string; json?: unknown; body?: BodyInit; signal?: AbortSignal }
|
||||
|
||||
export type ApiClient = {
|
||||
request<T>(path: string, options?: RequestOptions): Promise<T>
|
||||
refresh(): Promise<boolean>
|
||||
setAccessToken(token: string | null): void
|
||||
hasAccessToken(): boolean
|
||||
}
|
||||
|
||||
async function toError(res: Response): Promise<ApiError> {
|
||||
let message = `HTTP ${res.status}`
|
||||
try {
|
||||
const body: unknown = await res.json()
|
||||
if (body && typeof body === 'object' && 'error' in body && typeof body.error === 'string') message = body.error
|
||||
} catch {
|
||||
// non-JSON error body: keep the status text
|
||||
}
|
||||
const retry = Number(res.headers.get('retry-after'))
|
||||
return new ApiError(res.status, message, Number.isFinite(retry) && retry > 0 ? retry : null)
|
||||
}
|
||||
|
||||
export function createApiClient(
|
||||
baseUrl = '/api',
|
||||
// Resolved at call time so tests can stub the global fetch.
|
||||
fetchImpl: typeof fetch = (input, init) => fetch(input, init),
|
||||
): ApiClient {
|
||||
let accessToken: string | null = null
|
||||
let refreshing: Promise<boolean> | null = null
|
||||
|
||||
async function refreshOnce(): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetchImpl(`${baseUrl}/auth/refresh`, { method: 'POST', credentials: 'include' })
|
||||
if (!res.ok) {
|
||||
accessToken = null
|
||||
return false
|
||||
}
|
||||
const body = (await res.json()) as { access_token: string }
|
||||
accessToken = body.access_token
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function refresh(): Promise<boolean> {
|
||||
refreshing ??= refreshOnce().finally(() => {
|
||||
refreshing = null
|
||||
})
|
||||
return refreshing
|
||||
}
|
||||
|
||||
function send(path: string, options: RequestOptions): Promise<Response> {
|
||||
const headers = new Headers()
|
||||
let body = options.body
|
||||
if (options.json !== undefined) {
|
||||
headers.set('content-type', 'application/json')
|
||||
body = JSON.stringify(options.json)
|
||||
}
|
||||
if (accessToken) headers.set('authorization', `Bearer ${accessToken}`)
|
||||
return fetchImpl(`${baseUrl}${path}`, {
|
||||
method: options.method ?? 'GET',
|
||||
headers,
|
||||
body,
|
||||
credentials: 'include',
|
||||
signal: options.signal,
|
||||
})
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
let res = await send(path, options)
|
||||
if (res.status === 401 && !path.startsWith('/auth/') && (await refresh())) {
|
||||
res = await send(path, options)
|
||||
}
|
||||
if (!res.ok) throw await toError(res)
|
||||
const text = await res.text()
|
||||
return (text ? JSON.parse(text) : undefined) as T
|
||||
}
|
||||
|
||||
return {
|
||||
request,
|
||||
refresh,
|
||||
setAccessToken: (token) => {
|
||||
accessToken = token
|
||||
},
|
||||
hasAccessToken: () => accessToken !== null,
|
||||
}
|
||||
}
|
||||
|
||||
export const api = createApiClient()
|
||||
22
frontend/src/shared/api/errors.ts
Normal file
22
frontend/src/shared/api/errors.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { ApiError } from './client'
|
||||
|
||||
const BY_STATUS: Record<number, string> = {
|
||||
400: 'Проверь введённые данные.',
|
||||
401: 'Нужно войти в аккаунт.',
|
||||
403: 'Недостаточно прав.',
|
||||
404: 'Не найдено.',
|
||||
409: 'Уже существует.',
|
||||
}
|
||||
|
||||
export function describeError(err: unknown, overrides: Partial<Record<number, string>> = {}): string {
|
||||
if (err instanceof ApiError) {
|
||||
if (err.status === 429) {
|
||||
return err.retryAfter
|
||||
? `Слишком много попыток. Подожди ${err.retryAfter} с.`
|
||||
: 'Слишком много попыток. Подожди немного.'
|
||||
}
|
||||
if (err.status >= 500) return 'Сервер не ответил. Попробуй через минуту.'
|
||||
return overrides[err.status] ?? BY_STATUS[err.status] ?? 'Проверь введённые данные.'
|
||||
}
|
||||
return 'Нет связи с сервером. Проверь интернет и попробуй ещё раз.'
|
||||
}
|
||||
82
frontend/src/shared/api/tests/client.test.ts
Normal file
82
frontend/src/shared/api/tests/client.test.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { expect, test } from 'vitest'
|
||||
import { ApiError, createApiClient } from '../client'
|
||||
import { describeError } from '../errors'
|
||||
import { json, mockFetch } from '../../../test/fetch'
|
||||
|
||||
test('sends json with bearer token and cookies', async () => {
|
||||
const fetch = mockFetch({ 'PUT /configs/1': () => json({ ok: true }) })
|
||||
const api = createApiClient()
|
||||
api.setAccessToken('tok')
|
||||
await api.request('/configs/1', { method: 'PUT', json: { a: 1 } })
|
||||
const [, init] = fetch.mock.calls[0]
|
||||
const headers = new Headers(init?.headers)
|
||||
expect(headers.get('authorization')).toBe('Bearer tok')
|
||||
expect(headers.get('content-type')).toBe('application/json')
|
||||
expect(init?.credentials).toBe('include')
|
||||
expect(init?.body).toBe('{"a":1}')
|
||||
})
|
||||
|
||||
test('401 triggers one refresh and one retry', async () => {
|
||||
let calls = 0
|
||||
const fetch = mockFetch({
|
||||
'GET /me': () => (++calls === 1 ? json({ error: 'unauthorized' }, 401) : json({ id: 'x' })),
|
||||
'POST /auth/refresh': () => json({ access_token: 'new' }),
|
||||
})
|
||||
const api = createApiClient()
|
||||
await expect(api.request('/me')).resolves.toEqual({ id: 'x' })
|
||||
expect(fetch.mock.calls.filter(([u]) => String(u).endsWith('/auth/refresh'))).toHaveLength(1)
|
||||
expect(new Headers(fetch.mock.calls[2][1]?.headers).get('authorization')).toBe('Bearer new')
|
||||
})
|
||||
|
||||
test('concurrent 401s share a single refresh', async () => {
|
||||
let refreshes = 0
|
||||
mockFetch({
|
||||
'GET /a': (init) => (new Headers(init.headers).get('authorization') ? json(1) : json({}, 401)),
|
||||
'GET /b': (init) => (new Headers(init.headers).get('authorization') ? json(2) : json({}, 401)),
|
||||
'POST /auth/refresh': () => {
|
||||
refreshes++
|
||||
return json({ access_token: 't' })
|
||||
},
|
||||
})
|
||||
const api = createApiClient()
|
||||
await Promise.all([api.request('/a'), api.request('/b')])
|
||||
expect(refreshes).toBe(1)
|
||||
})
|
||||
|
||||
test('failed refresh surfaces the original 401 and clears the token', async () => {
|
||||
mockFetch({
|
||||
'GET /me': () => json({ error: 'unauthorized' }, 401),
|
||||
'POST /auth/refresh': () => json({ error: 'unauthorized' }, 401),
|
||||
})
|
||||
const api = createApiClient()
|
||||
api.setAccessToken('stale')
|
||||
await expect(api.request('/me')).rejects.toMatchObject({ status: 401 })
|
||||
expect(api.hasAccessToken()).toBe(false)
|
||||
})
|
||||
|
||||
test('auth endpoints never trigger refresh', async () => {
|
||||
const fetch = mockFetch({ 'POST /auth/login': () => json({ error: 'unauthorized' }, 401) })
|
||||
await expect(createApiClient().request('/auth/login', { method: 'POST', json: {} })).rejects.toBeInstanceOf(
|
||||
ApiError,
|
||||
)
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('429 carries retry-after; 204 resolves undefined', async () => {
|
||||
mockFetch({
|
||||
'POST /auth/login': () => json({ error: 'too many requests' }, 429, { 'retry-after': '42' }),
|
||||
'DELETE /device/links/1': () => new Response(null, { status: 204 }),
|
||||
})
|
||||
const api = createApiClient()
|
||||
await expect(api.request('/auth/login', { method: 'POST' })).rejects.toMatchObject({ status: 429, retryAfter: 42 })
|
||||
await expect(api.request('/device/links/1', { method: 'DELETE' })).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
test('describeError covers 429, network failure and status defaults', () => {
|
||||
expect(describeError(new ApiError(429, 'x', 42))).toBe('Слишком много попыток. Подожди 42 с.')
|
||||
expect(describeError(new ApiError(429, 'x', null))).toBe('Слишком много попыток. Подожди немного.')
|
||||
expect(describeError(new TypeError('Failed to fetch'))).toBe(
|
||||
'Нет связи с сервером. Проверь интернет и попробуй ещё раз.',
|
||||
)
|
||||
expect(describeError(new ApiError(404, 'x'))).toBe('Не найдено.')
|
||||
})
|
||||
8
frontend/src/shared/types.ts
Normal file
8
frontend/src/shared/types.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
export type Me = {
|
||||
id: string
|
||||
email: string
|
||||
display_nick: string
|
||||
role: 'user' | 'admin'
|
||||
avatar_url: string | null
|
||||
created_at: string
|
||||
}
|
||||
28
frontend/src/shared/ui/Button.tsx
Normal file
28
frontend/src/shared/ui/Button.tsx
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import type { ButtonHTMLAttributes } from 'react'
|
||||
|
||||
type Variant = 'primary' | 'quiet' | 'danger'
|
||||
|
||||
const VARIANTS: Record<Variant, string> = {
|
||||
primary: 'bg-ice text-abyss hover:bg-ice/90',
|
||||
quiet: 'bg-transparent text-snow border border-shoal hover:border-frost',
|
||||
danger: 'bg-transparent text-ember border border-ember/60 hover:border-ember',
|
||||
}
|
||||
|
||||
export function Button({
|
||||
variant = 'primary',
|
||||
busy = false,
|
||||
disabled,
|
||||
className = '',
|
||||
type = 'button',
|
||||
...rest
|
||||
}: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: Variant; busy?: boolean }) {
|
||||
return (
|
||||
<button
|
||||
type={type}
|
||||
disabled={disabled || busy}
|
||||
aria-busy={busy || undefined}
|
||||
className={`inline-flex items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${VARIANTS[variant]} ${className}`}
|
||||
{...rest}
|
||||
/>
|
||||
)
|
||||
}
|
||||
10
frontend/src/shared/ui/Notice.tsx
Normal file
10
frontend/src/shared/ui/Notice.tsx
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import type { ReactNode } from 'react'
|
||||
|
||||
export function Notice({ tone, children }: { tone: 'info' | 'error'; children: ReactNode }) {
|
||||
const styles = tone === 'error' ? 'border-ember/60 text-ember' : 'border-shoal text-frost'
|
||||
return (
|
||||
<div role={tone === 'error' ? 'alert' : 'status'} className={`rounded-md border px-3 py-2 text-sm ${styles}`}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
29
frontend/src/shared/ui/ShareCode.tsx
Normal file
29
frontend/src/shared/ui/ShareCode.tsx
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { Button } from './Button'
|
||||
|
||||
export function ShareCode({ code, label }: { code: string; label?: string }) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
useEffect(() => {
|
||||
if (!copied) return
|
||||
const t = setTimeout(() => setCopied(false), 2000)
|
||||
return () => clearTimeout(t)
|
||||
}, [copied])
|
||||
|
||||
async function copy() {
|
||||
await navigator.clipboard.writeText(code)
|
||||
setCopied(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{label ? <span className="text-sm text-frost">{label}</span> : null}
|
||||
<code className="font-code text-lg tracking-widest text-ice">{code}</code>
|
||||
<Button variant="quiet" onClick={copy}>
|
||||
Скопировать
|
||||
</Button>
|
||||
<span aria-live="polite" className="text-sm text-frost">
|
||||
{copied ? 'Скопировано' : ''}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
35
frontend/src/shared/ui/TextField.tsx
Normal file
35
frontend/src/shared/ui/TextField.tsx
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { useId, type InputHTMLAttributes } from 'react'
|
||||
|
||||
export function TextField({
|
||||
label,
|
||||
error,
|
||||
hint,
|
||||
className = '',
|
||||
...rest
|
||||
}: InputHTMLAttributes<HTMLInputElement> & { label: string; error?: string; hint?: string }) {
|
||||
const id = useId()
|
||||
const describedBy = error ? `${id}-error` : hint ? `${id}-hint` : undefined
|
||||
return (
|
||||
<div className={`flex flex-col gap-1.5 ${className}`}>
|
||||
<label htmlFor={id} className="text-sm text-frost">
|
||||
{label}
|
||||
</label>
|
||||
<input
|
||||
id={id}
|
||||
aria-invalid={error ? true : undefined}
|
||||
aria-describedby={describedBy}
|
||||
className="rounded-md border border-shoal bg-abyss px-3 py-2 text-snow placeholder:text-frost/60 focus:border-ice aria-invalid:border-ember"
|
||||
{...rest}
|
||||
/>
|
||||
{error ? (
|
||||
<p id={`${id}-error`} className="text-sm text-ember">
|
||||
{error}
|
||||
</p>
|
||||
) : hint ? (
|
||||
<p id={`${id}-hint`} className="text-sm text-frost">
|
||||
{hint}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
36
frontend/src/shared/ui/tests/ui.test.tsx
Normal file
36
frontend/src/shared/ui/tests/ui.test.tsx
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { expect, test, vi } from 'vitest'
|
||||
import { Button } from '../Button'
|
||||
import { TextField } from '../TextField'
|
||||
import { ShareCode } from '../ShareCode'
|
||||
import { Notice } from '../Notice'
|
||||
|
||||
test('busy button is disabled and announces busy', () => {
|
||||
render(<Button busy>Сохранить</Button>)
|
||||
const b = screen.getByRole('button', { name: 'Сохранить' })
|
||||
expect(b).toBeDisabled()
|
||||
expect(b).toHaveAttribute('aria-busy', 'true')
|
||||
})
|
||||
|
||||
test('text field links label and error', () => {
|
||||
render(<TextField label="Почта" error="Введи почту" />)
|
||||
const input = screen.getByLabelText('Почта')
|
||||
expect(input).toHaveAttribute('aria-invalid', 'true')
|
||||
expect(input).toHaveAccessibleDescription('Введи почту')
|
||||
})
|
||||
|
||||
test('share code copies to clipboard and confirms', async () => {
|
||||
const user = userEvent.setup()
|
||||
const writeText = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue()
|
||||
render(<ShareCode code="7KQ3M9XA" />)
|
||||
expect(screen.getByText('7KQ3M9XA')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Скопировать' }))
|
||||
expect(writeText).toHaveBeenCalledWith('7KQ3M9XA')
|
||||
expect(await screen.findByText('Скопировано')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('error notice is an alert', () => {
|
||||
render(<Notice tone="error">Неверный код</Notice>)
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Неверный код')
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue