docs: refine frontend conventions and routing
Frontend security / security (push) Successful in 8s
Frontend verify / verify (push) Successful in 3m56s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 3m41s
Conventional commits / commits (pull_request) Successful in 19s
Frontend security / security (push) Successful in 8s
Frontend verify / verify (push) Successful in 3m56s
Frontend security / security (pull_request) Successful in 9s
Frontend verify / verify (pull_request) Successful in 3m41s
Conventional commits / commits (pull_request) Successful in 19s
This commit is contained in:
@@ -11,6 +11,11 @@ Mantine component и общую тему. Для выпадающего выбо
|
||||
ограничения JSDOM решай в test setup, сохраняя production UI.
|
||||
Семантический HTML для структуры страницы остаётся уместным.
|
||||
|
||||
Icons ищи у существующего owner (например,
|
||||
[BankOperationIcon](../../src/entities/bank-card/ui/BankOperationIcon.tsx));
|
||||
общая icon library сейчас не принята. Не добавляй пакет ради одного символа. Business/domain
|
||||
components живут у feature/entity/page, даже при повторном использовании.
|
||||
|
||||
Wrapper нужен для проектной ответственности, а не ради нового имени
|
||||
для Button. Локальный CSS module принадлежит component; общий token вводи для
|
||||
реально общей роли через [design system](../../../docs/design/overview.md).
|
||||
@@ -23,9 +28,11 @@ Wrapper нужен для проектной ответственности, а
|
||||
| Локальное открытие, focus, rendering fallback | React UI state |
|
||||
| Значение, вычисляемое из уже доступных inputs | Вычисление при render/в VM, без копирования через effect в state |
|
||||
|
||||
Effect нужен для синхронизации с внешней системой; действие пользователя
|
||||
обрабатывай в handler. Не добавляй store, memoization или abstraction без текущей
|
||||
потребности. Inspect ближайший component до создания нового pattern.
|
||||
State, который нужен в ссылке, back/forward или после navigation, хранится в URL
|
||||
через existing router search params. Остальной UI state остаётся у ближайшего
|
||||
owner. Shared client store нужен только нескольким consumers без подходящего
|
||||
общего owner; наличие двух компонентов само по себе его не требует.
|
||||
Hooks/effects/derived state — по [TypeScript/React](typescript-react.md#hooks-и-derived-state).
|
||||
|
||||
## Container, VM и view
|
||||
|
||||
@@ -76,71 +83,12 @@ Button loading при mutation и компактный cached-snapshot progress
|
||||
|
||||
## Код и components
|
||||
|
||||
Style/type automation задают configs. Используй `import type`; `enum` и
|
||||
`namespace` в frontend не применяются. Named components — const-valued; Biome
|
||||
проверяет declarations, no-default-export и exports-last в своём scope.
|
||||
|
||||
Обязательный review: `FC<Props>` и named props рядом/в types-файле; без inline
|
||||
props typing и destructuring в параметрах. Принимай `props`, destructure в body.
|
||||
Только children — `FC<PropsWithChildren>`; дополнительные props — named type
|
||||
на основе `PropsWithChildren<{ ... }>`. Без props — `FC`.
|
||||
Своди обычные exports к читаемому нижнему named block; barrel делает прямой
|
||||
re-export без промежуточного import.
|
||||
|
||||
CSF `*.stories.tsx` сохраняют default meta и прямые story exports для indexer.
|
||||
Vite/Vitest configs и `.storybook/main.ts`/`preview.tsx` имеют только
|
||||
конфигурационное default-export exception. Scope исключений принадлежит biome.json.
|
||||
Types, props, hooks и memoization — в [TypeScript/React](typescript-react.md).
|
||||
|
||||
## Domain literals and magic values
|
||||
|
||||
Finite business vocabulary must be modeled explicitly; incidental implementation
|
||||
literals stay inline. Это относится к error codes, statuses, operation/account/
|
||||
instrument/transaction types, permissions, roles, feature states и бизнес-режимам.
|
||||
|
||||
Перед новым определением найди existing owner/type/value. В branching и comparisons
|
||||
используй символическое значение владельца; не повторяй raw domain literals.
|
||||
Храни словарь у domain/module/entity с соблюдением границ слоёв, без глобальной
|
||||
свалки `constants.ts`. Сохраняй принятый pattern; для нового project-owned словаря
|
||||
без подходящего аналога используй `as const` с derived union:
|
||||
|
||||
```ts
|
||||
const BankErrorCode = {
|
||||
InvalidDate: "BANK_INVALID_DATE",
|
||||
ImmutableOperation: "BANK_IMMUTABLE_OPERATION",
|
||||
} as const;
|
||||
type BankErrorCode = (typeof BankErrorCode)[keyof typeof BankErrorCode];
|
||||
|
||||
// Вместо code === "BANK_INVALID_DATE":
|
||||
if (code === BankErrorCode.InvalidDate) { /* existing handling */ }
|
||||
```
|
||||
|
||||
Значимые numeric policies (timeout, retry, page size, threshold, coefficient)
|
||||
называй по смыслу и единицам: `REQUEST_TIMEOUT_MS`, `CACHE_TTL_SECONDS`,
|
||||
`MAX_RETRY_COUNT`, `PAGE_SIZE`. Оставляй inline UI labels в принятом месте,
|
||||
log messages, индексы, `index + 1`, `Math.max(value, 0)`, `page ?? 1`,
|
||||
`percentage * 100` и очевидные локальные детали без semantic benefit.
|
||||
При неясном owner/смысле оставь значение и укажи ограничение в review.
|
||||
|
||||
Не мигрируй корректные existing enum/union styles массово. Не добавляй ради
|
||||
правила factories, registries, schemas, loaders, abstraction layers, dependencies,
|
||||
custom lint/AST rules, generation/validation scripts или тесты существования
|
||||
констант. Semantic review проверяет ownership, единое написание и неизменность
|
||||
wire values; обычные behavior tests проверяют поведение.
|
||||
|
||||
Backend API vocabulary бери из generated OpenAPI types/client, runtime values —
|
||||
когда генератор их предоставляет. Не создавай ручную копию backend enum/object.
|
||||
Текущий `schema.d.ts` предоставляет только types: используй indexed-access type
|
||||
из `paths`; typed literals в запросах/сравнениях допустимы при отсутствии
|
||||
runtime values. `ProblemDetailsDto.code` сейчас `string`: не выдумывай закрытый
|
||||
frontend error enum. Развитие API source — отдельное contract-решение.
|
||||
Frontend `enum` по-прежнему запрещён локальным TS/style profile.
|
||||
|
||||
`noMagicNumbers` включён как error в Biome. Fixtures, tests и stories исключены
|
||||
из этого правила; остальные проверки для них сохраняются. Используй имена
|
||||
политик/единиц и existing values. Точечное подавление допустимо для очевидного
|
||||
incidental значения с объяснением, например перевода доли в проценты; не подавляй
|
||||
скрытые бизнес-лимиты. Semantic magic strings проверяются conventions/review: в
|
||||
установленном Biome нет такого встроенного правила, новый инструмент не добавляем.
|
||||
Правило и generated API exception — в
|
||||
[TypeScript/React](typescript-react.md#domain-literals-and-magic-values).
|
||||
|
||||
## Строки и валидация
|
||||
|
||||
@@ -154,5 +102,5 @@ incidental значения с объяснением, например пере
|
||||
|
||||
Type/style: `npm run typecheck`, `npm run lint`. Для risk behavior/изменения тестов
|
||||
используй [Testing](frontend-testing.md). UI: keyboard, narrow viewport,
|
||||
loading/error/empty/loaded и recovery по применимости. [Storybook](../../README.md#ui-каталог-storybook)
|
||||
уже установлен; используй его как reference, но сверяй UI с задачей отдельно от build.
|
||||
loading/error/empty/loaded и recovery по применимости. [Storybook](storybook.md) задаёт выбор stories и изоляцию каталога;
|
||||
сверяй UI с задачей отдельно от build.
|
||||
|
||||
Reference in New Issue
Block a user