From b37eb755425846fc2f0cdfe96cbb8ceb7cc60025 Mon Sep 17 00:00:00 2001 From: "S.Gromov" Date: Sat, 28 Mar 2026 21:15:15 +0300 Subject: [PATCH] sync --- .gitea/workflows/ci.yml | 2 +- .gitignore | 7 +- .vitepress/cache/deps/_metadata.json | 12 +- .vitepress/config.ts | 164 +++++++---- .vitepress/theme/custom.css | 5 + README.md | 59 +++- README_RU.md | 57 ++++ concat-md.js | 99 +++++-- docs/en/applied/api.md | 5 + docs/en/applied/components.md | 7 + docs/en/applied/fonts.md | 5 + docs/en/applied/hooks.md | 5 + docs/en/applied/images-sprites.md | 5 + docs/en/applied/localization.md | 5 + docs/en/applied/project-structure.md | 7 + docs/en/applied/stores.md | 5 + docs/en/applied/styles.md | 7 + docs/en/applied/svg-sprites.md | 5 + docs/en/applied/templates-generation.md | 7 + docs/en/applied/video.md | 5 + docs/en/basics/architecture.md | 7 + docs/en/basics/code-style.md | 7 + docs/en/basics/documentation.md | 7 + docs/en/basics/naming.md | 7 + docs/en/basics/tech-stack.md | 7 + docs/en/basics/typing.md | 7 + docs/en/index.md | 56 ++++ docs/en/workflow/creating-app.md | 7 + docs/en/workflow/creating-components.md | 7 + docs/en/workflow/creating-pages.md | 7 + docs/en/workflow/data-fetching.md | 7 + docs/en/workflow/getting-started.md | 7 + docs/en/workflow/localization.md | 7 + docs/en/workflow/state-management.md | 7 + docs/en/workflow/styling.md | 7 + .../ru/applied/api.md | 0 .../ru/applied/components.md | 4 +- parts/11-video.md => docs/ru/applied/fonts.md | 0 parts/12-api.md => docs/ru/applied/hooks.md | 0 .../ru/applied/images-sprites.md | 0 .../ru/applied/localization.md | 0 .../ru/applied/project-structure.md | 0 .../15-fonts.md => docs/ru/applied/stores.md | 0 .../9-styles.md => docs/ru/applied/styles.md | 16 +- .../ru/applied/svg-sprites.md | 0 .../ru/applied/templates-generation.md | 12 +- .../ru/applied/video.md | 0 .../ru/basics/architecture.md | 0 .../ru/basics/code-style.md | 0 .../ru/basics/documentation.md | 0 parts/4-naming.md => docs/ru/basics/naming.md | 0 .../ru/basics/tech-stack.md | 0 parts/6-typing.md => docs/ru/basics/typing.md | 0 docs/ru/index.md | 57 ++++ docs/ru/workflow/creating-app.md | 7 + docs/ru/workflow/creating-components.md | 7 + docs/ru/workflow/creating-pages.md | 7 + docs/ru/workflow/data-fetching.md | 7 + docs/ru/workflow/getting-started.md | 66 +++++ docs/ru/workflow/localization.md | 7 + docs/ru/workflow/state-management.md | 7 + docs/ru/workflow/styling.md | 7 + generated/en/RULES.md | 225 ++++++++++++++ RULES.md => generated/ru/RULES.md | 278 +++++++++++++++--- index.md | 13 - netlify.toml | 6 - package.json | 2 +- 67 files changed, 1203 insertions(+), 152 deletions(-) create mode 100644 README_RU.md create mode 100644 docs/en/applied/api.md create mode 100644 docs/en/applied/components.md create mode 100644 docs/en/applied/fonts.md create mode 100644 docs/en/applied/hooks.md create mode 100644 docs/en/applied/images-sprites.md create mode 100644 docs/en/applied/localization.md create mode 100644 docs/en/applied/project-structure.md create mode 100644 docs/en/applied/stores.md create mode 100644 docs/en/applied/styles.md create mode 100644 docs/en/applied/svg-sprites.md create mode 100644 docs/en/applied/templates-generation.md create mode 100644 docs/en/applied/video.md create mode 100644 docs/en/basics/architecture.md create mode 100644 docs/en/basics/code-style.md create mode 100644 docs/en/basics/documentation.md create mode 100644 docs/en/basics/naming.md create mode 100644 docs/en/basics/tech-stack.md create mode 100644 docs/en/basics/typing.md create mode 100644 docs/en/index.md create mode 100644 docs/en/workflow/creating-app.md create mode 100644 docs/en/workflow/creating-components.md create mode 100644 docs/en/workflow/creating-pages.md create mode 100644 docs/en/workflow/data-fetching.md create mode 100644 docs/en/workflow/getting-started.md create mode 100644 docs/en/workflow/localization.md create mode 100644 docs/en/workflow/state-management.md create mode 100644 docs/en/workflow/styling.md rename parts/10-images-sprites.md => docs/ru/applied/api.md (100%) rename parts/8-0-components.md => docs/ru/applied/components.md (82%) rename parts/11-video.md => docs/ru/applied/fonts.md (100%) rename parts/12-api.md => docs/ru/applied/hooks.md (100%) rename parts/13-stores.md => docs/ru/applied/images-sprites.md (100%) rename parts/14-hooks.md => docs/ru/applied/localization.md (100%) rename parts/7-project-structure.md => docs/ru/applied/project-structure.md (100%) rename parts/15-fonts.md => docs/ru/applied/stores.md (100%) rename parts/9-styles.md => docs/ru/applied/styles.md (85%) rename parts/17-svg-sprites.md => docs/ru/applied/svg-sprites.md (100%) rename parts/8-1-templates-generation.md => docs/ru/applied/templates-generation.md (78%) rename parts/16-localization.md => docs/ru/applied/video.md (100%) rename parts/2-architecture.md => docs/ru/basics/architecture.md (100%) rename parts/3-code-style.md => docs/ru/basics/code-style.md (100%) rename parts/5-documentation.md => docs/ru/basics/documentation.md (100%) rename parts/4-naming.md => docs/ru/basics/naming.md (100%) rename parts/1-tech-stack.md => docs/ru/basics/tech-stack.md (100%) rename parts/6-typing.md => docs/ru/basics/typing.md (100%) create mode 100644 docs/ru/index.md create mode 100644 docs/ru/workflow/creating-app.md create mode 100644 docs/ru/workflow/creating-components.md create mode 100644 docs/ru/workflow/creating-pages.md create mode 100644 docs/ru/workflow/data-fetching.md create mode 100644 docs/ru/workflow/getting-started.md create mode 100644 docs/ru/workflow/localization.md create mode 100644 docs/ru/workflow/state-management.md create mode 100644 docs/ru/workflow/styling.md create mode 100644 generated/en/RULES.md rename RULES.md => generated/ru/RULES.md (78%) delete mode 100644 index.md delete mode 100644 netlify.toml diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 2b7bad2..ed4a943 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -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 diff --git a/.gitignore b/.gitignore index f3f691e..b303b1a 100644 --- a/.gitignore +++ b/.gitignore @@ -129,4 +129,9 @@ dist .yarn/install-state.gz .pnp.* -.DS_Store \ No newline at end of file +.DS_Store + +# VitePress +.vitepress/cache +.vitepress/dist +docs/.vitepress \ No newline at end of file diff --git a/.vitepress/cache/deps/_metadata.json b/.vitepress/cache/deps/_metadata.json index ca0db82..398dffa 100644 --- a/.vitepress/cache/deps/_metadata.json +++ b/.vitepress/cache/deps/_metadata.json @@ -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 } }, diff --git a/.vitepress/config.ts b/.vitepress/config.ts index dd3542e..df8cf92 100644 --- a/.vitepress/config.ts +++ b/.vitepress/config.ts @@ -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, + }, + }, + }, +}); diff --git a/.vitepress/theme/custom.css b/.vitepress/theme/custom.css index 266026d..1831c87 100644 --- a/.vitepress/theme/custom.css +++ b/.vitepress/theme/custom.css @@ -1,3 +1,8 @@ +.VPNavBarTitle.has-sidebar .title { + border-top: none !important; + padding-top: 0; +} + .VPNavBarTitle .title { white-space: normal; line-height: 1.2; diff --git a/README.md b/README.md index e53636f..178367c 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/README_RU.md b/README_RU.md new file mode 100644 index 0000000..6fcd3a7 --- /dev/null +++ b/README_RU.md @@ -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 | _(не заполнен)_ | +| Хуки | _(не заполнен)_ | +| Шрифты | _(не заполнен)_ | +| Локализация | _(не заполнен)_ | + diff --git a/concat-md.js b/concat-md.js index 82f2ac3..0f202bd 100644 --- a/concat-md.js +++ b/concat-md.js @@ -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"); diff --git a/docs/en/applied/api.md b/docs/en/applied/api.md new file mode 100644 index 0000000..92e2c05 --- /dev/null +++ b/docs/en/applied/api.md @@ -0,0 +1,5 @@ +--- +title: API +--- + +# API diff --git a/docs/en/applied/components.md b/docs/en/applied/components.md new file mode 100644 index 0000000..62b33e6 --- /dev/null +++ b/docs/en/applied/components.md @@ -0,0 +1,7 @@ +--- +title: Components +--- + +# Components + +Rules for creating UI components across all FSD layers. diff --git a/docs/en/applied/fonts.md b/docs/en/applied/fonts.md new file mode 100644 index 0000000..f44d50c --- /dev/null +++ b/docs/en/applied/fonts.md @@ -0,0 +1,5 @@ +--- +title: Fonts +--- + +# Fonts diff --git a/docs/en/applied/hooks.md b/docs/en/applied/hooks.md new file mode 100644 index 0000000..a0c4376 --- /dev/null +++ b/docs/en/applied/hooks.md @@ -0,0 +1,5 @@ +--- +title: Hooks +--- + +# Hooks diff --git a/docs/en/applied/images-sprites.md b/docs/en/applied/images-sprites.md new file mode 100644 index 0000000..9014879 --- /dev/null +++ b/docs/en/applied/images-sprites.md @@ -0,0 +1,5 @@ +--- +title: Images +--- + +# Images diff --git a/docs/en/applied/localization.md b/docs/en/applied/localization.md new file mode 100644 index 0000000..c0c5eb3 --- /dev/null +++ b/docs/en/applied/localization.md @@ -0,0 +1,5 @@ +--- +title: Localization +--- + +# Localization diff --git a/docs/en/applied/project-structure.md b/docs/en/applied/project-structure.md new file mode 100644 index 0000000..bbf5def --- /dev/null +++ b/docs/en/applied/project-structure.md @@ -0,0 +1,7 @@ +--- +title: Project Structure +--- + +# Project Structure + +Base project structure and principles of module organization at folder and file level. diff --git a/docs/en/applied/stores.md b/docs/en/applied/stores.md new file mode 100644 index 0000000..d0cf77d --- /dev/null +++ b/docs/en/applied/stores.md @@ -0,0 +1,5 @@ +--- +title: Stores +--- + +# Stores diff --git a/docs/en/applied/styles.md b/docs/en/applied/styles.md new file mode 100644 index 0000000..7af40ac --- /dev/null +++ b/docs/en/applied/styles.md @@ -0,0 +1,7 @@ +--- +title: Styles +--- + +# Styles + +CSS writing rules: PostCSS Modules, nesting, media queries, variables, formatting. diff --git a/docs/en/applied/svg-sprites.md b/docs/en/applied/svg-sprites.md new file mode 100644 index 0000000..45e5895 --- /dev/null +++ b/docs/en/applied/svg-sprites.md @@ -0,0 +1,5 @@ +--- +title: SVG Sprites +--- + +# SVG Sprites diff --git a/docs/en/applied/templates-generation.md b/docs/en/applied/templates-generation.md new file mode 100644 index 0000000..c137721 --- /dev/null +++ b/docs/en/applied/templates-generation.md @@ -0,0 +1,7 @@ +--- +title: Templates & Code Generation +--- + +# Templates & Code Generation + +Template tools, syntax, and examples for code generation. diff --git a/docs/en/applied/video.md b/docs/en/applied/video.md new file mode 100644 index 0000000..7b6cd18 --- /dev/null +++ b/docs/en/applied/video.md @@ -0,0 +1,5 @@ +--- +title: Video +--- + +# Video diff --git a/docs/en/basics/architecture.md b/docs/en/basics/architecture.md new file mode 100644 index 0000000..b908f6b --- /dev/null +++ b/docs/en/basics/architecture.md @@ -0,0 +1,7 @@ +--- +title: Architecture +--- + +# Architecture + +Architecture based on FSD (Feature-Sliced Design) and strict module boundaries. diff --git a/docs/en/basics/code-style.md b/docs/en/basics/code-style.md new file mode 100644 index 0000000..85bec4b --- /dev/null +++ b/docs/en/basics/code-style.md @@ -0,0 +1,7 @@ +--- +title: Code Style +--- + +# Code Style + +Unified code formatting rules: indentation, line breaks, quotes, import order, and readability. diff --git a/docs/en/basics/documentation.md b/docs/en/basics/documentation.md new file mode 100644 index 0000000..094808e --- /dev/null +++ b/docs/en/basics/documentation.md @@ -0,0 +1,7 @@ +--- +title: Documentation +--- + +# Documentation + +Documentation should help understand the purpose of an entity, not duplicate its types or obvious details. diff --git a/docs/en/basics/naming.md b/docs/en/basics/naming.md new file mode 100644 index 0000000..c5aebc0 --- /dev/null +++ b/docs/en/basics/naming.md @@ -0,0 +1,7 @@ +--- +title: Naming +--- + +# Naming + +Naming should be predictable, concise, and reflect the meaning of the entity. diff --git a/docs/en/basics/tech-stack.md b/docs/en/basics/tech-stack.md new file mode 100644 index 0000000..c43318f --- /dev/null +++ b/docs/en/basics/tech-stack.md @@ -0,0 +1,7 @@ +--- +title: Tech Stack +--- + +# Tech Stack + +Base technology stack and libraries used in projects. diff --git a/docs/en/basics/typing.md b/docs/en/basics/typing.md new file mode 100644 index 0000000..faa1d11 --- /dev/null +++ b/docs/en/basics/typing.md @@ -0,0 +1,7 @@ +--- +title: Typing +--- + +# Typing + +Typing is required for all public interfaces, functions, and components. diff --git a/docs/en/index.md b/docs/en/index.md new file mode 100644 index 0000000..178367c --- /dev/null +++ b/docs/en/index.md @@ -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 diff --git a/docs/en/workflow/creating-app.md b/docs/en/workflow/creating-app.md new file mode 100644 index 0000000..119b9b6 --- /dev/null +++ b/docs/en/workflow/creating-app.md @@ -0,0 +1,7 @@ +--- +title: Creating an App +--- + +# Creating an App + +How to create a new application: choosing a project template and initialization. diff --git a/docs/en/workflow/creating-components.md b/docs/en/workflow/creating-components.md new file mode 100644 index 0000000..6c71dd2 --- /dev/null +++ b/docs/en/workflow/creating-components.md @@ -0,0 +1,7 @@ +--- +title: Creating Components +--- + +# Creating Components + +Generating components using templates, working with child components. diff --git a/docs/en/workflow/creating-pages.md b/docs/en/workflow/creating-pages.md new file mode 100644 index 0000000..5edd2fa --- /dev/null +++ b/docs/en/workflow/creating-pages.md @@ -0,0 +1,7 @@ +--- +title: Creating Pages +--- + +# Creating Pages + +Page creation pattern: routing (page.tsx) and screen. diff --git a/docs/en/workflow/data-fetching.md b/docs/en/workflow/data-fetching.md new file mode 100644 index 0000000..a20cf89 --- /dev/null +++ b/docs/en/workflow/data-fetching.md @@ -0,0 +1,7 @@ +--- +title: Data Fetching +--- + +# Data Fetching + +How to fetch data: SWR, API client codegen, sockets. diff --git a/docs/en/workflow/getting-started.md b/docs/en/workflow/getting-started.md new file mode 100644 index 0000000..a503150 --- /dev/null +++ b/docs/en/workflow/getting-started.md @@ -0,0 +1,7 @@ +--- +title: Getting Started +--- + +# Getting Started + +Setting up the environment and installing tools before starting development. diff --git a/docs/en/workflow/localization.md b/docs/en/workflow/localization.md new file mode 100644 index 0000000..6231664 --- /dev/null +++ b/docs/en/workflow/localization.md @@ -0,0 +1,7 @@ +--- +title: Localization +--- + +# Localization + +How to add translations and work with i18next. diff --git a/docs/en/workflow/state-management.md b/docs/en/workflow/state-management.md new file mode 100644 index 0000000..05cfa65 --- /dev/null +++ b/docs/en/workflow/state-management.md @@ -0,0 +1,7 @@ +--- +title: State Management +--- + +# State Management + +When and how to create a store (Zustand), what to store locally vs globally. diff --git a/docs/en/workflow/styling.md b/docs/en/workflow/styling.md new file mode 100644 index 0000000..495de7e --- /dev/null +++ b/docs/en/workflow/styling.md @@ -0,0 +1,7 @@ +--- +title: Styling +--- + +# Styling + +Styling tools priority and rules for their application. diff --git a/parts/10-images-sprites.md b/docs/ru/applied/api.md similarity index 100% rename from parts/10-images-sprites.md rename to docs/ru/applied/api.md diff --git a/parts/8-0-components.md b/docs/ru/applied/components.md similarity index 82% rename from parts/8-0-components.md rename to docs/ru/applied/components.md index de04047..a969d8c 100644 --- a/parts/8-0-components.md +++ b/docs/ru/applied/components.md @@ -78,9 +78,9 @@ export { Container } from './container.ui' ## Шаблоны и генерация кода -Генерация нужна, чтобы быстро создавать компоненты с единым каркасом и не допускать расхождений в структуре. Это даёт одинаковые папки и имена файлов, уменьшает ручные ошибки и ускоряет старт работы. +Создание компонентов — **только через шаблоны**. Ручное создание файловой структуры компонента запрещено. Это обеспечивает единообразие каркаса, одинаковые папки и имена файлов, уменьшает ручные ошибки и ускоряет старт работы. -Используйте **@gromlab/create** для создания базового шаблона компонента. После генерации проверьте название компонента/файлов и заполните описание назначения. +После генерации через **@gromlab/create** — проверить название компонента/файлов и заполнить описание назначения. Подробный порядок действий и перечень обязательных шаблонов — в разделе «Workflow». ## Вложенные (дочерние) компоненты diff --git a/parts/11-video.md b/docs/ru/applied/fonts.md similarity index 100% rename from parts/11-video.md rename to docs/ru/applied/fonts.md diff --git a/parts/12-api.md b/docs/ru/applied/hooks.md similarity index 100% rename from parts/12-api.md rename to docs/ru/applied/hooks.md diff --git a/parts/13-stores.md b/docs/ru/applied/images-sprites.md similarity index 100% rename from parts/13-stores.md rename to docs/ru/applied/images-sprites.md diff --git a/parts/14-hooks.md b/docs/ru/applied/localization.md similarity index 100% rename from parts/14-hooks.md rename to docs/ru/applied/localization.md diff --git a/parts/7-project-structure.md b/docs/ru/applied/project-structure.md similarity index 100% rename from parts/7-project-structure.md rename to docs/ru/applied/project-structure.md diff --git a/parts/15-fonts.md b/docs/ru/applied/stores.md similarity index 100% rename from parts/15-fonts.md rename to docs/ru/applied/stores.md diff --git a/parts/9-styles.md b/docs/ru/applied/styles.md similarity index 85% rename from parts/9-styles.md rename to docs/ru/applied/styles.md index 5ce2a88..6197142 100644 --- a/parts/9-styles.md +++ b/docs/ru/applied/styles.md @@ -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`. diff --git a/parts/17-svg-sprites.md b/docs/ru/applied/svg-sprites.md similarity index 100% rename from parts/17-svg-sprites.md rename to docs/ru/applied/svg-sprites.md diff --git a/parts/8-1-templates-generation.md b/docs/ru/applied/templates-generation.md similarity index 78% rename from parts/8-1-templates-generation.md rename to docs/ru/applied/templates-generation.md index 3bdedfb..ba9ba61 100644 --- a/parts/8-1-templates-generation.md +++ b/docs/ru/applied/templates-generation.md @@ -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 diff --git a/parts/16-localization.md b/docs/ru/applied/video.md similarity index 100% rename from parts/16-localization.md rename to docs/ru/applied/video.md diff --git a/parts/2-architecture.md b/docs/ru/basics/architecture.md similarity index 100% rename from parts/2-architecture.md rename to docs/ru/basics/architecture.md diff --git a/parts/3-code-style.md b/docs/ru/basics/code-style.md similarity index 100% rename from parts/3-code-style.md rename to docs/ru/basics/code-style.md diff --git a/parts/5-documentation.md b/docs/ru/basics/documentation.md similarity index 100% rename from parts/5-documentation.md rename to docs/ru/basics/documentation.md diff --git a/parts/4-naming.md b/docs/ru/basics/naming.md similarity index 100% rename from parts/4-naming.md rename to docs/ru/basics/naming.md diff --git a/parts/1-tech-stack.md b/docs/ru/basics/tech-stack.md similarity index 100% rename from parts/1-tech-stack.md rename to docs/ru/basics/tech-stack.md diff --git a/parts/6-typing.md b/docs/ru/basics/typing.md similarity index 100% rename from parts/6-typing.md rename to docs/ru/basics/typing.md diff --git a/docs/ru/index.md b/docs/ru/index.md new file mode 100644 index 0000000..6fcd3a7 --- /dev/null +++ b/docs/ru/index.md @@ -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 | _(не заполнен)_ | +| Хуки | _(не заполнен)_ | +| Шрифты | _(не заполнен)_ | +| Локализация | _(не заполнен)_ | + diff --git a/docs/ru/workflow/creating-app.md b/docs/ru/workflow/creating-app.md new file mode 100644 index 0000000..fae79c6 --- /dev/null +++ b/docs/ru/workflow/creating-app.md @@ -0,0 +1,7 @@ +--- +title: Создание приложения +--- + +# Создание приложения + +Как создать новое приложение: выбор шаблона проекта и инициализация. diff --git a/docs/ru/workflow/creating-components.md b/docs/ru/workflow/creating-components.md new file mode 100644 index 0000000..1b2ee5d --- /dev/null +++ b/docs/ru/workflow/creating-components.md @@ -0,0 +1,7 @@ +--- +title: Создание компонентов +--- + +# Создание компонентов + +Генерация компонентов через шаблоны, работа с дочерними компонентами. diff --git a/docs/ru/workflow/creating-pages.md b/docs/ru/workflow/creating-pages.md new file mode 100644 index 0000000..bd6e297 --- /dev/null +++ b/docs/ru/workflow/creating-pages.md @@ -0,0 +1,7 @@ +--- +title: Создание страниц +--- + +# Создание страниц + +Паттерн создания страниц: роутинг (page.tsx) и экран (screen). diff --git a/docs/ru/workflow/data-fetching.md b/docs/ru/workflow/data-fetching.md new file mode 100644 index 0000000..7b170b2 --- /dev/null +++ b/docs/ru/workflow/data-fetching.md @@ -0,0 +1,7 @@ +--- +title: Работа с данными +--- + +# Работа с данными + +Как получать данные: SWR, кодген API-клиентов, сокеты. diff --git a/docs/ru/workflow/getting-started.md b/docs/ru/workflow/getting-started.md new file mode 100644 index 0000000..3c152c7 --- /dev/null +++ b/docs/ru/workflow/getting-started.md @@ -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 | diff --git a/docs/ru/workflow/localization.md b/docs/ru/workflow/localization.md new file mode 100644 index 0000000..e22a7d2 --- /dev/null +++ b/docs/ru/workflow/localization.md @@ -0,0 +1,7 @@ +--- +title: Локализация +--- + +# Локализация + +Как добавлять переводы и работать с i18next. diff --git a/docs/ru/workflow/state-management.md b/docs/ru/workflow/state-management.md new file mode 100644 index 0000000..24cc46a --- /dev/null +++ b/docs/ru/workflow/state-management.md @@ -0,0 +1,7 @@ +--- +title: Управление состоянием +--- + +# Управление состоянием + +Когда и как создавать стор (Zustand), что хранить локально и глобально. diff --git a/docs/ru/workflow/styling.md b/docs/ru/workflow/styling.md new file mode 100644 index 0000000..4ba3697 --- /dev/null +++ b/docs/ru/workflow/styling.md @@ -0,0 +1,7 @@ +--- +title: Стилизация +--- + +# Стилизация + +Приоритет инструментов стилизации и правила их применения. diff --git a/generated/en/RULES.md b/generated/en/RULES.md new file mode 100644 index 0000000..c3753c0 --- /dev/null +++ b/generated/en/RULES.md @@ -0,0 +1,225 @@ + + + +# 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 + + + + +# Getting Started + +Setting up the environment and installing tools before starting development. + + + + +# Creating an App + +How to create a new application: choosing a project template and initialization. + + + + +# Creating Pages + +Page creation pattern: routing (page.tsx) and screen. + + + + +# Creating Components + +Generating components using templates, working with child components. + + + + +# Styling + +Styling tools priority and rules for their application. + + + + +# Data Fetching + +How to fetch data: SWR, API client codegen, sockets. + + + + +# State Management + +When and how to create a store (Zustand), what to store locally vs globally. + + + + +# Localization + +How to add translations and work with i18next. + + + + +# Tech Stack + +Base technology stack and libraries used in projects. + + + + +# Architecture + +Architecture based on FSD (Feature-Sliced Design) and strict module boundaries. + + + + +# Code Style + +Unified code formatting rules: indentation, line breaks, quotes, import order, and readability. + + + + +# Naming + +Naming should be predictable, concise, and reflect the meaning of the entity. + + + + +# Documentation + +Documentation should help understand the purpose of an entity, not duplicate its types or obvious details. + + + + +# Typing + +Typing is required for all public interfaces, functions, and components. + + + + +# Project Structure + +Base project structure and principles of module organization at folder and file level. + + + + +# Components + +Rules for creating UI components across all FSD layers. + + + + +# Templates & Code Generation + +Template tools, syntax, and examples for code generation. + + + + +# Styles + +CSS writing rules: PostCSS Modules, nesting, media queries, variables, formatting. + + + + +# Images + + + + +# SVG Sprites + + + + +# Video + + + + +# API + + + + +# Stores + + + + +# Hooks + + + + +# Fonts + + + + +# Localization diff --git a/RULES.md b/generated/ru/RULES.md similarity index 78% rename from RULES.md rename to generated/ru/RULES.md index d56b4fa..7baff9e 100644 --- a/RULES.md +++ b/generated/ru/RULES.md @@ -1,5 +1,179 @@ - + + +# 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 | _(не заполнен)_ | +| Хуки | _(не заполнен)_ | +| Шрифты | _(не заполнен)_ | +| Локализация | _(не заполнен)_ | + + + + + +# Начало работы + +Что нужно установить и настроить перед началом разработки. + +## Инструменты + +### 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 | + + + + +# Создание приложения + +Как создать новое приложение: выбор шаблона проекта и инициализация. + + + + +# Создание страниц + +Паттерн создания страниц: роутинг (page.tsx) и экран (screen). + + + + +# Создание компонентов + +Генерация компонентов через шаблоны, работа с дочерними компонентами. + + + + +# Стилизация + +Приоритет инструментов стилизации и правила их применения. + + + + +# Работа с данными + +Как получать данные: SWR, кодген API-клиентов, сокеты. + + + + +# Управление состоянием + +Когда и как создавать стор (Zustand), что хранить локально и глобально. + + + + +# Локализация + +Как добавлять переводы и работать с i18next. + + + # Технологии и библиотеки @@ -40,7 +214,7 @@ - **@gromlab/create** — шаблонизатор для создания слоёв и других файлов из шаблонов. - + # Архитектура @@ -100,7 +274,7 @@ - Прямые импорты внутренних файлов, минуя публичный API. - + # Стиль кода @@ -252,7 +426,7 @@ const config = { url: '/api/users', method: 'GET', params: { page: 1, pageSize: ``` - + # Именование @@ -409,7 +583,7 @@ const users = {} as Record; ``` - + # Документирование @@ -473,7 +647,7 @@ export enum TodoFilter { ``` - + # Типизация @@ -569,7 +743,7 @@ const parse = (value: any) => value; ``` - + # Структура проекта @@ -687,7 +861,7 @@ src/ - Не смешивать ответственность разных слоёв в одном модуле. - + # Компоненты @@ -765,9 +939,9 @@ export { Container } from './container.ui' ## Шаблоны и генерация кода -Генерация нужна, чтобы быстро создавать компоненты с единым каркасом и не допускать расхождений в структуре. Это даёт одинаковые папки и имена файлов, уменьшает ручные ошибки и ускоряет старт работы. +Создание компонентов — **только через шаблоны**. Ручное создание файловой структуры компонента запрещено. Это обеспечивает единообразие каркаса, одинаковые папки и имена файлов, уменьшает ручные ошибки и ускоряет старт работы. -Используйте **@gromlab/create** для создания базового шаблона компонента. После генерации проверьте название компонента/файлов и заполните описание назначения. +После генерации через **@gromlab/create** — проверить название компонента/файлов и заполнить описание назначения. Подробный порядок действий и перечень обязательных шаблонов — в разделе «Workflow». ## Вложенные (дочерние) компоненты @@ -776,16 +950,22 @@ export { Container } from './container.ui' Вложенные компоненты подчиняются тем же правилам по структуре, именованию и стилю (включая папку `styles/` для их стилей). - + # Шаблоны генерации кода -Подход к использованию шаблонов и генерации кода для стандартизации структуры и ускорения разработки. +Раздел описывает инструменты, синтаксис шаблонов и примеры. Порядок действий при создании модулей и перечень обязательных шаблонов — в разделе «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, . ``` - + # Стили Раздел описывает правила написания 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, . - Исключение — нетривиальные хаки и обходные решения, к которым стоит оставить пояснение. - + - - - - - - - - - - - - - - - - - - - - - - - - - + # SVG-спрайты + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/index.md b/index.md deleted file mode 100644 index e53636f..0000000 --- a/index.md +++ /dev/null @@ -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 diff --git a/netlify.toml b/netlify.toml deleted file mode 100644 index 6375196..0000000 --- a/netlify.toml +++ /dev/null @@ -1,6 +0,0 @@ -[build] -command = "npm run build" -publish = ".vitepress/dist" - -[build.environment] -NODE_VERSION = "24" diff --git a/package.json b/package.json index 976a479..bf59ffe 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "react-ts docs", + "name": "nextjs-style-guide", "private": true, "type": "module", "version": "0.0.0",