From afac868846bdd2ffb97c1c41befa682cc1e1c83c Mon Sep 17 00:00:00 2001 From: Lev Chelyadinov Date: Wed, 26 Jun 2024 01:11:52 +0200 Subject: [PATCH 1/3] feat: rewrite the overview for English --- .../current/get-started/overview.md | 102 -------------- .../current/get-started/overview.mdx | 129 ++++++++++++++++++ 2 files changed, 129 insertions(+), 102 deletions(-) delete mode 100644 i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.md create mode 100644 i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx diff --git a/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.md b/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.md deleted file mode 100644 index 750bf4d52..000000000 --- a/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Overview - -**Feature-Sliced Design** (FSD) is an architectural methodology for scaffolding front-end applications. Simply put, it's a compilation of rules and conventions on organizing code. The main purpose of this methodology is to make the project more understandable and structured in the face of ever-changing business requirements. - -## Is it right for me? - -FSD can be implemented in projects and teams of any size, but there are a few things to keep in mind: - -- This methodology is for front-end projects only. If you're looking for a back-end architecture, consider [Clean Architecture][refs-clean-architecture]. -- This methodology is for user-facing applications only, not for libraries or UI kits. If you're looking for an architecture for a UI kit, see [Material UI][ext-material-ui] for inspiration. -- A very simple app of a single page might not need the benefits of FSD and suffer from the overhead. However, FSD promotes a nice way of thinking, so feel free to use it on the tiniest projects if you want. -- A huge app, the size of the Google Cloud admin dashboard, will require a custom architecture. It could still be based on FSD, by the way. - -FSD doesn't enforce a particular programming language, UI framework or state manager — bring your own or see some [examples][refs-examples]. - -If you have an existing project, fear not — FSD can be adopted incrementally. Just make sure that your team is **in pain** from the current architecture, otherwise a switch might not be worth it. For migration guidance, see the [Migration section][refs-migration]. - -## Basics - -In FSD, a project consists of layers, each layer is made up of slices and each slice is made up of segments. - -![themed--scheme](/img/visual_schema.jpg) - -The **layers** are standardized across all projects and vertically arranged. Modules on one layer can only interact with modules from the layers strictly below. There are currently seven of them (from top to bottom): - -1. `app` — app-wide settings, styles and providers. -2. `processes` (deprecated) — complex inter-page scenarios. - (e.g., authentication). -3. `pages` — compositional layer to construct full pages from entities, features and widgets. -4. `widgets` — compositional layer to combine entities and features into meaningful blocks. - (e.g. IssuesList, UserProfile). -5. `features` — user interactions, actions that bring business value to the user. - (e.g. SendComment, AddToCart, UsersSearch). -6. `entities` — business entities. - (e.g., User, Product, Order). -7. `shared` — reusable functionality, detached from the specifics of the project/business. - (e.g. UIKit, libs, API)/. - - -Then there are **slices**, which partition the code by business domain. This makes your codebase easy to navigate by keeping logically related modules close together. Slices cannot use other slices on the same layer, and that helps with high cohesion and low coupling. - -Each slice, in turn, consists of **segments**. These are tiny modules that are meant to help with separating code within a slice by its technical purpose. The most common segments are `ui`, `model` (store, actions), `api` and `lib` (utils/hooks), but you can omit some or add more, as you see fit. - -:::note - -In most cases, [it is recommended][ext-disc-api] to place `api` and `config` only in the shared layer, unless your API client is also your storage (GraphQL, TanStack Query, etc.) - -::: - -## Example - -Let's consider a social network application. - -* `app/` contains setup of routing, store and global styles. -* `pages/` contains the route components for each page in the app, mostly composition, hardly any logic. - -Within that application, let's consider a post card in a news feed. - -* `widgets/` contains the "assembled" post card, with content and interactive buttons that are wired up to the relevant calls on the back-end. -* `features/` contains the interactivity of the card (e.g., like button) and the logic of processing those interactions. -* `entities/` contains the shell of the card with slots for content and the interactive elements. The tile representing the post author is also here, but in a different slice. - -## Advantages - -- **Uniformity** - The code is organized by scope of influence (layers), by domain (slices), and by technical purpose (segments). - This creates a standardized architecture that is easy to comprehend for newcomers. - -- **Controlled reuse of logic** - Each architectural component has its purpose and predictable dependencies. - This keeps a balance between following the **DRY** principle and adaptation possibilities. - -- **Stability in face of changes and refactoring** - A module on a particular layer cannot use other modules on the same layer, or the layers above. - This enables isolated modifications without unforeseen consequences. - -- **Orientation to business and users needs** - When the app is split into business domains, you can navigate the code to discover and deeper understand all the project features. - -## Incremental adoption - -The power of FSD lies in _structured_ decomposition. At its finest, it enables to locate any part of code near-deterministically. However, the level of decomposition is a parameter, and each team can tweak it to strike a balance between simple adoption and the amount of benefits. - -Here's a proposed strategy to migrate an existing codebase to FSD, based on experience: - -1. Start by outlining the `app` and `shared` layers to create a foundation. Usually, these layers are the smallest. - -2. Distribute all of the existing UI across `widgets` and `pages`, even if they have dependencies that violate the rules of FSD. - -3. Start gradually increasing the precision of decomposition by separating `features` and `entities`, turning pages and widgets from logic-bearing layers into purely compositional layers. - -It's advised to refrain from adding new large entities while refactoring or refactoring only certain parts of the project. - -[refs-clean-architecture]: https://medium.com/codex/clean-architecture-for-dummies-df6561d42c94 -[ext-disc-api]: https://github.com/feature-sliced/documentation/discussions/66 -[ext-material-ui]: https://github.com/mui/material-ui -[refs-examples]: /examples -[refs-migration]: /docs/guides/migration/from-legacy diff --git a/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx b/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx new file mode 100644 index 000000000..1f14f4f56 --- /dev/null +++ b/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx @@ -0,0 +1,129 @@ +--- +sidebar_position: 1 +--- + +# Overview + +**Feature-Sliced Design** (FSD) is an architectural methodology for scaffolding front-end applications. Simply put, it's a compilation of rules and conventions on organizing code. The main purpose of this methodology is to make the project more understandable and structured in the face of ever-changing business requirements. + +Apart from a set of conventions, FSD is also a toolchain. We have a [linter][ext-steiger] to check your project's architecture, [folder generators][ext-tools] in CLI and IDEs, as well as a rich library of [examples][examples]. + +## Is it right for me? + +FSD can be implemented in projects and teams of any size. It is right for your project if: + +- You're doing **frontend** (UI on web, mobile, desktop, etc.) +- You're building an **application**, not a library + +And that's it! There are no restrictions on what programming language, UI framework or state manager you use. You can also adopt FSD incrementally, use it in monorepos, and scale to great lengths. + +If you already have an architecture and you're considering a switch to FSD, make sure that the current architecture is **causing trouble** in your team. For example, if your project has grown too large and inter-connected to efficiently implement new features, or if you're expecting a lot of new members to join the team. If the current architecture works, maybe it's not worth changing. But if you do decide to migrate, see the [Migration][migration] section for guidance. + +## Basic example + +Here is a simple project that implements FSD: + +- `📁 app` +- `📁 pages` +- `📁 shared` + +These top-level folders are called _layers_. Let's look deeper: + +- `📂 app` + - `📁 routes` + - `📁 analytics` +- `📂 pages` + - `📁 home` + - `📂 article-reader` + - `📁 ui` + - `📁 api` + - `📁 settings` +- `📂 shared` + - `📁 ui` + - `📁 api` + +Folders inside `📂 pages` are called _slices_. They divide the layer by domain (in this case, by pages). + +Folders inside `📂 app`, `📂 shared`, and `📂 pages/article-reader` are called _segments_, and they divide slices (or layers) by technical purpose, i.e. what the code is for. + +## Concepts + +Layers, slices, and segments form a hierarchy like this: + +
+ ![Three pillars, labeled left to right as "Layers", "Slices", and "Segments" respectively. The "Layers" pillar contains seven divisions arranged top to bottom and labeled "app", "processes", "pages", "widgets", "features", "entities", and "shared". The "processes" division is crossed out. The "entities" division is connected to the second pillar "Slices" in a way that conveys that the second pillar is the content of "entities". The "Slices" pillar contains three divisions arranged top to bottom and labeled "user", "post", and "comment". The "post" division is connected to the third pillar "Segments" in the same way such that it's the content of "post". The "Segments" pillar contains three divisions, arranged top to bottom and labeled "ui", "model", and "api".](/img/visual_schema.jpg) + +
+

Three pillars, labeled left to right as "Layers", "Slices", and "Segments" respectively.

+

The "Layers" pillar contains seven divisions arranged top to bottom and labeled "app", "processes", "pages", "widgets", "features", "entities", and "shared". The "processes" division is crossed out. The "entities" division is connected to the second pillar "Slices" in a way that conveys that the second pillar is the content of "entities".

+

The "Slices" pillar contains three divisions arranged top to bottom and labeled "user", "post", and "comment". The "post" division is connected to the third pillar "Segments" in the same way such that it's the content of "post".

+

The "Segments" pillar contains three divisions, arranged top to bottom and labeled "ui", "model", and "api".

+
+
+ +### Layers + +Layers are standardized across all FSD projects. You don't have to use all of the layers, but their names are important. There are currently seven of them (from top to bottom): + +1. App\* — everything that makes the app run — routing, entrypoints, global styles, providers. +2. Processes (deprecated) — complex inter-page scenarios. +3. Pages — full pages or large parts of a page in nested routing scenarios. +4. Widgets — large self-contained chunks of functionality or UI, usually delivering an entire use case. +5. Features — _reusable_ implementations of entire product features, i.e. actions that bring business value to the user. +6. Entities — business entities that the project works with, like `user` or `product`. +7. Shared\* — reusable functionality, ideally detached from the specifics of the project/business. + +_\* — Layers App and Shared are made up of segments directly, while other layers are made up of slices that are then made up of segments._ + +The trick with layers is that modules on one layer can only know about and import from modules from the layers strictly below. + +### Slices + +Next up are slices, which partition the code by business domain. You're free to choose any names for them, and create as many as you wish. Slices make your codebase easier to navigate by keeping logically related modules close together. + +Slices cannot use other slices on the same layer, and that helps with high cohesion and low coupling. + +### Segments + +Slices, as well as layers App and Shared, consist of segments, and segments group your code by its purpose. Segment names are not constrained by standard, but there are several conventional names for the most common purposes: + +- `ui` — self-explanatory +- `api` — also self-explanatory +- `model` — the data model: schemas, interfaces, stores, and business logic +- `lib` — library code that's only used within this slice +- `config` — configuration files and feature flags + +Usually these segments are enough for most layers, you would only create your own segments in Shared or App, but this is not a rule that you have to obey. + +## Advantages + +- **Uniformity** + Since the structure is standardized, projects become more uniform, which makes onboarding new members easier for the team. + +- **Stability in face of changes and refactoring** + A module on a layer cannot use other modules on the same layer, or the layers above. + This allows you to make isolated modifications without unforeseen consequences to the rest of the app. + +- **Controlled reuse of logic** + Depending on the layer, you can make code very reusable or very local. + This keeps a balance between following the **DRY** principle and practicality. + +- **Orientation to business and users needs** + The app is split into business domains and usage of the business language is encouraged in naming, so that you can do useful product work without fully understanding all other unrelated parts of the project. + +## Incremental adoption + +If you have an existing codebase that you want to migrate to FSD, we suggest this strategy. We found it useful in our own migration experience. + +1. Start by slowly moving code module-by-module to the App and Shared layers to create a foundation. Usually, these layers are the smallest. + +2. Distribute all of the existing UI across Widgets and Pages using broad strokes, even if they have dependencies that violate the rules of FSD. + +3. Start gradually resolving import violations and also extracting Entities and possibly even Features. + +It's advised to refrain from adding new large entities while refactoring or refactoring only certain parts of the project. + +[examples]: /examples +[migration]: /docs/guides/migration/from-legacy +[ext-steiger]: https://github.com/feature-sliced/steiger +[ext-tools]: https://github.com/feature-sliced/awesome?tab=readme-ov-file#tools From 19ba748da5c35f9b1289a5bf2f6b53887acdf8f4 Mon Sep 17 00:00:00 2001 From: Lev Chelyadinov Date: Thu, 27 Jun 2024 00:44:26 +0200 Subject: [PATCH 2/3] Add the Russian version and fix mistakes --- .../current/get-started/overview.mdx | 55 ++++--- .../current/get-started/overview.md | 102 ------------- .../current/get-started/overview.mdx | 138 ++++++++++++++++++ 3 files changed, 170 insertions(+), 125 deletions(-) delete mode 100644 i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.md create mode 100644 i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.mdx diff --git a/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx b/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx index 1f14f4f56..930b330c4 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx +++ b/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx @@ -2,24 +2,24 @@ sidebar_position: 1 --- -# Overview +# Overview {#overview} -**Feature-Sliced Design** (FSD) is an architectural methodology for scaffolding front-end applications. Simply put, it's a compilation of rules and conventions on organizing code. The main purpose of this methodology is to make the project more understandable and structured in the face of ever-changing business requirements. +**Feature-Sliced Design** (FSD) is an architectural methodology for scaffolding front-end applications. Simply put, it's a compilation of rules and conventions on organizing code. The main purpose of this methodology is to make the project more understandable and stable in the face of ever-changing business requirements. -Apart from a set of conventions, FSD is also a toolchain. We have a [linter][ext-steiger] to check your project's architecture, [folder generators][ext-tools] in CLI and IDEs, as well as a rich library of [examples][examples]. +Apart from a set of conventions, FSD is also a toolchain. We have a [linter][ext-steiger] to check your project's architecture, [folder generators][ext-tools] through a CLI or IDEs, as well as a rich library of [examples][examples]. -## Is it right for me? +## Is it right for me? {#is-it-right-for-me} FSD can be implemented in projects and teams of any size. It is right for your project if: - You're doing **frontend** (UI on web, mobile, desktop, etc.) - You're building an **application**, not a library -And that's it! There are no restrictions on what programming language, UI framework or state manager you use. You can also adopt FSD incrementally, use it in monorepos, and scale to great lengths. +And that's it! There are no restrictions on what programming language, UI framework, or state manager you use. You can also adopt FSD incrementally, use it in monorepos, and scale to great lengths by breaking your app into packages and implementing FSD individually within them. If you already have an architecture and you're considering a switch to FSD, make sure that the current architecture is **causing trouble** in your team. For example, if your project has grown too large and inter-connected to efficiently implement new features, or if you're expecting a lot of new members to join the team. If the current architecture works, maybe it's not worth changing. But if you do decide to migrate, see the [Migration][migration] section for guidance. -## Basic example +## Basic example {#basic-example} Here is a simple project that implements FSD: @@ -46,46 +46,46 @@ Folders inside `📂 pages` are called _slices_. They divide the layer by domain Folders inside `📂 app`, `📂 shared`, and `📂 pages/article-reader` are called _segments_, and they divide slices (or layers) by technical purpose, i.e. what the code is for. -## Concepts +## Concepts {#concepts} Layers, slices, and segments form a hierarchy like this:
- ![Three pillars, labeled left to right as "Layers", "Slices", and "Segments" respectively. The "Layers" pillar contains seven divisions arranged top to bottom and labeled "app", "processes", "pages", "widgets", "features", "entities", and "shared". The "processes" division is crossed out. The "entities" division is connected to the second pillar "Slices" in a way that conveys that the second pillar is the content of "entities". The "Slices" pillar contains three divisions arranged top to bottom and labeled "user", "post", and "comment". The "post" division is connected to the third pillar "Segments" in the same way such that it's the content of "post". The "Segments" pillar contains three divisions, arranged top to bottom and labeled "ui", "model", and "api".](/img/visual_schema.jpg) + ![Hierarchy of FSD concepts, described below](/img/visual_schema.jpg)
-

Three pillars, labeled left to right as "Layers", "Slices", and "Segments" respectively.

+

Pictured above: three pillars, labeled left to right as "Layers", "Slices", and "Segments" respectively.

The "Layers" pillar contains seven divisions arranged top to bottom and labeled "app", "processes", "pages", "widgets", "features", "entities", and "shared". The "processes" division is crossed out. The "entities" division is connected to the second pillar "Slices" in a way that conveys that the second pillar is the content of "entities".

The "Slices" pillar contains three divisions arranged top to bottom and labeled "user", "post", and "comment". The "post" division is connected to the third pillar "Segments" in the same way such that it's the content of "post".

The "Segments" pillar contains three divisions, arranged top to bottom and labeled "ui", "model", and "api".

-### Layers +### Layers {#layers} Layers are standardized across all FSD projects. You don't have to use all of the layers, but their names are important. There are currently seven of them (from top to bottom): 1. App\* — everything that makes the app run — routing, entrypoints, global styles, providers. 2. Processes (deprecated) — complex inter-page scenarios. -3. Pages — full pages or large parts of a page in nested routing scenarios. +3. Pages — full pages or large parts of a page in nested routing. 4. Widgets — large self-contained chunks of functionality or UI, usually delivering an entire use case. -5. Features — _reusable_ implementations of entire product features, i.e. actions that bring business value to the user. +5. Features — _reused_ implementations of entire product features, i.e. actions that bring business value to the user. 6. Entities — business entities that the project works with, like `user` or `product`. -7. Shared\* — reusable functionality, ideally detached from the specifics of the project/business. +7. Shared\* — reusable functionality, especially when it's detached from the specifics of the project/business, though not necessarily. -_\* — Layers App and Shared are made up of segments directly, while other layers are made up of slices that are then made up of segments._ +_\* — these layers, App and Shared, unlike the other layers, don't have slices, and are made up of segments directly._ The trick with layers is that modules on one layer can only know about and import from modules from the layers strictly below. -### Slices +### Slices {#slices} Next up are slices, which partition the code by business domain. You're free to choose any names for them, and create as many as you wish. Slices make your codebase easier to navigate by keeping logically related modules close together. Slices cannot use other slices on the same layer, and that helps with high cohesion and low coupling. -### Segments +### Segments {#segments} -Slices, as well as layers App and Shared, consist of segments, and segments group your code by its purpose. Segment names are not constrained by standard, but there are several conventional names for the most common purposes: +Slices, as well as layers App and Shared, consist of segments, and segments group your code by its purpose. Segment names are not constrained by the standard, but there are several conventional names for the most common purposes: - `ui` — self-explanatory - `api` — also self-explanatory @@ -93,15 +93,15 @@ Slices, as well as layers App and Shared, consist of segments, and segments grou - `lib` — library code that's only used within this slice - `config` — configuration files and feature flags -Usually these segments are enough for most layers, you would only create your own segments in Shared or App, but this is not a rule that you have to obey. +Usually these segments are enough for most layers, you would only create your own segments in Shared or App, but this is not a rule. -## Advantages +## Advantages {#advantages} - **Uniformity** Since the structure is standardized, projects become more uniform, which makes onboarding new members easier for the team. - **Stability in face of changes and refactoring** - A module on a layer cannot use other modules on the same layer, or the layers above. + A module on one layer cannot use other modules on the same layer, or the layers above. This allows you to make isolated modifications without unforeseen consequences to the rest of the app. - **Controlled reuse of logic** @@ -111,11 +111,11 @@ Usually these segments are enough for most layers, you would only create your ow - **Orientation to business and users needs** The app is split into business domains and usage of the business language is encouraged in naming, so that you can do useful product work without fully understanding all other unrelated parts of the project. -## Incremental adoption +## Incremental adoption {#incremental-adoption} -If you have an existing codebase that you want to migrate to FSD, we suggest this strategy. We found it useful in our own migration experience. +If you have an existing codebase that you want to migrate to FSD, we suggest the following strategy. We found it useful in our own migration experience. -1. Start by slowly moving code module-by-module to the App and Shared layers to create a foundation. Usually, these layers are the smallest. +1. Start by slowly shaping up the App and Shared layers module-by-module to create a foundation. Usually, these layers are the smallest. 2. Distribute all of the existing UI across Widgets and Pages using broad strokes, even if they have dependencies that violate the rules of FSD. @@ -123,7 +123,16 @@ If you have an existing codebase that you want to migrate to FSD, we suggest thi It's advised to refrain from adding new large entities while refactoring or refactoring only certain parts of the project. +## Next steps {#next-steps} + +- **Want to get a good grasp of how to think in FSD?** Check out the [Tutorial][tutorial]. +- **Prefer to learn from examples?** We have a lot in the [Examples][examples] section. +- **Have questions?** Drop by our [Telegram chat][ext-telegram] and get help from the community. + +[tutorial]: /docs/get-started/tutorial [examples]: /examples [migration]: /docs/guides/migration/from-legacy [ext-steiger]: https://github.com/feature-sliced/steiger [ext-tools]: https://github.com/feature-sliced/awesome?tab=readme-ov-file#tools +[ext-telegram]: https://t.me/feature_sliced + diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.md b/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.md deleted file mode 100644 index bf7653d02..000000000 --- a/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Обзор - -## Подходит ли это мне? {#is-it-right-for-me} - -FSD подходит для проектов и команд любого размера с некоторыми оговорками: - -- Эта методология исключительно для фронтенда. Если вы ищете архитектуру для бэкенда, обратите внимание на [Clean Architecture][refs-clean-architecture]. -- Эта методология исключительно для приложений, а не для библиотек или UI-китов. Если вы ищете архитектуру для крупной библиотеки компонентов, рекомендуем взять пример с [Material UI][ext-material-ui]. -- Если вы разрабатываете очень простое приложение из одной странички на FSD, преимущества методологии вряд ли понадобятся, а вот разработка может замедлиться. Однако, FSD помогает стандартизированно мыслить о фронтенд-приложениях, так что смело используйте даже на маленьких проектах, если знаете, для чего она вам. -- Огромное приложение, соизмеримое с админ-панелью Google Cloud, потребует специализированной архитектуры. FSD в данном случае может выступать в качестве отправной точки. - -Методология не привязана к конкретному языку программирования, UI-фреймворку или менеджеру состояния — подойдет любой (см. [примеры использования][refs-examples]). - -Если у вас уже есть проект, не переживайте — FSD можно внедрять постепенно. Главный вопрос, который стоит задать команде: "**Есть ли боль** при разработке проекта?" Если боли нет, возможно, переход делать не стоит. Руководство по миграции см. в разделе [Миграция][refs-migration]. - - -## Основы {#basics} - -Проект на FSD состоит из слоев (layers), каждый слой состоит из слайсов (slices) и каждый слайс состоит из сегментов (segments). - -![themed--scheme](/img/visual_schema.jpg) - -**Слои** стандартизированы во всех проектах и расположены вертикально. Модули на одном слое могут взаимодействовать лишь с модулями, находящимися на слоях строго ниже. На данный момент слоев семь (сверху вниз): - -1. `app` — настройки, стили и провайдеры для всего приложения. -2. `processes` (процессы, устаревший слой) — сложные сценарии, покрывающие несколько страниц. - (например, авторизация). -3. `pages` (страницы) — композиционный слой для сборки полноценных страниц из сущностей, фич и виджетов. -4. `widgets` (виджеты) — композиционный слой для соединения сущностей и фич в самостоятельные блоки. - (например, IssuesList, UserProfile). -5. `features` (фичи) — взаимодействия с пользователем, действия, которые несут бизнес-ценность для пользователя. - (например, SendComment, AddToCart, UsersSearch). -6. `entities` (сущности) — бизнес-сущности. - (например, User, Product, Order). -7. `shared` — переиспользуемый код, не имеющий отношения к специфике приложения/бизнеса. - (например, UIKit, libs, API). - -Затем есть **слайсы**, разделяющие код по предметной области. Они группируют логически связанные модули, что облегчает навигацию по кодовой базе. Слайсы не могут использовать другие слайсы на том же слое, что обеспечивает высокий уровень [_связности_][refs-wiki-cohesion] (cohesion) при низком уровне [_зацепления_][refs-wiki-coupling] (coupling). - -В свою очередь, каждый слайс состоит из **сегментов**. Это маленькие модули, главная задача которых — разделить код внутри слайса по техническому назначению. Самые распространенные сегменты — `ui`, `model` (store, actions), `api` и `lib` (utils/hooks), но в вашем слайсе может не быть каких-то сегментов, могут быть другие, по вашему усмотрению. - -:::note - -В большинстве случаев [рекомендуется][ext-disc-api] располагать `api` и `config` только в shared-слое - -::: - -## Пример {#example} - -Рассмотрим приложение социальной сети. - -* `app/` содержит настройку роутера, глобальные хранилища и стили. -* `pages/` содержит компоненты роутов на каждую страницу в приложении, преимущественно композирующие, по возможности, без собственной логики. - -В рамках этого приложения рассмотрим карточку поста в ленте новостей. - -* `widgets/` содержит "собранную" карточку поста, с содержимым и интерактивными кнопками, в которые вшиты запросы к бэкенду. -* `features/` содержит всю интерактивность карточки (например, кнопку лайка) и логику обработки этой интерактивности. -* `entities/` содержит скелет карточки со слотами под интерактивные элементы. Компонент, демонстрирующий автора поста, также находится в этой папке, но в другом слайсе. - -### Преимущества {#advantages} - -- **Единообразие** - Код распределяется согласно области влияния (слой), предметной области (слайс) и техническому назначению (сегмент). - Благодаря этому архитектура стандартизируется и становится более простой для ознакомления. - -- **Контролируемое переиспользование логики** - Каждый компонент архитектуры имеет свое назначение и предсказуемый список зависимостей. - Благодаря этому сохраняется баланс между соблюдением принципа **DRY** и возможностью адаптировать модуль под разные цели. - -- **Устойчивость к изменениям и рефакторингу** - Один модуль не может использовать другой модуль, расположенный на том же слое или на слоях выше. - Благодаря этому приложение можно изолированно модифицировать под новые требования без непредвиденных последствий. - -- **Ориентированность на потребности бизнеса и пользователей** - Разбиение приложения по бизнес-доменам помогает глубже понимать, структурировать и находить фичи проекта. - -## Постепенное внедрение {#incremental-adoption} - -Сила FSD в _структурированной_ декомпозиции. В лучшей форме, FSD позволяет найти место для любой части кода почти однозначно. Однако, уровень декомпозиции — это параметр, и любая команда может подстроить его для оптимального баланса между легкостью внедрения и преимуществами. - -Предлагаем следующую стратегию для миграции существующей кодовой базы на FSD, проверенную опытом: - -1. Вырезать слои `app` и `shared`, чтобы иметь опору для последующих этапов. Эти слои получатся тонкими и простыми, пусть такими и остаются. - -2. Вынести весь интерфейс, связанный с бизнесом, распределить по виджетам и страницам, даже если в них пока что будут зависимости, нарушающие правила FSD. - -3. Постепенно наращивать степень декомпозиции, выделяя `features` и `entities`. Превращать страницы и виджеты из перегруженных логикой слоёв в чисто композиционные слои. - -Рекомендуется воздержаться от добавления новых крупных сущностей во время рефакторинга, а также рефакторинга по частям. - -[refs-clean-architecture]: https://medium.com/codex/clean-architecture-for-dummies-df6561d42c94 -[ext-disc-api]: https://github.com/feature-sliced/documentation/discussions/66 -[ext-material-ui]: https://github.com/mui/material-ui -[refs-examples]: /examples -[refs-migration]: /docs/guides/migration/from-legacy -[refs-wiki-cohesion]: https://ru.wikipedia.org/wiki/%D0%A1%D0%B2%D1%8F%D0%B7%D0%BD%D0%BE%D1%81%D1%82%D1%8C_(%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) -[refs-wiki-coupling]: https://ru.wikipedia.org/wiki/%D0%97%D0%B0%D1%86%D0%B5%D0%BF%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5_(%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.mdx new file mode 100644 index 000000000..6e6510736 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.mdx @@ -0,0 +1,138 @@ +--- +sidebar_position: 1 +--- + +# Обзор {#overview} + +**Feature-Sliced Design** (FSD) — это архитектурная методология для проектирования фронтенд-приложений. Проще говоря, это набор правил и соглашений по организации кода. Главная цель этой методологии — сделать проект понятнее и стабильнее в условиях постоянно меняющихся бизнес-требований. + +Помимо набора правил, FSD — это также целый инструментарий. У нас есть [линтер][ext-steiger] для проверки архитектуры вашего проекта, [генераторы папок][ext-tools] через CLI или IDE, а также богатая библиотека [примеров][examples]. + +## Подходит ли она мне? {#is-it-right-for-me} + +FSD можно внедрять в проектах и командах любого размера. Она подходит для вашего проекта, если: + +- Вы занимаетесь **фронтенд**-разработкой (интерфейсы для сайтов, мобильных/десктопных приложений, и т. д.) +- Вы разрабатываете **приложение**, а не библиотеку + +И это все! Нет никаких ограничений на используемый вами язык программирования, фреймворк или стейт-менеджер. Ещё вы можете внедрять FSD постепенно, использовать его в монорепозиториях, и масштабировать его хоть до луны, разделяя ваше приложение на пакеты и внедряя FSD в каждом из них по отдельности. + +Если у вас уже есть архитектура, и вы подумываете перейти на FSD, убедитесь, что текущая архитектура **создает проблемы** в вашей команде. Например, если ваш проект стал слишком большим и переплетённым, чтоб эффективно разрабатывать новые функции, или если вы ожидаете, что в команду придет много новых участников. Если текущая архитектура работает, возможно, ее не стоит менять. Но если вы всё же решите перейти, ознакомьтесь с рекомендациями в разделе [Миграция][migration]. + +## Базовый пример {#basic-example} + +Вот простой проект, реализующий FSD: + +- `📁 app` +- `📁 pages` +- `📁 shared` + +Эти папки верхнего уровня называются _слоями_. Давайте посмотрим глубже: + +- `📂 app` + - `📁 routes` + - `📁 analytics` +- `📂 pages` + - `📁 home` + - `📂 article-reader` + - `📁 ui` + - `📁 api` + - `📁 settings` +- `📂 shared` + - `📁 ui` + - `📁 api` + +Папки внутри `📂 pages` называются _слайсами_. Они делят слой по домену (в данном случае, по страницам). + +Папки внутри `📂 app`, `📂 shared` и `📂 pages/article-reader` называются _сегментами_, и они делят слайсы (или слои) по техническому назначению, то есть по тому, для чего предназначен код. + +## Понятия {#concepts} + +Слои, слайсы и сегменты образуют иерархию, как показано на схеме: + +
+ ![Иерархия концепций FSD, описанная ниже](/img/visual_schema.jpg) + +
+

На картинке выше: три столбика, обозначенные слева направо как "Слои", "Слайсы" и "Сегменты" соответственно.

+

Столбик "Слои" содержит семь делений, расположенных сверху вниз и обозначенных "app", "processes", "pages", "widgets", "features", "entities" и "shared". Деление "processes" зачеркнуто. Деление "entities" соединено со вторым столбиком "Слайсы", показывая, что второй столбик является содержимым "entities".

+

Столбик "Слайсы" содержит три деления, расположенных сверху вниз и обозначенных "user", "post" и "comment". Деление "post" соединено со столбиком "Сегменты" таким же образом, что и содержимое "post".

+

Столбик "Сегменты" содержит три деления, расположенных сверху вниз и обозначенных "ui", "model" и "api".

+
+
+ +### Слои {#layers} + +Слои стандартизированы во всех проектах FSD. Вам не обязательно использовать все слои, но их названия важны. На данный момент их семь (сверху вниз): + +1. App\* — всё, благодаря чему приложение запускается — роутинг, точки входа, глобальные стили, провайдеры и т. д. +2. Processes (процессы, устаревший) — сложные межстраничные сценарии. +3. Pages (страницы) — полные страницы или большие части страницы при вложенном роутинге. +4. Widgets (виджеты) — большие самодостаточные куски функциональности или интерфейса, обычно реализующие целый пользовательский сценарий. +5. Features (фичи) — _повторно используемые_ реализации целых фич продукта, то есть действий, приносящих бизнес-ценность пользователю. +6. Entities (сущности) — бизнес-сущности, с которыми работает проект, например `user` или `product`. +7. Shared\* — переиспользуемый код, особенно когда она отделена от специфики проекта/бизнеса, хотя это не обязательно. + +_\* — эти слои, App и Shared, в отличие от других слоев, не имеют слайсов и состоят из сегментов напрямую._ + +Фишка слоев в том, что модули на одном слое могут знать только о модулях со слоев строго ниже, и как следствие, импортировать только с них. + +### Слайсы {#slices} + +Дальше идут слайсы, они делят слой по предметной области. Вы можете называть ваши слайсы как угодно, и создавать их сколько угодно. Слайсы помогают не теряться в проекте, потому что группируют тесно связанный по смыслу код. + +Слайсы не могут использовать другие слайсы на том же слое, и это обеспечивает сильную связанность кода внутри слайса и слабую сцепленность между слайсами. + +### Сегменты {#segments} + +Слайсы, а также слои App и Shared, состоят из сегментов, а сегменты группируют код по его назначению. Имена сегментов не зафиксированы стандартом, но существует несколько общепринятых имен для наиболее распространенных целей: + +- `ui` — говорит само за себя +- `api` — тоже говорит само за себя +- `model` — модель данных: схемы валидации, интерфейсы, хранилища и бизнес-логика. +- `lib` — библиотечный код, который используется только внутри этого слайса. +- `config` — файлы конфигурации и фиче-флаги. + +Обычно этих сегментов достаточно для большинства слоев, поэтому свои собственные сегменты обычно создают только в Shared или App, но это не жёсткое правило. + +## Преимущества {#advantages} + +- **Однородность** + Поскольку структура стандартизирована, проекты становятся более единообразными, что облегчает набор новых участников в команду. + +- **Устойчивость к изменениям и рефакторингу** + Модуль на одном слое не может использовать другие модули на том же слое или слоях выше. + Это позволяет вам вносить изолированные правки без непредвиденных последствий для остальной части приложения. + +- **Контролируемое переиспользование логики** + В зависимости от уровня вы можете сделать код либо очень переиспользуемым, либо очень локальным. + Это сохраняет баланс между соблюдением принципа **DRY** и практичностью. + +- **Ориентация на потребности бизнеса и пользователей** + Приложение разделено на бизнес-домены, и при именовании поощряется использование терминологии бизнеса, чтобы вы могли делать полезную работу в продукте, не вникая полностью во все другие несвязанные части проекта. + +## Постепенное внедрение {#incremental-adoption} + +Если у вас есть существующая кодовая база, которую вы хотите перенести на FSD, мы предлагаем следующую стратегию. На нашем собственном опыте миграции она хорошо себя зарекомендовала. + +1. Начните постепенно формировать слои App и Shared, чтобы создать фундамент. Обычно эти слои самые маленькие. + +2. Раскидайте весь существующий интерфейсный код по виджетам и страницам, даже если у них пока что есть зависимости, нарушающие правила FSD. + +3. Постепенно исправляйте нарушения правил на импорты, а по ходу извлекайте сущности и, возможно, фичи. + +Рекомендуется воздержаться от добавления новых крупных сущностей во время рефакторинга, а также рефакторинга по частям. + +## Следующие шаги {#next-steps} + +- **Хотите разобраться в том, как мыслить по-FSD-шному?** Прочтите [Туториал][tutorial]. +- **Предпочитаете учиться на примерах?** У нас их много в разделе [Примеры][examples]. +- **Есть вопросы?** Загляните в наш [чат Telegram][ext-telegram] и спросите у сообщества. + +[tutorial]: /docs/get-started/tutorial +[examples]: /examples +[migration]: /docs/guides/migration/from-legacy +[ext-steiger]: https://github.com/feature-sliced/steiger +[ext-tools]: https://github.com/feature-sliced/awesome?tab=readme-ov-file#tools +[ext-telegram]: https://t.me/feature_sliced + From a5d7c5dc20c271ea7c641697f0775134bd9a7d40 Mon Sep 17 00:00:00 2001 From: Lev Chelyadinov Date: Thu, 27 Jun 2024 20:30:20 +0200 Subject: [PATCH 3/3] Make some corrections --- .../current/get-started/overview.mdx | 14 ++++++------ .../current/get-started/overview.mdx | 22 +++++++++---------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx b/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx index 930b330c4..a35f52106 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx +++ b/i18n/en/docusaurus-plugin-content-docs/current/get-started/overview.mdx @@ -2,7 +2,7 @@ sidebar_position: 1 --- -# Overview {#overview} +# Overview **Feature-Sliced Design** (FSD) is an architectural methodology for scaffolding front-end applications. Simply put, it's a compilation of rules and conventions on organizing code. The main purpose of this methodology is to make the project more understandable and stable in the face of ever-changing business requirements. @@ -87,11 +87,11 @@ Slices cannot use other slices on the same layer, and that helps with high cohes Slices, as well as layers App and Shared, consist of segments, and segments group your code by its purpose. Segment names are not constrained by the standard, but there are several conventional names for the most common purposes: -- `ui` — self-explanatory -- `api` — also self-explanatory -- `model` — the data model: schemas, interfaces, stores, and business logic -- `lib` — library code that's only used within this slice -- `config` — configuration files and feature flags +- `ui` — everything related to UI display: UI components, date formatters, styles, etc. +- `api` — backend interactions: request functions, data types, mappers, etc. +- `model` — the data model: schemas, interfaces, stores, and business logic. +- `lib` — library code that other modules on this slice need. +- `config` — configuration files and feature flags. Usually these segments are enough for most layers, you would only create your own segments in Shared or App, but this is not a rule. @@ -115,7 +115,7 @@ Usually these segments are enough for most layers, you would only create your ow If you have an existing codebase that you want to migrate to FSD, we suggest the following strategy. We found it useful in our own migration experience. -1. Start by slowly shaping up the App and Shared layers module-by-module to create a foundation. Usually, these layers are the smallest. +1. Start by slowly shaping up the App and Shared layers module-by-module to create a foundation. 2. Distribute all of the existing UI across Widgets and Pages using broad strokes, even if they have dependencies that violate the rules of FSD. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.mdx index 6e6510736..776f75a0b 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/get-started/overview.mdx @@ -2,13 +2,13 @@ sidebar_position: 1 --- -# Обзор {#overview} +# Обзор **Feature-Sliced Design** (FSD) — это архитектурная методология для проектирования фронтенд-приложений. Проще говоря, это набор правил и соглашений по организации кода. Главная цель этой методологии — сделать проект понятнее и стабильнее в условиях постоянно меняющихся бизнес-требований. Помимо набора правил, FSD — это также целый инструментарий. У нас есть [линтер][ext-steiger] для проверки архитектуры вашего проекта, [генераторы папок][ext-tools] через CLI или IDE, а также богатая библиотека [примеров][examples]. -## Подходит ли она мне? {#is-it-right-for-me} +## Подходит ли FSD мне? {#is-it-right-for-me} FSD можно внедрять в проектах и командах любого размера. Она подходит для вашего проекта, если: @@ -87,35 +87,35 @@ _\* — эти слои, App и Shared, в отличие от других сл Слайсы, а также слои App и Shared, состоят из сегментов, а сегменты группируют код по его назначению. Имена сегментов не зафиксированы стандартом, но существует несколько общепринятых имен для наиболее распространенных целей: -- `ui` — говорит само за себя -- `api` — тоже говорит само за себя +- `ui` — всё, что связано с отображением: UI-компоненты, форматтеры дат, стили и т.д. +- `api` — взаимодействие с бэкендом: функции запросов, типы данных, мапперы. - `model` — модель данных: схемы валидации, интерфейсы, хранилища и бизнес-логика. -- `lib` — библиотечный код, который используется только внутри этого слайса. +- `lib` — библиотечный код, который нужен другим модулям этого слайса. - `config` — файлы конфигурации и фиче-флаги. Обычно этих сегментов достаточно для большинства слоев, поэтому свои собственные сегменты обычно создают только в Shared или App, но это не жёсткое правило. ## Преимущества {#advantages} -- **Однородность** +- **Однородность** Поскольку структура стандартизирована, проекты становятся более единообразными, что облегчает набор новых участников в команду. - **Устойчивость к изменениям и рефакторингу** - Модуль на одном слое не может использовать другие модули на том же слое или слоях выше. + Модуль на одном слое не может использовать другие модули на том же слое или слоях выше. Это позволяет вам вносить изолированные правки без непредвиденных последствий для остальной части приложения. -- **Контролируемое переиспользование логики** - В зависимости от уровня вы можете сделать код либо очень переиспользуемым, либо очень локальным. +- **Контролируемое переиспользование логики** + В зависимости от уровня вы можете сделать код либо очень переиспользуемым, либо очень локальным. Это сохраняет баланс между соблюдением принципа **DRY** и практичностью. -- **Ориентация на потребности бизнеса и пользователей** +- **Ориентация на потребности бизнеса и пользователей** Приложение разделено на бизнес-домены, и при именовании поощряется использование терминологии бизнеса, чтобы вы могли делать полезную работу в продукте, не вникая полностью во все другие несвязанные части проекта. ## Постепенное внедрение {#incremental-adoption} Если у вас есть существующая кодовая база, которую вы хотите перенести на FSD, мы предлагаем следующую стратегию. На нашем собственном опыте миграции она хорошо себя зарекомендовала. -1. Начните постепенно формировать слои App и Shared, чтобы создать фундамент. Обычно эти слои самые маленькие. +1. Начните постепенно формировать слои App и Shared, чтобы создать фундамент. 2. Раскидайте весь существующий интерфейсный код по виджетам и страницам, даже если у них пока что есть зависимости, нарушающие правила FSD.