sync
Some checks failed
CI/CD Pipeline / deploy (push) Blocked by required conditions
CI/CD Pipeline / docker (push) Failing after 12m36s

This commit is contained in:
2026-03-28 21:15:15 +03:00
parent a9f91dae29
commit b37eb75542
67 changed files with 1203 additions and 152 deletions

View File

@@ -73,7 +73,7 @@ jobs:
ssh -i ~/.ssh/deploy_key root@188.225.47.78 bash -s <<'SCRIPT'
set -e
IMAGE="${{ env.REGISTRY_IMAGE }}:latest"
CONTAINER="frontend-style-guide"
CONTAINER="nextjs-style-guide"
# Логин в реестр
echo '${{ secrets.CR_TOKEN }}' | docker login ${{ env.DOCKER_REGISTRY }} -u '${{ secrets.CR_USER }}' --password-stdin

7
.gitignore vendored
View File

@@ -129,4 +129,9 @@ dist
.yarn/install-state.gz
.pnp.*
.DS_Store
.DS_Store
# VitePress
.vitepress/cache
.vitepress/dist
docs/.vitepress

View File

@@ -1,25 +1,25 @@
{
"hash": "328a40d6",
"configHash": "755e8183",
"hash": "a12e5463",
"configHash": "dd9ed373",
"lockfileHash": "5778a81f",
"browserHash": "9485839a",
"browserHash": "2debf0f0",
"optimized": {
"vue": {
"src": "../../../node_modules/vue/dist/vue.runtime.esm-bundler.js",
"file": "vue.js",
"fileHash": "2c01c408",
"fileHash": "50b34fbf",
"needsInterop": false
},
"vitepress > @vue/devtools-api": {
"src": "../../../node_modules/@vue/devtools-api/dist/index.js",
"file": "vitepress___@vue_devtools-api.js",
"fileHash": "668fe053",
"fileHash": "ea163609",
"needsInterop": false
},
"vitepress > @vueuse/core": {
"src": "../../../node_modules/@vueuse/core/index.mjs",
"file": "vitepress___@vueuse_core.js",
"fileHash": "adb8a37f",
"fileHash": "2ef97fe2",
"needsInterop": false
}
},

View File

@@ -1,55 +1,117 @@
import { defineConfig } from 'vitepress';
const versions = Array.from({ length: 100 }, (_, i) => {
const major = Math.floor(i / 10) + 1;
const minor = i % 10;
return `v${major}.${minor}`;
}).reverse();
export default defineConfig({
lang: 'ru-RU',
title: 'Frontend Style Guide',
description: 'Правила и стандарты разработки фронтенд-проектов на React/NextJS и TypeScript',
themeConfig: {
siteTitle: 'Frontend Style Guide',
nav: [
{
text: versions[0],
items: versions.map((v) => ({
text: v,
link: `/${v}/`,
})),
},
],
sidebar: [
{
text: 'Базовые правила',
items: [
{ text: 'Технологии и библиотеки', link: '/parts/1-tech-stack' },
{ text: 'Архитектура', link: '/parts/2-architecture' },
{ text: 'Стиль кода', link: '/parts/3-code-style' },
{ text: 'Именование', link: '/parts/4-naming' },
{ text: 'Документирование', link: '/parts/5-documentation' },
{ text: 'Типизация', link: '/parts/6-typing' },
],
},
{
text: 'Прикладные разделы',
items: [
{ text: 'Структура проекта', link: '/parts/7-project-structure' },
{ text: 'Компоненты', link: '/parts/8-0-components' },
{ text: 'Шаблоны и генерация кода', link: '/parts/8-1-templates-generation' },
{ text: 'Стили', link: '/parts/9-styles' },
{ text: 'Изображения', link: '/parts/10-images-sprites' },
{ text: 'SVG-спрайты', link: '/parts/17-svg-sprites' },
{ text: 'Видео', link: '/parts/11-video' },
{ text: 'API', link: '/parts/12-api' },
{ text: 'Stores', link: '/parts/13-stores' },
{ text: 'Хуки', link: '/parts/14-hooks' },
{ text: 'Шрифты', link: '/parts/15-fonts' },
{ text: 'Локализация', link: '/parts/16-localization' },
],
},
const ruSidebar = [
{
text: 'Workflow',
items: [
{ text: 'Начало работы', link: '/workflow/getting-started' },
{ text: 'Создание приложения', link: '/workflow/creating-app' },
{ text: 'Создание страниц', link: '/workflow/creating-pages' },
{ text: 'Создание компонентов', link: '/workflow/creating-components' },
{ text: 'Стилизация', link: '/workflow/styling' },
{ text: 'Работа с данными', link: '/workflow/data-fetching' },
{ text: 'Управление состоянием', link: '/workflow/state-management' },
{ text: 'Локализация', link: '/workflow/localization' },
],
},
});
{
text: 'Базовые правила',
items: [
{ text: 'Технологии и библиотеки', link: '/basics/tech-stack' },
{ text: 'Архитектура', link: '/basics/architecture' },
{ text: 'Стиль кода', link: '/basics/code-style' },
{ text: 'Именование', link: '/basics/naming' },
{ text: 'Документирование', link: '/basics/documentation' },
{ text: 'Типизация', link: '/basics/typing' },
],
},
{
text: 'Прикладные разделы',
items: [
{ text: 'Структура проекта', link: '/applied/project-structure' },
{ text: 'Компоненты', link: '/applied/components' },
{ text: 'Шаблоны и генерация кода', link: '/applied/templates-generation' },
{ text: 'Стили', link: '/applied/styles' },
{ text: 'Изображения', link: '/applied/images-sprites' },
{ text: 'SVG-спрайты', link: '/applied/svg-sprites' },
{ text: 'Видео', link: '/applied/video' },
{ text: 'API', link: '/applied/api' },
{ text: 'Stores', link: '/applied/stores' },
{ text: 'Хуки', link: '/applied/hooks' },
{ text: 'Шрифты', link: '/applied/fonts' },
{ text: 'Локализация', link: '/applied/localization' },
],
},
];
const enSidebar = [
{
text: 'Processes',
items: [
{ text: 'Getting Started', link: '/en/workflow/getting-started' },
{ text: 'Creating an App', link: '/en/workflow/creating-app' },
{ text: 'Creating Pages', link: '/en/workflow/creating-pages' },
{ text: 'Creating Components', link: '/en/workflow/creating-components' },
{ text: 'Styling', link: '/en/workflow/styling' },
{ text: 'Data Fetching', link: '/en/workflow/data-fetching' },
{ text: 'State Management', link: '/en/workflow/state-management' },
{ text: 'Localization', link: '/en/workflow/localization' },
],
},
{
text: 'Basic Rules',
items: [
{ text: 'Tech Stack', link: '/en/basics/tech-stack' },
{ text: 'Architecture', link: '/en/basics/architecture' },
{ text: 'Code Style', link: '/en/basics/code-style' },
{ text: 'Naming', link: '/en/basics/naming' },
{ text: 'Documentation', link: '/en/basics/documentation' },
{ text: 'Typing', link: '/en/basics/typing' },
],
},
{
text: 'Applied Sections',
items: [
{ text: 'Project Structure', link: '/en/applied/project-structure' },
{ text: 'Components', link: '/en/applied/components' },
{ text: 'Templates & Code Generation', link: '/en/applied/templates-generation' },
{ text: 'Styles', link: '/en/applied/styles' },
{ text: 'Images', link: '/en/applied/images-sprites' },
{ text: 'SVG Sprites', link: '/en/applied/svg-sprites' },
{ text: 'Video', link: '/en/applied/video' },
{ text: 'API', link: '/en/applied/api' },
{ text: 'Stores', link: '/en/applied/stores' },
{ text: 'Hooks', link: '/en/applied/hooks' },
{ text: 'Fonts', link: '/en/applied/fonts' },
{ text: 'Localization', link: '/en/applied/localization' },
],
},
];
export default defineConfig({
srcDir: 'docs',
title: 'NextJS Style Guide',
description: 'Правила и стандарты разработки на NextJS и TypeScript',
rewrites: {
'ru/:rest*': ':rest*',
},
locales: {
root: {
label: 'Русский',
lang: 'ru-RU',
themeConfig: {
sidebar: ruSidebar,
},
},
en: {
label: 'English',
lang: 'en-US',
link: '/en/',
themeConfig: {
sidebar: enSidebar,
},
},
},
});

View File

@@ -1,3 +1,8 @@
.VPNavBarTitle.has-sidebar .title {
border-top: none !important;
padding-top: 0;
}
.VPNavBarTitle .title {
white-space: normal;
line-height: 1.2;

View File

@@ -1,13 +1,56 @@
# Frontend Style Guide для проектов на React/Next.js и TypeScript
# NextJS Style Guide
Это набор правил и практик для разработки фронтенд-проектов: архитектура, типизация, стили, компоненты, API и инфраструктурные разделы.
Rules and standards for NextJS and TypeScript development: architecture, typing, styles, components, API, and infrastructure.
## Как пользоваться
## Documentation Structure
- Начните с «Технологии и библиотеки», чтобы понимать базовые допущения.
- Затем прочитайте разделы из «Базовых правил».
- При реализации используйте соответствующие прикладные разделы.
### Processes
## Для ассистентов
**What to do** in a specific situation — step-by-step instructions.
Полная документация в одном MD файле: https://gromlab.ru/docs/frontend-style-guide/raw/branch/main/RULES.md
| Section | Answers the question |
|---------|---------------------|
| Getting Started | What tools to install before starting development? |
| Creating an App | How to create a new project, where to get a template? |
| Creating Pages | How to add a page: routing and screen? |
| Creating Components | How to generate components using templates? |
| Styling | What to use: Mantine, tokens, or PostCSS? |
| Data Fetching | How to fetch data: SWR, codegen, sockets? |
| State Management | When and how to create a store (Zustand)? |
| Localization | How to add translations and work with i18next? |
### Basic Rules
**What the code should look like** — standards not tied to a specific technology.
| Section | Answers the question |
|---------|---------------------|
| Tech Stack | What stack do we use? |
| Architecture | How are FSD layers, dependencies, and public API structured? |
| Code Style | How to format code: indentation, quotes, imports, early return? |
| Naming | How to name files, variables, components, hooks? |
| Documentation | How to write JSDoc: what to document and what not? |
| Typing | How to type: type vs interface, any/unknown, FC? |
### Applied Sections
**How a specific area works** — rules, structure, and code examples for specific technologies and tools.
| Section | Answers the question |
|---------|---------------------|
| Project Structure | How are folders and files organized by FSD? |
| Components | How is a component structured: files, props, clsx, FC? |
| Templates & Code Generation | How do templates work: syntax, variables, modifiers? |
| Styles | How to write CSS: PostCSS Modules, nesting, media, tokens? |
| Images | _(not filled)_ |
| SVG Sprites | _(not filled)_ |
| Video | _(not filled)_ |
| API | _(not filled)_ |
| Stores | _(not filled)_ |
| Hooks | _(not filled)_ |
| Fonts | _(not filled)_ |
| Localization | _(not filled)_ |
## For Assistants
Full documentation in a single MD file: https://gromlab.ru/docs/frontend-style-guide/raw/branch/main/generated/en/RULES.md

57
README_RU.md Normal file
View File

@@ -0,0 +1,57 @@
# NextJS Style Guide
Правила и стандарты разработки на NextJS и TypeScript: архитектура, типизация, стили, компоненты, API и инфраструктурные разделы.
## Для ассистентов
Полная документация в одном MD файле: https://gromlab.ru/docs/frontend-style-guide/raw/branch/main/generated/ru/RULES.md
## Структура документации
### Workflow
**Что делать** в конкретной ситуации — пошаговые инструкции.
| Раздел | Отвечает на вопрос |
|--------|-------------------|
| Начало работы | Какие инструменты установить перед началом разработки? |
| Создание приложения | Как создать новый проект, откуда взять шаблон? |
| Создание страниц | Как добавить страницу: роутинг и экран? |
| Создание компонентов | Как генерировать компоненты через шаблоны? |
| Стилизация | Чем стилизовать: Mantine, токены или PostCSS? |
| Работа с данными | Как получать данные: SWR, кодген, сокеты? |
| Управление состоянием | Когда и как создавать стор (Zustand)? |
| Локализация | Как добавлять переводы и работать с i18next? |
### Базовые правила
**Каким должен быть код** — стандарты, не привязанные к конкретной технологии.
| Раздел | Отвечает на вопрос |
|--------|-------------------|
| Технологии и библиотеки | Какой стек используем? |
| Архитектура | Как устроены слои FSD, зависимости, публичный API? |
| Стиль кода | Как оформлять код: отступы, кавычки, импорты, early return? |
| Именование | Как называть файлы, переменные, компоненты, хуки? |
| Документирование | Как писать JSDoc: что документировать, а что нет? |
| Типизация | Как типизировать: type vs interface, any/unknown, FC? |
### Прикладные разделы
**Как устроена конкретная область** — правила, структура и примеры кода для отдельных технологий и инструментов.
| Раздел | Отвечает на вопрос |
|--------|-------------------|
| Структура проекта | Как организованы папки и файлы по FSD? |
| Компоненты | Как устроен компонент: файлы, пропсы, clsx, FC? |
| Шаблоны и генерация | Как работают шаблоны: синтаксис, переменные, модификаторы? |
| Стили | Как писать CSS: PostCSS Modules, вложенность, медиа, токены? |
| Изображения | _(не заполнен)_ |
| SVG-спрайты | _(не заполнен)_ |
| Видео | _(не заполнен)_ |
| API | _(не заполнен)_ |
| Stores | _(не заполнен)_ |
| Хуки | _(не заполнен)_ |
| Шрифты | _(не заполнен)_ |
| Локализация | _(не заполнен)_ |

View File

@@ -1,23 +1,88 @@
import concatMd, { concatMdSync } from "concat-md";
import { concatMdSync } from "concat-md";
import path from "path";
import fs from "fs";
const resultMd = concatMdSync("./parts", {
toc: false,
sorter: (a, b) => {
// Извлекаем номер из начала имени файла (например, "1" из "1-assistent.md")
const getNumber = (filename) => {
const match = filename.match(/^(\d+)/);
return match ? parseInt(match[1], 10) : 0;
};
// Сортировка по возрастанию (1, 2, 3...)
return getNumber(a) - getNumber(b);
// Явный порядок файлов внутри каждого языка
const fileOrder = [
// index
"index.md",
// workflow
"workflow/getting-started.md",
"workflow/creating-app.md",
"workflow/creating-pages.md",
"workflow/creating-components.md",
"workflow/styling.md",
"workflow/data-fetching.md",
"workflow/state-management.md",
"workflow/localization.md",
// basics
"basics/tech-stack.md",
"basics/architecture.md",
"basics/code-style.md",
"basics/naming.md",
"basics/documentation.md",
"basics/typing.md",
// applied
"applied/project-structure.md",
"applied/components.md",
"applied/templates-generation.md",
"applied/styles.md",
"applied/images-sprites.md",
"applied/svg-sprites.md",
"applied/video.md",
"applied/api.md",
"applied/stores.md",
"applied/hooks.md",
"applied/fonts.md",
"applied/localization.md",
];
const buildRules = (lang) => {
const srcDir = `./docs/${lang}`;
const outDir = `./generated/${lang}`;
const outFile = path.join(outDir, "RULES.md");
if (!fs.existsSync(srcDir)) {
console.log(`Пропуск ${lang}: папка ${srcDir} не найдена`);
return;
}
});
// Записываем результат в файл RULES.md в корне проекта
const outputPath = path.join("./", "RULES.md");
fs.writeFileSync(outputPath, resultMd, "utf8");
fs.mkdirSync(outDir, { recursive: true });
console.log(`Файл RULES.md успешно создан: ${outputPath}`);
const resultMd = concatMdSync(srcDir, {
toc: false,
sorter: (a, b) => {
const indexA = fileOrder.indexOf(a);
const indexB = fileOrder.indexOf(b);
const posA = indexA === -1 ? fileOrder.length : indexA;
const posB = indexB === -1 ? fileOrder.length : indexB;
return posA - posB;
},
});
fs.writeFileSync(outFile, resultMd, "utf8");
console.log(`RULES.md (${lang}) создан: ${outFile}`);
};
// Собираем RULES.md для обоих языков
buildRules("ru");
buildRules("en");
// Генерируем README из index.md
const buildReadme = (lang, outFile) => {
const indexPath = `./docs/${lang}/index.md`;
if (!fs.existsSync(indexPath)) {
console.log(`Пропуск README (${lang}): ${indexPath} не найден`);
return;
}
const content = fs.readFileSync(indexPath, "utf8")
.replace(/^---[\s\S]*?---\n*/m, "");
fs.writeFileSync(outFile, content, "utf8");
console.log(`${outFile} создан из ${indexPath}`);
};
buildReadme("en", "./README.md");
buildReadme("ru", "./README_RU.md");

5
docs/en/applied/api.md Normal file
View File

@@ -0,0 +1,5 @@
---
title: API
---
# API

View File

@@ -0,0 +1,7 @@
---
title: Components
---
# Components
Rules for creating UI components across all FSD layers.

5
docs/en/applied/fonts.md Normal file
View File

@@ -0,0 +1,5 @@
---
title: Fonts
---
# Fonts

5
docs/en/applied/hooks.md Normal file
View File

@@ -0,0 +1,5 @@
---
title: Hooks
---
# Hooks

View File

@@ -0,0 +1,5 @@
---
title: Images
---
# Images

View File

@@ -0,0 +1,5 @@
---
title: Localization
---
# Localization

View File

@@ -0,0 +1,7 @@
---
title: Project Structure
---
# Project Structure
Base project structure and principles of module organization at folder and file level.

View File

@@ -0,0 +1,5 @@
---
title: Stores
---
# Stores

View File

@@ -0,0 +1,7 @@
---
title: Styles
---
# Styles
CSS writing rules: PostCSS Modules, nesting, media queries, variables, formatting.

View File

@@ -0,0 +1,5 @@
---
title: SVG Sprites
---
# SVG Sprites

View File

@@ -0,0 +1,7 @@
---
title: Templates & Code Generation
---
# Templates & Code Generation
Template tools, syntax, and examples for code generation.

5
docs/en/applied/video.md Normal file
View File

@@ -0,0 +1,5 @@
---
title: Video
---
# Video

View File

@@ -0,0 +1,7 @@
---
title: Architecture
---
# Architecture
Architecture based on FSD (Feature-Sliced Design) and strict module boundaries.

View File

@@ -0,0 +1,7 @@
---
title: Code Style
---
# Code Style
Unified code formatting rules: indentation, line breaks, quotes, import order, and readability.

View File

@@ -0,0 +1,7 @@
---
title: Documentation
---
# Documentation
Documentation should help understand the purpose of an entity, not duplicate its types or obvious details.

7
docs/en/basics/naming.md Normal file
View File

@@ -0,0 +1,7 @@
---
title: Naming
---
# Naming
Naming should be predictable, concise, and reflect the meaning of the entity.

View File

@@ -0,0 +1,7 @@
---
title: Tech Stack
---
# Tech Stack
Base technology stack and libraries used in projects.

7
docs/en/basics/typing.md Normal file
View File

@@ -0,0 +1,7 @@
---
title: Typing
---
# Typing
Typing is required for all public interfaces, functions, and components.

56
docs/en/index.md Normal file
View File

@@ -0,0 +1,56 @@
# NextJS Style Guide
Rules and standards for NextJS and TypeScript development: architecture, typing, styles, components, API, and infrastructure.
## Documentation Structure
### Processes
**What to do** in a specific situation — step-by-step instructions.
| Section | Answers the question |
|---------|---------------------|
| Getting Started | What tools to install before starting development? |
| Creating an App | How to create a new project, where to get a template? |
| Creating Pages | How to add a page: routing and screen? |
| Creating Components | How to generate components using templates? |
| Styling | What to use: Mantine, tokens, or PostCSS? |
| Data Fetching | How to fetch data: SWR, codegen, sockets? |
| State Management | When and how to create a store (Zustand)? |
| Localization | How to add translations and work with i18next? |
### Basic Rules
**What the code should look like** — standards not tied to a specific technology.
| Section | Answers the question |
|---------|---------------------|
| Tech Stack | What stack do we use? |
| Architecture | How are FSD layers, dependencies, and public API structured? |
| Code Style | How to format code: indentation, quotes, imports, early return? |
| Naming | How to name files, variables, components, hooks? |
| Documentation | How to write JSDoc: what to document and what not? |
| Typing | How to type: type vs interface, any/unknown, FC? |
### Applied Sections
**How a specific area works** — rules, structure, and code examples for specific technologies and tools.
| Section | Answers the question |
|---------|---------------------|
| Project Structure | How are folders and files organized by FSD? |
| Components | How is a component structured: files, props, clsx, FC? |
| Templates & Code Generation | How do templates work: syntax, variables, modifiers? |
| Styles | How to write CSS: PostCSS Modules, nesting, media, tokens? |
| Images | _(not filled)_ |
| SVG Sprites | _(not filled)_ |
| Video | _(not filled)_ |
| API | _(not filled)_ |
| Stores | _(not filled)_ |
| Hooks | _(not filled)_ |
| Fonts | _(not filled)_ |
| Localization | _(not filled)_ |
## For Assistants
Full documentation in a single MD file: https://gromlab.ru/docs/frontend-style-guide/raw/branch/main/generated/en/RULES.md

View File

@@ -0,0 +1,7 @@
---
title: Creating an App
---
# Creating an App
How to create a new application: choosing a project template and initialization.

View File

@@ -0,0 +1,7 @@
---
title: Creating Components
---
# Creating Components
Generating components using templates, working with child components.

View File

@@ -0,0 +1,7 @@
---
title: Creating Pages
---
# Creating Pages
Page creation pattern: routing (page.tsx) and screen.

View File

@@ -0,0 +1,7 @@
---
title: Data Fetching
---
# Data Fetching
How to fetch data: SWR, API client codegen, sockets.

View File

@@ -0,0 +1,7 @@
---
title: Getting Started
---
# Getting Started
Setting up the environment and installing tools before starting development.

View File

@@ -0,0 +1,7 @@
---
title: Localization
---
# Localization
How to add translations and work with i18next.

View File

@@ -0,0 +1,7 @@
---
title: State Management
---
# State Management
When and how to create a store (Zustand), what to store locally vs globally.

View File

@@ -0,0 +1,7 @@
---
title: Styling
---
# Styling
Styling tools priority and rules for their application.

View File

@@ -78,9 +78,9 @@ export { Container } from './container.ui'
## Шаблоны и генерация кода
Генерация нужна, чтобы быстро создавать компоненты с единым каркасом и не допускать расхождений в структуре. Это даёт одинаковые папки и имена файлов, уменьшает ручные ошибки и ускоряет старт работы.
Создание компонентов — **только через шаблоны**. Ручное создание файловой структуры компонента запрещено. Это обеспечивает единообразие каркаса, одинаковые папки и имена файлов, уменьшает ручные ошибки и ускоряет старт работы.
Используйте **@gromlab/create** для создания базового шаблона компонента. После генерации проверьте название компонента/файлов и заполните описание назначения.
После генерации через **@gromlab/create** проверить название компонента/файлов и заполнить описание назначения. Подробный порядок действий и перечень обязательных шаблонов — в разделе «Workflow».
## Вложенные (дочерние) компоненты

View File

@@ -6,9 +6,23 @@ title: Стили
Раздел описывает правила написания CSS: PostCSS Modules, вложенность, медиа-запросы, переменные, форматирование.
## Приоритет стилизации
Приоритет инструментов стилизации (от высшего к низшему):
1. **Mantine-компоненты и их пропсы** — в первую очередь использовать встроенные возможности Mantine.
2. **Глобальные CSS-токены** (`--color-*`, `--space-*`, `--radius-*`) — для значений, которые не покрываются Mantine.
3. **PostCSS Module файлы** — когда Mantine не покрывает задачу и нужна кастомная стилизация.
- Инлайн-стили в компонентах запрещены.
- Произвольные магические значения цветов, отступов и скруглений запрещены — использовать токены.
- Глобальные стили вне `app/styles/` запрещены.
Подробный порядок действий — в разделе «Workflow».
## Общие правила
- Только **PostCSS** и **CSS Modules** для стилизации.
- Только **PostCSS** и **CSS Modules** для кастомной стилизации.
- Подход **Mobile First** — стили пишутся от мобильных к десктопу.
- Именование классов — `camelCase` (`.root`, `.buttonNext`, `.itemTitle`).
- Модификаторы — отдельный класс с `_`, применяется через `&._modifier`.

View File

@@ -4,12 +4,18 @@ title: Шаблоны генерации кода
# Шаблоны генерации кода
Подход к использованию шаблонов и генерации кода для стандартизации структуры и ускорения разработки.
Раздел описывает инструменты, синтаксис шаблонов и примеры. Порядок действий при создании модулей и перечень обязательных шаблонов — в разделе «Workflow».
## Обязательность
- Создание типовых модулей — **только через шаблоны**. Ручное создание файловой структуры модуля запрещено, если для него существует шаблон.
- Перед созданием нового модуля — проверить наличие подходящего шаблона в `.templates/`.
- Если подходящего шаблона нет — сначала создать шаблон, затем использовать его.
## Что генерируем
- Компоненты (`screens`, `layouts`, `widgets`, `features`, `entities`).
- Страницы (nextjs `app`, `pages`)
- Страницы (nextjs `app`, `pages`).
- Типовые инфраструктурные модули (например, `store`).
## Чем генерируем
@@ -88,7 +94,7 @@ export const {{name.pascalCase}} = () => {
## Шаблон компонента
Рекомендуемая структура компонента, создаётся генератором по шаблону.
Структура компонента по шаблону. Создаётся генератором автоматически.
```ts
// .templates/component/index.ts

57
docs/ru/index.md Normal file
View File

@@ -0,0 +1,57 @@
# NextJS Style Guide
Правила и стандарты разработки на NextJS и TypeScript: архитектура, типизация, стили, компоненты, API и инфраструктурные разделы.
## Для ассистентов
Полная документация в одном MD файле: https://gromlab.ru/docs/frontend-style-guide/raw/branch/main/generated/ru/RULES.md
## Структура документации
### Workflow
**Что делать** в конкретной ситуации — пошаговые инструкции.
| Раздел | Отвечает на вопрос |
|--------|-------------------|
| Начало работы | Какие инструменты установить перед началом разработки? |
| Создание приложения | Как создать новый проект, откуда взять шаблон? |
| Создание страниц | Как добавить страницу: роутинг и экран? |
| Создание компонентов | Как генерировать компоненты через шаблоны? |
| Стилизация | Чем стилизовать: Mantine, токены или PostCSS? |
| Работа с данными | Как получать данные: SWR, кодген, сокеты? |
| Управление состоянием | Когда и как создавать стор (Zustand)? |
| Локализация | Как добавлять переводы и работать с i18next? |
### Базовые правила
**Каким должен быть код** — стандарты, не привязанные к конкретной технологии.
| Раздел | Отвечает на вопрос |
|--------|-------------------|
| Технологии и библиотеки | Какой стек используем? |
| Архитектура | Как устроены слои FSD, зависимости, публичный API? |
| Стиль кода | Как оформлять код: отступы, кавычки, импорты, early return? |
| Именование | Как называть файлы, переменные, компоненты, хуки? |
| Документирование | Как писать JSDoc: что документировать, а что нет? |
| Типизация | Как типизировать: type vs interface, any/unknown, FC? |
### Прикладные разделы
**Как устроена конкретная область** — правила, структура и примеры кода для отдельных технологий и инструментов.
| Раздел | Отвечает на вопрос |
|--------|-------------------|
| Структура проекта | Как организованы папки и файлы по FSD? |
| Компоненты | Как устроен компонент: файлы, пропсы, clsx, FC? |
| Шаблоны и генерация | Как работают шаблоны: синтаксис, переменные, модификаторы? |
| Стили | Как писать CSS: PostCSS Modules, вложенность, медиа, токены? |
| Изображения | _(не заполнен)_ |
| SVG-спрайты | _(не заполнен)_ |
| Видео | _(не заполнен)_ |
| API | _(не заполнен)_ |
| Stores | _(не заполнен)_ |
| Хуки | _(не заполнен)_ |
| Шрифты | _(не заполнен)_ |
| Локализация | _(не заполнен)_ |

View File

@@ -0,0 +1,7 @@
---
title: Создание приложения
---
# Создание приложения
Как создать новое приложение: выбор шаблона проекта и инициализация.

View File

@@ -0,0 +1,7 @@
---
title: Создание компонентов
---
# Создание компонентов
Генерация компонентов через шаблоны, работа с дочерними компонентами.

View File

@@ -0,0 +1,7 @@
---
title: Создание страниц
---
# Создание страниц
Паттерн создания страниц: роутинг (page.tsx) и экран (screen).

View File

@@ -0,0 +1,7 @@
---
title: Работа с данными
---
# Работа с данными
Как получать данные: SWR, кодген API-клиентов, сокеты.

View File

@@ -0,0 +1,66 @@
---
title: Начало работы
---
# Начало работы
Что нужно установить и настроить перед началом разработки.
## Генерация кода
AI-ассистент создаёт компоненты, страницы и другие модули из шаблонов проекта через CLI. Установить глобально:
```bash
npm i -g @gromlab/create
```
Подробнее: [@gromlab/create](https://www.npmjs.com/package/@gromlab/create)
## VS Code
#### Расширения
Каждый проект должен содержать файл `.vscode/extensions.json` — VS Code автоматически предложит установить нужные расширения при открытии проекта.
```json
// .vscode/extensions.json
{
"recommendations": [
"biomejs.biome",
"MyTemplateGenerator.mytemplategenerator",
"csstools.postcss"
]
}
```
| Расширение | Назначение |
|-----------|-----------|
| [MyTemplateGenerator](https://open-vsx.org/extension/MyTemplateGenerator/mytemplategenerator) | Генерация файлов и папок из шаблонов через UI |
| [Biome](https://marketplace.visualstudio.com/items?itemName=biomejs.biome) | Линтинг и форматирование кода |
| [PostCSS Language Support](https://marketplace.visualstudio.com/items?itemName=csstools.postcss) | Подсветка и автодополнение PostCSS |
#### Настройки
Каждый проект должен содержать файл `.vscode/settings.json` с базовой конфигурацией редактора.
```json
// .vscode/settings.json
{
"editor.defaultFormatter": "biomejs.biome",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"quickfix.biome": "explicit",
"source.organizeImports.biome": "explicit"
},
"files.associations": {
"*.css": "postcss"
}
}
```
| Настройка | Что делает |
|-----------|-----------|
| `editor.defaultFormatter` | Biome как форматтер по умолчанию |
| `editor.formatOnSave` | Автоформатирование при сохранении |
| `codeActionsOnSave` | Автофикс и сортировка импортов при сохранении |
| `files.associations` | CSS-файлы открываются с подсветкой PostCSS |

View File

@@ -0,0 +1,7 @@
---
title: Локализация
---
# Локализация
Как добавлять переводы и работать с i18next.

View File

@@ -0,0 +1,7 @@
---
title: Управление состоянием
---
# Управление состоянием
Когда и как создавать стор (Zustand), что хранить локально и глобально.

View File

@@ -0,0 +1,7 @@
---
title: Стилизация
---
# Стилизация
Приоритет инструментов стилизации и правила их применения.

225
generated/en/RULES.md Normal file
View File

@@ -0,0 +1,225 @@
<a name="indexmd"></a>
# NextJS Style Guide
Rules and standards for NextJS and TypeScript development: architecture, typing, styles, components, API, and infrastructure.
## Documentation Structure
### Processes
**What to do** in a specific situation — step-by-step instructions.
| Section | Answers the question |
|---------|---------------------|
| Getting Started | What tools to install before starting development? |
| Creating an App | How to create a new project, where to get a template? |
| Creating Pages | How to add a page: routing and screen? |
| Creating Components | How to generate components using templates? |
| Styling | What to use: Mantine, tokens, or PostCSS? |
| Data Fetching | How to fetch data: SWR, codegen, sockets? |
| State Management | When and how to create a store (Zustand)? |
| Localization | How to add translations and work with i18next? |
### Basic Rules
**What the code should look like** — standards not tied to a specific technology.
| Section | Answers the question |
|---------|---------------------|
| Tech Stack | What stack do we use? |
| Architecture | How are FSD layers, dependencies, and public API structured? |
| Code Style | How to format code: indentation, quotes, imports, early return? |
| Naming | How to name files, variables, components, hooks? |
| Documentation | How to write JSDoc: what to document and what not? |
| Typing | How to type: type vs interface, any/unknown, FC? |
### Applied Sections
**How a specific area works** — rules, structure, and code examples for specific technologies and tools.
| Section | Answers the question |
|---------|---------------------|
| Project Structure | How are folders and files organized by FSD? |
| Components | How is a component structured: files, props, clsx, FC? |
| Templates & Code Generation | How do templates work: syntax, variables, modifiers? |
| Styles | How to write CSS: PostCSS Modules, nesting, media, tokens? |
| Images | _(not filled)_ |
| SVG Sprites | _(not filled)_ |
| Video | _(not filled)_ |
| API | _(not filled)_ |
| Stores | _(not filled)_ |
| Hooks | _(not filled)_ |
| Fonts | _(not filled)_ |
| Localization | _(not filled)_ |
## For Assistants
Full documentation in a single MD file: https://gromlab.ru/docs/frontend-style-guide/raw/branch/main/generated/en/RULES.md
<a name="workflowgetting-startedmd"></a>
# Getting Started
Setting up the environment and installing tools before starting development.
<a name="workflowcreating-appmd"></a>
# Creating an App
How to create a new application: choosing a project template and initialization.
<a name="workflowcreating-pagesmd"></a>
# Creating Pages
Page creation pattern: routing (page.tsx) and screen.
<a name="workflowcreating-componentsmd"></a>
# Creating Components
Generating components using templates, working with child components.
<a name="workflowstylingmd"></a>
# Styling
Styling tools priority and rules for their application.
<a name="workflowdata-fetchingmd"></a>
# Data Fetching
How to fetch data: SWR, API client codegen, sockets.
<a name="workflowstate-managementmd"></a>
# State Management
When and how to create a store (Zustand), what to store locally vs globally.
<a name="workflowlocalizationmd"></a>
# Localization
How to add translations and work with i18next.
<a name="basicstech-stackmd"></a>
# Tech Stack
Base technology stack and libraries used in projects.
<a name="basicsarchitecturemd"></a>
# Architecture
Architecture based on FSD (Feature-Sliced Design) and strict module boundaries.
<a name="basicscode-stylemd"></a>
# Code Style
Unified code formatting rules: indentation, line breaks, quotes, import order, and readability.
<a name="basicsnamingmd"></a>
# Naming
Naming should be predictable, concise, and reflect the meaning of the entity.
<a name="basicsdocumentationmd"></a>
# Documentation
Documentation should help understand the purpose of an entity, not duplicate its types or obvious details.
<a name="basicstypingmd"></a>
# Typing
Typing is required for all public interfaces, functions, and components.
<a name="appliedproject-structuremd"></a>
# Project Structure
Base project structure and principles of module organization at folder and file level.
<a name="appliedcomponentsmd"></a>
# Components
Rules for creating UI components across all FSD layers.
<a name="appliedtemplates-generationmd"></a>
# Templates & Code Generation
Template tools, syntax, and examples for code generation.
<a name="appliedstylesmd"></a>
# Styles
CSS writing rules: PostCSS Modules, nesting, media queries, variables, formatting.
<a name="appliedimages-spritesmd"></a>
# Images
<a name="appliedsvg-spritesmd"></a>
# SVG Sprites
<a name="appliedvideomd"></a>
# Video
<a name="appliedapimd"></a>
# API
<a name="appliedstoresmd"></a>
# Stores
<a name="appliedhooksmd"></a>
# Hooks
<a name="appliedfontsmd"></a>
# Fonts
<a name="appliedlocalizationmd"></a>
# Localization

View File

@@ -1,5 +1,179 @@
<a name="1-tech-stackmd"></a>
<a name="indexmd"></a>
# NextJS Style Guide
Правила и стандарты разработки на NextJS и TypeScript: архитектура, типизация, стили, компоненты, API и инфраструктурные разделы.
## Для ассистентов
Полная документация в одном MD файле: https://gromlab.ru/docs/frontend-style-guide/raw/branch/main/generated/ru/RULES.md
## Структура документации
### Workflow
**Что делать** в конкретной ситуации — пошаговые инструкции.
| Раздел | Отвечает на вопрос |
|--------|-------------------|
| Начало работы | Какие инструменты установить перед началом разработки? |
| Создание приложения | Как создать новый проект, откуда взять шаблон? |
| Создание страниц | Как добавить страницу: роутинг и экран? |
| Создание компонентов | Как генерировать компоненты через шаблоны? |
| Стилизация | Чем стилизовать: Mantine, токены или PostCSS? |
| Работа с данными | Как получать данные: SWR, кодген, сокеты? |
| Управление состоянием | Когда и как создавать стор (Zustand)? |
| Локализация | Как добавлять переводы и работать с i18next? |
### Базовые правила
**Каким должен быть код** — стандарты, не привязанные к конкретной технологии.
| Раздел | Отвечает на вопрос |
|--------|-------------------|
| Технологии и библиотеки | Какой стек используем? |
| Архитектура | Как устроены слои FSD, зависимости, публичный API? |
| Стиль кода | Как оформлять код: отступы, кавычки, импорты, early return? |
| Именование | Как называть файлы, переменные, компоненты, хуки? |
| Документирование | Как писать JSDoc: что документировать, а что нет? |
| Типизация | Как типизировать: type vs interface, any/unknown, FC? |
### Прикладные разделы
**Как устроена конкретная область** — правила, структура и примеры кода для отдельных технологий и инструментов.
| Раздел | Отвечает на вопрос |
|--------|-------------------|
| Структура проекта | Как организованы папки и файлы по FSD? |
| Компоненты | Как устроен компонент: файлы, пропсы, clsx, FC? |
| Шаблоны и генерация | Как работают шаблоны: синтаксис, переменные, модификаторы? |
| Стили | Как писать CSS: PostCSS Modules, вложенность, медиа, токены? |
| Изображения | _(не заполнен)_ |
| SVG-спрайты | _(не заполнен)_ |
| Видео | _(не заполнен)_ |
| API | _(не заполнен)_ |
| Stores | _(не заполнен)_ |
| Хуки | _(не заполнен)_ |
| Шрифты | _(не заполнен)_ |
| Локализация | _(не заполнен)_ |
<a name="workflowgetting-startedmd"></a>
# Начало работы
Что нужно установить и настроить перед началом разработки.
## Инструменты
### CLI
| Инструмент | Установка | Назначение |
|-----------|-----------|-----------|
| [@gromlab/create](https://gromlab.ru/gromov/create) | `npm i -g @gromlab/create` | Генерация файлов и папок по шаблонам |
### VS Code
#### Расширения
Каждый проект должен содержать файл `.vscode/extensions.json` — VS Code автоматически предложит установить нужные расширения при открытии проекта.
```json
// .vscode/extensions.json
{
"recommendations": [
"biomejs.biome",
"MyTemplateGenerator.mytemplategenerator",
"csstools.postcss"
]
}
```
| Расширение | Назначение |
|-----------|-----------|
| [MyTemplateGenerator](https://open-vsx.org/extension/MyTemplateGenerator/mytemplategenerator) | Генерация файлов и папок из шаблонов через UI |
| [Biome](https://marketplace.visualstudio.com/items?itemName=biomejs.biome) | Линтинг и форматирование кода |
| [PostCSS Language Support](https://marketplace.visualstudio.com/items?itemName=csstools.postcss) | Подсветка и автодополнение PostCSS |
#### Настройки
Каждый проект должен содержать файл `.vscode/settings.json` с базовой конфигурацией редактора.
```json
// .vscode/settings.json
{
"editor.defaultFormatter": "biomejs.biome",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"quickfix.biome": "explicit",
"source.organizeImports.biome": "explicit"
},
"files.associations": {
"*.css": "postcss"
}
}
```
| Настройка | Что делает |
|-----------|-----------|
| `editor.defaultFormatter` | Biome как форматтер по умолчанию |
| `editor.formatOnSave` | Автоформатирование при сохранении |
| `codeActionsOnSave` | Автофикс и сортировка импортов при сохранении |
| `files.associations` | CSS-файлы открываются с подсветкой PostCSS |
<a name="workflowcreating-appmd"></a>
# Создание приложения
Как создать новое приложение: выбор шаблона проекта и инициализация.
<a name="workflowcreating-pagesmd"></a>
# Создание страниц
Паттерн создания страниц: роутинг (page.tsx) и экран (screen).
<a name="workflowcreating-componentsmd"></a>
# Создание компонентов
Генерация компонентов через шаблоны, работа с дочерними компонентами.
<a name="workflowstylingmd"></a>
# Стилизация
Приоритет инструментов стилизации и правила их применения.
<a name="workflowdata-fetchingmd"></a>
# Работа с данными
Как получать данные: SWR, кодген API-клиентов, сокеты.
<a name="workflowstate-managementmd"></a>
# Управление состоянием
Когда и как создавать стор (Zustand), что хранить локально и глобально.
<a name="workflowlocalizationmd"></a>
# Локализация
Как добавлять переводы и работать с i18next.
<a name="basicstech-stackmd"></a>
# Технологии и библиотеки
@@ -40,7 +214,7 @@
- **@gromlab/create** — шаблонизатор для создания слоёв и других файлов из шаблонов.
<a name="2-architecturemd"></a>
<a name="basicsarchitecturemd"></a>
# Архитектура
@@ -100,7 +274,7 @@
- Прямые импорты внутренних файлов, минуя публичный API.
<a name="3-code-stylemd"></a>
<a name="basicscode-stylemd"></a>
# Стиль кода
@@ -252,7 +426,7 @@ const config = { url: '/api/users', method: 'GET', params: { page: 1, pageSize:
```
<a name="4-namingmd"></a>
<a name="basicsnamingmd"></a>
# Именование
@@ -409,7 +583,7 @@ const users = {} as Record<string, User>;
```
<a name="5-documentationmd"></a>
<a name="basicsdocumentationmd"></a>
# Документирование
@@ -473,7 +647,7 @@ export enum TodoFilter {
```
<a name="6-typingmd"></a>
<a name="basicstypingmd"></a>
# Типизация
@@ -569,7 +743,7 @@ const parse = (value: any) => value;
```
<a name="7-project-structuremd"></a>
<a name="appliedproject-structuremd"></a>
# Структура проекта
@@ -687,7 +861,7 @@ src/
- Не смешивать ответственность разных слоёв в одном модуле.
<a name="8-0-componentsmd"></a>
<a name="appliedcomponentsmd"></a>
# Компоненты
@@ -765,9 +939,9 @@ export { Container } from './container.ui'
## Шаблоны и генерация кода
Генерация нужна, чтобы быстро создавать компоненты с единым каркасом и не допускать расхождений в структуре. Это даёт одинаковые папки и имена файлов, уменьшает ручные ошибки и ускоряет старт работы.
Создание компонентов — **только через шаблоны**. Ручное создание файловой структуры компонента запрещено. Это обеспечивает единообразие каркаса, одинаковые папки и имена файлов, уменьшает ручные ошибки и ускоряет старт работы.
Используйте **@gromlab/create** для создания базового шаблона компонента. После генерации проверьте название компонента/файлов и заполните описание назначения.
После генерации через **@gromlab/create** проверить название компонента/файлов и заполнить описание назначения. Подробный порядок действий и перечень обязательных шаблонов — в разделе «Workflow».
## Вложенные (дочерние) компоненты
@@ -776,16 +950,22 @@ export { Container } from './container.ui'
Вложенные компоненты подчиняются тем же правилам по структуре, именованию и стилю (включая папку `styles/` для их стилей).
<a name="8-1-templates-generationmd"></a>
<a name="appliedtemplates-generationmd"></a>
# Шаблоны генерации кода
Подход к использованию шаблонов и генерации кода для стандартизации структуры и ускорения разработки.
Раздел описывает инструменты, синтаксис шаблонов и примеры. Порядок действий при создании модулей и перечень обязательных шаблонов — в разделе «Workflow».
## Обязательность
- Создание типовых модулей — **только через шаблоны**. Ручное создание файловой структуры модуля запрещено, если для него существует шаблон.
- Перед созданием нового модуля — проверить наличие подходящего шаблона в `.templates/`.
- Если подходящего шаблона нет — сначала создать шаблон, затем использовать его.
## Что генерируем
- Компоненты (`screens`, `layouts`, `widgets`, `features`, `entities`).
- Страницы (nextjs `app`, `pages`)
- Страницы (nextjs `app`, `pages`).
- Типовые инфраструктурные модули (например, `store`).
## Чем генерируем
@@ -864,7 +1044,7 @@ export const {{name.pascalCase}} = () => {
## Шаблон компонента
Рекомендуемая структура компонента, создаётся генератором по шаблону.
Структура компонента по шаблону. Создаётся генератором автоматически.
```ts
// .templates/component/index.ts
@@ -908,15 +1088,29 @@ export const {{name.pascalCase}}: FC<{{name.pascalCase}}Props> = ({ className, .
```
<a name="9-stylesmd"></a>
<a name="appliedstylesmd"></a>
# Стили
Раздел описывает правила написания CSS: PostCSS Modules, вложенность, медиа-запросы, переменные, форматирование.
## Приоритет стилизации
Приоритет инструментов стилизации (от высшего к низшему):
1. **Mantine-компоненты и их пропсы** — в первую очередь использовать встроенные возможности Mantine.
2. **Глобальные CSS-токены** (`--color-*`, `--space-*`, `--radius-*`) — для значений, которые не покрываются Mantine.
3. **PostCSS Module файлы** — когда Mantine не покрывает задачу и нужна кастомная стилизация.
- Инлайн-стили в компонентах запрещены.
- Произвольные магические значения цветов, отступов и скруглений запрещены — использовать токены.
- Глобальные стили вне `app/styles/` запрещены.
Подробный порядок действий — в разделе «Workflow».
## Общие правила
- Только **PostCSS** и **CSS Modules** для стилизации.
- Только **PostCSS** и **CSS Modules** для кастомной стилизации.
- Подход **Mobile First** — стили пишутся от мобильных к десктопу.
- Именование классов — `camelCase` (`.root`, `.buttonNext`, `.itemTitle`).
- Модификаторы — отдельный класс с `_`, применяется через `&._modifier`.
@@ -1177,34 +1371,34 @@ export const {{name.pascalCase}}: FC<{{name.pascalCase}}Props> = ({ className, .
- Исключение — нетривиальные хаки и обходные решения, к которым стоит оставить пояснение.
<a name="10-images-spritesmd"></a>
<a name="appliedimages-spritesmd"></a>
<a name="11-videomd"></a>
<a name="12-apimd"></a>
<a name="13-storesmd"></a>
<a name="14-hooksmd"></a>
<a name="15-fontsmd"></a>
<a name="16-localizationmd"></a>
<a name="17-svg-spritesmd"></a>
<a name="appliedsvg-spritesmd"></a>
# SVG-спрайты
<a name="appliedvideomd"></a>
<a name="appliedapimd"></a>
<a name="appliedstoresmd"></a>
<a name="appliedhooksmd"></a>
<a name="appliedfontsmd"></a>
<a name="appliedlocalizationmd"></a>

View File

@@ -1,13 +0,0 @@
# Frontend Style Guide для проектов на React/Next.js и TypeScript
Это набор правил и практик для разработки фронтенд-проектов: архитектура, типизация, стили, компоненты, API и инфраструктурные разделы.
## Как пользоваться
- Начните с «Технологии и библиотеки», чтобы понимать базовые допущения.
- Затем прочитайте разделы из «Базовых правил».
- При реализации используйте соответствующие прикладные разделы.
## Для ассистентов
Полная документация в одном MD файле: https://gromlab.ru/docs/frontend-style-guide/raw/branch/main/RULES.md

View File

@@ -1,6 +0,0 @@
[build]
command = "npm run build"
publish = ".vitepress/dist"
[build.environment]
NODE_VERSION = "24"

View File

@@ -1,5 +1,5 @@
{
"name": "react-ts docs",
"name": "nextjs-style-guide",
"private": true,
"type": "module",
"version": "0.0.0",