LoVisual/frontend/ARCHITECTURE.md
loki5512344 7f4b532f99 chore(history): squash 67 commit(s) from 2026-09-25
- feat(accounts): persist device links with opaque hashed tokens, list and revoke endpoints
- feat(frontend): app shell, routing and landing page with the chat-command hero
- feat(frontend): Cyrillic-first fonts (Unbounded, Onest, JetBrains Mono); add i18next and motion
- docs: free mod, bilingual site, one-click download, theme editor, public profiles, rich landing in plans
- feat(accounts): internal gRPC AuthenticateDevice guarded by internal key
- feat(frontend): ru/en i18n with typed per-feature dictionaries and language switch
- feat(accounts): GET /me profile endpoint
- feat(gateway): scaffold crate with config validation and health check
- feat(gateway): reverse proxy to accounts and configs services
- feat(gateway): resolve identity once from access JWT or device token via gRPC
- feat(gateway): per-route and global rate limits with Retry-After
- feat(gateway): CORS for the site origin; docs for gateway and internal contract
- feat(configs): scaffold service with schema, config validation and health check
- feat(configs): four config slots per account with list, get and save
- feat(configs): permanent share codes with regenerate and public load-by-code
- feat(accounts): GetPublicProfiles gRPC for showcase author info
- style(accounts,common): apply rustfmt to existing sources
- feat(configs): public showcase with publish, browse, detail and copy-to-slot
- feat(backend): public profile endpoint and showcase author filter
- fix(gateway): silence clippy collapsible-if and needless-ref warnings
- docs(backend): configs-service implemented; Подсистема 1 backend complete
- feat(mod): add Optimize module skeleton with OptimizeState holder
- feat(mod): gate glass blur behind Optimize no_glass knob
- feat(mod): cut MotionBlur and DoF sample counts behind lite_post knob
- feat(mod): trim procedural sky noise behind lite_sky knob
- feat(mod): drop fade gradients and digit rolls behind lean_hud knob
- docs(todo): mark Optimize module phase 9.2 complete
- refactor(mod): drop dead Renderer2D compatibility shims
- refactor(mod): prune unreachable Renderer2D overload towers
- refactor(mod): remove unused Renderer2D overloads and imports
- docs(todo): mark Renderer2D giant-splitting done (2179 to 1597)
- refactor(mod): extract shader id constants from LoVisualRenderPipelines
- docs(todo): record registry wave 2026-09-25 (Renderer2D, pipelines)
- refactor(mod): move Renderer2D instance state into base class
- refactor(mod): extract Renderer2DRounded drawing family
- refactor(mod): extract Renderer2DPath connector and chamfer family
- refactor(mod): extract Renderer2DShapes circle line and texture primitives
- refactor(mod): extract Renderer2DGlass and Renderer2DItem families
- refactor(mod): prune Renderer2D imports after facade split
- docs(todo): record Renderer2D facade inheritance split (1597 to 475)
- docs: easter eggs — .env honeypot, konami troll mode, devtools banner, IDDQD config, breakable 404 block, 418 teapot
- feat(mod): introduce surface style system core (SurfaceStyle, StyleSpec, StyleConfig, SurfaceRenderer)
- refactor(mod): delegate HudRenderUtil liquid glass draws to SurfaceRenderer (dedupe glass constants)
- refactor(mod): route bespoke glass call sites through SurfaceRenderer.plateSpec
- feat(mod): add Auto option to HUD bg effects via shared HudBgStyles resolution
- feat(mod): flat fallback for no-glass optimize mode and persist global HUD config
- feat(mod): default HUD bg effects to Auto so the global surface style drives widgets
- feat(mod): add global cycle-style hotkey with surface style notification
- feat(mod): add surface style swatch strip under the global style picker
- feat(gateway): reject ambiguous paths and answer .env probes with a honeypot
- fix(gateway): charge failed credentials against the rate limit, allow stale ones on /auth
- feat(frontend): ClickGui theme pipeline generated from the mod, live site theming
- feat(frontend): landing v2 hero — voxel/particle backdrop, live ClickGui, theme strip
- docs(todo): drop the FPS A/B measurement from phase 9.3, close phase 9
- feat(gateway): answer /coffee with a 418 teapot
- feat(frontend): land the rest of landing v2 — HUD, module wall, showcase, FAQ, footer
- feat(frontend): one-click download from GitHub releases, changelog page, release CI
- feat(frontend): theme editor with live ClickGui preview, mod-compatible export and share links
- fix(frontend): landing HUD playground now shows real mod widgets (fps, coordinates, module list, keybinds, ping)
- style(frontend): apply ClickGui glass effect to landing HUD playground widgets
- fix(frontend): prevent color field row overflow in theme editor grid
- fix(frontend): never attach stale bearer token to /auth/* requests
- fix(configs): unpublish/publish can no longer bypass moderation
- refactor(accounts): shrink auth/handlers.rs under the 250-line cap
- fix(accounts): tolerate concurrent refresh without killing every session
- fix(gateway): minor hardening from the backend review
- feat(configs): IDDQD easter egg config
2026-09-25 20:22:13 +02:00

7.1 KiB
Raw Blame History

Frontend Architecture (продумано заранее, реализация — следующий план)

Статус: структура согласована до написания implementation-плана фронтенда, чтобы план сразу проектировался под правильные границы, а не переписывался после первого клубка спагетти. Стек: React + Vite + TypeScript + Tailwind (см. TODO.md, Фаза 10). Правила платформы (≤250 строк/файл и т.д.) — там же.

Принцип: структура по фичам, не по типу файла

Раскладывать src/ на /components, /hooks, /services, /types вперемешку — самая частая ошибка в React-проектах: одна фича размазывается по всему дереву папок, и её нельзя удалить или вынести, не задев остальное. Вместо этого — каждая фича владеет всем, что ей нужно, в одной папке.

frontend/src/
  features/
    auth/                    # регистрация/логин, device-link экран
      components/
      hooks/
      api.ts                 # вызовы к accounts-service через gateway
      types.ts
    configs/                 # 4 слота, share-коды, витрина
      components/
      hooks/
      api.ts
      types.ts
    avatars/
    admin/                   # /admin, видим только role=admin
  shared/                    # только то, что реально используют 2+ фичи
    components/              # кнопки, инпуты, модалки — дизайн-система
    hooks/                   # useAuth (общий контекст сессии), useDebounce и т.п.
    api/
      client.ts              # общий fetch-wrapper: base URL gateway, JWT в заголовке,
                              # обработка 401 (refresh) и 429 (rate-limit) в одном месте
    types.ts                 # общие DTO, если совпадают на нескольких фичах
    i18n/                    # LanguageSwitch, common.ru.ts / common.en.ts (typed dictionaries)
  pages/                     # роуты верхнего уровня, тонкие — просто собирают
                              # фичи в layout, никакой бизнес-логики
  app/                       # App.tsx, routes.tsx, i18n.ts (initI18n), i18next.d.ts (typed keys)
  main.tsx

Каждая фича, у которой есть строки для пользователя, также владеет своей i18n/ подпапкой (ru.ts, en.ts) — одно пространство имён i18next на фичу (auth, landing, ...), русские словари как источник (as const), английские типизированы через satisfies Translation<typeof ru> из shared/i18n/common.ru.ts, так что расхождение ключей — ошибка компиляции.

Правило раздела shared/feature: если код используется ровно в одной фиче — он живёт в этой фиче, а не в shared/. Переносить в shared/ только когда появился второй потребитель — не заранее "на всякий случай" (YAGNI).

Лимиты из правил платформы (TODO.md) действуют и тут: ≤250 строк на файл, ≤4 файла на папку (подпапки не считаются) — если в components/ внутри фичи появляется 5-й файл, выносим смысловую подпапку, а не копим.

Антипаттерны, которых сознательно избегаем

  • Barrel-файлы index.ts на каждую папку — удобны на вид, но ломают tree-shaking и IDE go-to-definition на больших проектах; экспортируем напрямую из файла, где определено
  • Prop drilling через 4+ уровня — если проп передаётся через компоненты, которым он сам не нужен (просто транзитом) — это сигнал на React Context (для auth-сессии) или на подъём компонента ниже по дереву, а не терпеть drilling
  • Бизнес-логика в pages/ — страницы только компонуют фичи и layout; если в файле страницы появляется fetch/сложная derived-логика — она переезжает в соответствующую фичу
  • Один гигантский api.ts на весь проект — обращения к API живут в папке своей фичи (features/configs/api.ts и т.д.), общий только low-level shared/api/client.ts (fetch-wrapper)
  • any вместо нормальных типов — DTO с бэкенда типизируются по контрактам из backend/PLAN.md (Task 6: RegisterResponse, LoginResponse и т.д.), не any/unknown без сужения

Тестирование

Тесты живут в подпапке tests/ внутри фичи (или shared/*), которую они проверяют — не рядом с файлом (Component.test.tsx) и не в отдельном дереве на верхнем уровне. Это всё ещё удаляется вместе с фичей при её удалении/ переносе, но не съедает бюджет "≤4 файла на папку" — колокация X.test.tsx рядом с X.tsx вдвое сокращала бы вместимость каждой папки под этим правилом.

frontend/src/
  features/
    auth/
      components/
      hooks/
      api.ts
      types.ts
      tests/
        api.test.ts
        components.test.tsx
  shared/
    ui/
      Button.tsx
      TextField.tsx
      tests/
        ui.test.tsx

Источники: Robin Wieruch — React Folder Structure Best Practices 2026, Mastering Modern React + Vite Folder Structure, Medium.

Единственное допустимое ребро shared → feature

shared/layout/ (шапка и каркас приложения) импортирует useSession из features/auth/session: шапке нужно знать, вошёл ли пользователь. Это единственный случай, когда shared/ зависит от фичи; остальной shared/ от фич не зависит.