### Module Structure Example Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/overview.md Illustrates a typical directory structure for a module within the application, showing the 'features' and 'domain' subdirectories. ```directory-structure ├── app/ ├── screens/ ├── modules/ | └── payment/ | | ├── features/ | | ├── domain/ | | └── index.ts ├── data/ └── shared/ ``` -------------------------------- ### Example Project Structure Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/overview.md Illustrates a typical project directory structure for an application, showing the placement of core directories like app, screens, modules, data, and shared. ```tree ├── app/ ├── screens/ ├── modules/ ├── data/ └── shared/ ``` -------------------------------- ### Example Module Structure Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/overview.md Demonstrates the structure of a 'Module' within the application, typically representing a business domain. It includes 'features' and 'domain' segments for business logic. ```tree ├── app/ ├── screens/ ├── modules/ | └── payment/ | | ├── features/ | | ├── domain/ | | └── index.ts ├── data/ └── shared/ ``` -------------------------------- ### Example Data Layer Structure Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/overview.md Presents the directory structure for the 'Data' layer, which manages data retrieval, aggregation, and formatting. It shows the 'repositories' and 'sources' segments. ```tree ├── app/ ├── screens/ ├── modules/ ├── data/ | ├── repositories/ | ├── sources/ | └── index.ts └── shared/ ``` -------------------------------- ### Valid vs. Invalid Naming for Mount/Unmount Methods Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/features/ui-store.md This section highlights the importance of unambiguous naming for UIStore methods that correspond to component lifecycle events. It provides valid examples using `mount` and `unmount` and invalid examples using `init` and `destroy` to ensure clarity. ```tsx import { useLocalObservable } from 'mobx-react-lite'; import { createUIStore } from './ui-store'; const List = () => { const containerRef = useRef(); const { mount, unmount } = useLocalObservable(createUIStore); useEffect(() => { mount(containerRef); return unmount; }, []); ... }; ``` ```tsx import { useLocalObservable } from 'mobx-react-lite'; import { createUIStore } from './ui-store'; const List = () => { const containerRef = useRef(); const { init, destroy } = useLocalObservable(createUIStore); useEffect(() => { init(containerRef); return destroy; }, []); ... }; ``` -------------------------------- ### Screen Assembly Example (React) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/overview.md Demonstrates how application screens are constructed by integrating features from various modules. This layer binds features to application routes and handles routing environment interactions. ```React ├── screens/ | ├── feedback/ | ├── no-access/ | ├── not-found/ | ├── popular-goods/ | ├── new-goods/ | | ├── new-goods.tsx | | ├── store/ | | └── index.ts | └── index.ts ``` -------------------------------- ### Improve formatPriceToView Test Case Naming Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/antipatterns.md Demonstrates how to improve the specificity of a test case for the `formatPriceToView` function. The 'Invalid' example uses a vague description ('Works correctly with zero'), while the 'Valid' example provides a clearer description ('For zero returns default text'), making the test's purpose more understandable. ```typescript describe('formatPriceToView', () => { it('Works correctly with zero', () => { expect(formatPriceToView(0)).toBe('Free'); }); }); ``` ```typescript describe('formatPriceToView', () => { it('For zero returns default text', () => { expect(formatPriceToView(0)).toBe('Free'); }); }); ``` -------------------------------- ### Module Dependency Control Example Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/overview.md Demonstrates how to control incoming dependencies and define a module's public API using 'external.ts' and 'index.ts' files respectively. ```directory-structure ├── app/ ├── screens/ ├── modules/ | ├── payment/ | | ├── features/ | | ├── domain/ | | ├── external.ts # Incoming dependencies | | └── index.ts # Module's public API ├── data/ └── shared/ ``` -------------------------------- ### Example Project Structure Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/intro.md Illustrates a typical directory structure for a frontend project following the described architectural methodology. It helps in organizing code by feature, data, and shared components. ```tree ├── app/ ├── screens/ ├── modules/ ├── data/ └── shared/ ``` -------------------------------- ### Example Module Feature Structure (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/features/overview.md Illustrates the directory structure for a 'payment' module featuring 'payment-switch', 'card-payment', and 'cash-payment' features. Each feature contains its own logic and components. ```typescript ├── app/ ├── screens/ ├── modules/ | └── payment/ | | ├── features/ | | | ├── payment-switch/ | | | ├── card-payment/ | | | ├── cash-payment/ | | | └── index.ts | | ├── domain/ | | └── index.ts ├── data/ └── shared/ ``` -------------------------------- ### Testing Infrastructure - Available Behavior Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/test-case-formatting.md This example illustrates testing based on available behavior within the testing infrastructure. It presents a test case that verifies content display when a header element is clicked. ```javascript it('Content is displayed when header is clicked') ``` -------------------------------- ### Shopping Cart Payment Scenario Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/test-case-formatting.md Provides a requirements example for testing business logic, specifically focusing on the shopping cart payment process. It outlines user actions and system responses. ```tsx # Shopping Cart Payment ## Main Scenario 1. User added goods to cart 2. User went to cart 3. System displays list of goods added to cart 4. If user has saved card, then clicking "Pay" button: 1. Payment of goods through saved card starts in background 2. System displays modal window to show payment status 5. System redirects user to popular goods page ``` -------------------------------- ### Application Layer Structure (React) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/overview.md Provides an example of the Application layer structure for a React project. This layer is environment-dependent, handling routing, initialization, and configuration of the application and its services. ```React ├── app/ | ├── routing/ | └── app.tsx ``` -------------------------------- ### Application Layer Structure (Next.js) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/overview.md Illustrates the Application layer structure in a Next.js project, where the 'pages' directory serves this role. It manages routing and application setup specific to the Next.js framework. ```Next.js ├── pages/ # pages is the application layer (Next.js specificity) | ├── index.tsx | ├── _app.tsx ``` -------------------------------- ### Initialize CartRepository with Fake Sources Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/data.md This TypeScript code demonstrates initializing the CartRepository with fake network sources. This setup is part of the Contract First approach, allowing development to proceed without a live backend. ```tsx export const cartRepository = new CartRepository( fakeCartNetworkSources, cacheService, ); ``` -------------------------------- ### Abstract Browser API Interaction in UIStore Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/features/ui-store.md This snippet demonstrates abstracting Browser API interactions within UIStore for easier testing. It shows examples of using `LocalStorageService` and `IntersectionObserver` through dependency injection, allowing for mock implementations during testing. ```ts export class UIStore { constructor( private readonly storage: LocalStorageService, ) { makeAutoObservable(this); } public setSearch = (search: string) => { this.storage.setItem('search', search) } } ``` ```ts export class UIStore { constructor( private readonly intersectionObserver: IntersectionObserver, ) { makeAutoObservable(this); } ... public mount = (itemRef: Ref) => { this.intersectionObserver(this.showAction, { root: itemRef.current }) } } ``` -------------------------------- ### Testing Infrastructure - Reaction to Input Parameters Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/test-case-formatting.md This example shows how to test the reaction of a system under test (SUT) to input parameters. It provides a test case that checks if content is displayed when an 'isExpanded' parameter is set to true. ```javascript it('Content is displayed when isExpanded=true') ``` -------------------------------- ### Feature Structure Example (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/overview.md Illustrates the typical directory structure for a feature within a module, including UI components, feature logic, styles, and other necessary entities. The UI component is solely for rendering, with all logic externalized. ```TypeScript ├── modules/ | └── payment/ | | ├── features/ | | | ├── payment-switch/ | | | ├── card-payment/ | | | ├── cash-payment/ | | | └── index.ts | | ├── domain/ | | └── index.ts ``` -------------------------------- ### Valid Class Directory Naming Convention Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/classes.md Shows the correct way to name directories containing classes, which must start with a capital letter to clearly identify them as class directories. ```tree ├── services/ | |── FileService/ | | |── file-service.ts | | └── index.ts | |── ErrorService/ | | |── error-service.ts | | └── index.ts | └── index.ts ``` -------------------------------- ### Domain Logic Structure Example (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/overview.md Shows the organization of pure business logic within the Domain layer. This includes reusable logic, data interaction, types, constants, and stores, ensuring separation from UI concerns. ```TypeScript ├── modules/ | └── cart/ | | ├── features/ | | └── domain/ | | | ├── services/ | | | ├── stores/ | | | | ├── cart-store/ | | | | └── index.ts | | | ├── utils/ | | | ├── types/ | | | ├── constants/ | | | └── index.ts | | └── index.ts ``` -------------------------------- ### DI for Class Dependencies in Testing Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/mock-and-stub.md Demonstrates how to use Dependency Injection (DI) for class dependencies in a testing scenario. It shows the setup of a `CartScreenStore` with mocked dependencies and verifies that a method is called upon interaction. ```tsx export class CartScreenStore { private readonly modalStore = createFlagStore(); constructor( private readonly cardPaymentStore: CardPaymentStore, private readonly routerService: Router, ) {} ... } ...describe('CartScreenStore', () => { it('Payment process starts in background when modal is opened', () => { const cartPaymentStoreMock = mock(); const sut = new CartScreenStore(cartPaymentStoreMock, createRouterMock()); sut.openModal(); expect(cartPaymentStoreMock.pay).toBeCalled(); }); }; ``` -------------------------------- ### Formatting Props for Components (Valid TSX) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/features/ui-logic.md This valid example demonstrates how props for a child component are pre-formatted by the `UIStore`. The component then simply passes these formatted props (`viewerTitle`, `descriptions`) to the `Viewer`. ```tsx import { useLocalObservable } from 'mobx-react-lite'; import { createUIStore } from './ui-store'; export const Card = () => { const { viewerTitle, descriptions } = useLocalObservable(createUIStore); return ( ); }; ``` -------------------------------- ### Using UIStore for Alert Messages in a React Component (TSX) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/guides/render-component-in-store.md This React component example demonstrates how to use the `UIStore` to manage and display an alert message. It utilizes `useLocalObservable` to get an instance of the `UIStore`. The `mount` function is called within a `useEffect` hook to set a `message` (a `ReactNode` containing a `` component) as the alert. The `send` function would then be used to trigger the notification. ```tsx import React, { useEffect } from 'react'; // Assuming useLocalObservable, createUIStore, Message, and Notify are defined elsewhere // declare const useLocalObservable: any; // declare const createUIStore: any; // declare const Message: React.FC<{ variant?: string }>; const AlertComponent = () => { // const { mount, send } = useLocalObservable(createUIStore); const mount = (message: React.ReactNode) => { console.log('Mounting message:', message); }; const send = () => { console.log('Sending alert'); }; const message = Hello; useEffect(() => { mount(message); }, [mount, message]); // Example of how to trigger the send function, e.g., via a button click // const handleClick = () => { // send(); // }; return (
{/* */}

Alert component is set up.

); }; export default AlertComponent; ``` -------------------------------- ### REST Data Retrieval Example (TypeScript/TSX) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/data.md Provides an example of a data source using REST to retrieve tariff data. It utilizes an `apiHttpClient` and defines the DTO for the response. ```tsx import { apiHttpClient } from '@shared'; import { TariffNetworkSourcesDTO } from './dto'; export const tariffsNetworkSources = { getTariffs: () => apiHttpClient.get('/tariffs'), }; ``` -------------------------------- ### TypeScript: Describe Nesting in Tests Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/testing/structure.md Illustrates the allowed structure for nesting 'describe' blocks in TypeScript tests. It shows a valid example with one level of nesting and an invalid example with deeper nesting. ```ts describe('CartRepository', () => { describe('Total item counter', () => { it('Increases when adding items before successful request completion'); it('Reverts to original when item addition request fails'); it('Decreases when removing items before successful request completion'); it('Reverts to original when item removal request fails'); }); }); ``` ```ts describe('CartRepository', () => { describe('Total item counter', () => { describe('When adding items', () => { it('Increases before successful request completion'); it('Reverts to original when request fails'); }); describe('When removing items', () => { it('Decreases before successful request completion'); it('Reverts to original when request fails'); }); }); }); ``` -------------------------------- ### Directory Structure for Frontend Tests Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/overview.md This example demonstrates a common directory structure for frontend applications, showing how to place test files (`.test.ts`) adjacent to their corresponding source files (`.ts`) to maintain a clear visual connection between the System Under Test (SUT) and its tests. ```bash ├── data/ | └── repositories/ | | └── user-repository/ | | | ├── user-repository.ts | | | ├── user-repository.test.ts | | | └── index.ts ``` -------------------------------- ### GoodsListStore Initialization and Data Formatting Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/data.md Demonstrates the initialization of GoodsListStore with a BookRepository and how it formats book data for display, including price formatting and creating associated stores. This snippet is crucial for understanding data transformation within the store. ```tsx class GoodsListStore { constructor(private readonly bookRepository: BookRepository) { makeAutoObservable(this); } private get listQuery() { return this.bookRepository.getBookListQuery(); } public get list(): ListItem[] { const data = this.listQuery.data?.data || []; return data.map(({ id, name, price }) => ({ id, name, price: formatPriceToView(price), store: createProductCartManagerStore(id), })); } } ``` -------------------------------- ### Shared Layer Usage Example (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/features/dependencies.md Provides an example of how features can directly import and utilize utilities and components from the shared layer. This highlights the unrestricted access features have to common, reusable code. ```typescript import { formatDate } from '@shared/utils/format-date'; import { Button } from '@shared/ui/components/button'; ``` -------------------------------- ### TypeScript: AAA Pattern in Tests Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/testing/structure.md Illustrates the Arrange-Act-Assert (AAA) pattern in TypeScript tests. It provides a valid example demonstrating the pattern without explicit comments for each phase and an invalid example that includes unnecessary comments. ```ts it('Item list and counter reset after reset', () => { const cartSourcesStub = mock(); const sut = new CartRepository(cartSourcesStub, createCacheService()); const goodsCountQuery = sut.getGoodsCountQuery(); const goodsQuery = sut.getGoodsQuery(); sut.resetCartCache(); expect(goodsCountQuery.data).toBe(0); expect(goodsQuery.data).toEqual([]); }); ``` ```ts it('Item list and counter reset after reset', () => { // Arrange const cartSourcesStub = mock(); const sut = new CartRepository(cartSourcesStub, createCacheService()); const goodsCountQuery = sut.getGoodsCountQuery(); const goodsQuery = sut.getGoodsQuery(); // Act sut.resetCartCache(); // Assert expect(goodsCountQuery.data).toBe(0); expect(goodsQuery.data).toEqual([]); }); ``` -------------------------------- ### Deep Nesting Example (React) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/nested.md Presents an example of deep directory nesting within a React project. Excessive nesting can indicate design issues, violate the Single Responsibility Principle, and hinder project maintainability and perception. -------------------------------- ### Application Initialization and Error Handling Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/application.md Initializes the application by configuring services, mounting the cache instance, and setting up error boundaries. It integrates React Query Devtools for debugging and uses `mobx-react-lite` for state management observation. ```tsx import { observer } from 'mobx-react-lite'; import { ErrorBoundary } from 'react-error-boundary'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; import { cacheInstance, configService, env, ErrorHandler, logError } from '@/shared'; import { Router } from './browser-router'; // Assuming env and configService are properly set up // Example: env.get('VITE_API_URL') would retrieve the API URL from environment variables configService.init({ apiUrl: env.get('VITE_API_URL'), }); export const App = observer(() => { const queryClient = cacheInstance.client; queryClient.mount(); // Mount the query client return ( ); }); ``` -------------------------------- ### Improve CartRepository Total Goods Counter Test Case Naming Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/antipatterns.md Illustrates how to enhance the clarity of test case names within the `CartRepository`'s 'Total goods counter' functionality. The 'Invalid' example uses an abstract name ('Works correctly when adding goods to cart'), whereas the 'Valid' example offers a more precise description ('Increases when adding goods after successful request execution'), improving test comprehension. ```typescript describe('CartRepository', () => { describe('Total goods counter', () => { it('Works correctly when adding goods to cart', async () => { const sut = new CartRepository(createCacheService()); const goodsCountQuery = sut.getGoodsCountQuery(); sut.addGoods(['id']); expect(goodsCountQuery.data).toBe(1); }); }); }); ``` ```typescript describe('CartRepository', () => { describe('Total goods counter', () => { it('Increases when adding goods after successful request execution', async () => { const sut = new CartRepository(createCacheService()); const goodsCountQuery = sut.getGoodsCountQuery(); sut.addGoods(['id']); expect(goodsCountQuery.data).toBe(1); }); }); }); ``` -------------------------------- ### Invalid UIStore Implementation (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/ru/style-guides/architecture/modules/features/ui-store.md An example of an invalid UIStore implementation where the class is named 'Store' instead of 'UIStore'. ```typescript export class Store {}; ``` -------------------------------- ### Testing Environment-Interacting Dependencies Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/mock-and-stub.md Provides a test case for a class (`CreateBookScreenStore`) that interacts with the environment. It mocks dependencies like `AdministrationRepository`, `Router`, and a notification service to verify the redirection logic after a successful book creation. ```tsx it('Successful book creation redirects to books list page', async () => { const fakeBookFormValues = makeFakeBookFormValues(); const adminRepositoryMock = mock(); const routerMock = createRouterMock(); const notifyMock = mock(); const sut = new CreateBookScreenStore( adminRepositoryMock, routerMock, notifyMock, ); await sut.createBook(fakeBookFormValues); expect(routerMock).toMatchObject({ pathname: APP_ROUTES.books.getRedirectPath(), }); }); ``` -------------------------------- ### Dependency Injection for UIStore Dependencies Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/features/ui-store.md This example illustrates the principle of dependency inversion for UIStore dependencies using basic DI. It shows a `CatalogStore` injecting `CartStore` to manage cart operations, promoting maintainability and testability by making dependencies explicit. ```tsx import { makeAutoObservable } from 'mobx'; import { CartStore } from '@modules/cart'; export class CatalogStore { constructor(private readonly cartStore: CartStore) { makeAutoObservable(this, {}, { autoBind: true }); } addToCart = (productID: string) => { this.cartStore.add(productID); }; } ``` -------------------------------- ### Invalid UIStore Implementation (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/ru/style-guides/architecture/modules/features/ui-store.md Another example of an invalid UIStore implementation where the class is named 'CartStore' instead of 'UIStore'. ```typescript export class CartStore {}; ``` -------------------------------- ### Valid UIStore Implementation (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/ru/style-guides/architecture/modules/features/ui-store.md A basic valid implementation of a UIStore class and a factory function to create instances of it. ```typescript export class UIStore {}; export const createUIStore = () => new UIStore(); ``` -------------------------------- ### Valid Function and Method Names (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/naming/functions.md Demonstrates valid naming conventions for functions and methods in TypeScript, starting with verbs to clearly indicate the action performed. ```TypeScript const calcSum = () => {}; const getUserData = () => {}; const removeID = () => {}; const refreshData = () => {}; const formatToView = () => {}; const createRequest = () => {}; ``` ```TypeScript class Example { public calcSum = () => {}; public getUserData = () => {}; public removeID = () => {}; public refresh = () => {}; public formatToView = () => {}; } ``` -------------------------------- ### Valid UIStore Method Naming (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/ru/style-guides/architecture/modules/features/ui-store.md Demonstrates the correct naming convention for UIStore methods, avoiding React-specific prefixes like 'handle' or 'on' unless semantically necessary. ```typescript import { SwitchStore } from './stores'; class UIStore { constructor() {} public deleteItem = () => {}; }; export const createUIStore = () => new UIStore(); ``` -------------------------------- ### Invalid Class Directory Naming Convention Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/classes.md Highlights an incorrect naming convention for class directories, where they do not start with a capital letter, potentially causing ambiguity. ```tree ├── services/ | |── file-service/ | | |── file-service.ts | | └── index.ts | |── error-service/ | | |── error-service.ts | | └── index.ts | └── index.ts ``` -------------------------------- ### Invalid Plural Noun Naming (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/naming/functions.md Shows examples of problematic naming for functions dealing with plural nouns in TypeScript, where the distinction between single and multiple items is unclear. ```TypeScript class Example { public getDraft = () => {}; public getDrafts = () => {}; public sendDraft = () => {}; public sendDrafts = () => {}; public calcDraftSum = () => {}; public calcDraftsSum = () => {}; } ``` ```React const DraftScreen = () => {}; const DraftsScreen = () => {}; ``` -------------------------------- ### Substituting Environment-Interacting Dependencies Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/mock-and-stub.md Demonstrates the substitution of dependencies that interact with the environment, such as `Router` and notification services, in a class constructor. This practice is crucial for reducing test execution time and maintaining isolation. ```tsx export class CreateBookScreenStore { constructor( private readonly administrationRepository: AdministrationRepository, private readonly routerService: Router, private readonly notifyService: typeof notify, ) {} } ``` -------------------------------- ### Invalid Directory Names (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/architecture/data/sources.md Shows an example of incorrect directory naming, specifically using camelCase instead of the required kebab-case, which deviates from the project's coding standards. ```tree ├── sources/ | ├── userNetworkSources/ | └── index.ts ``` -------------------------------- ### Create Basic Mock with Spy Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/mock-and-stub.md Demonstrates creating a mock object for a CartStore interface, replacing all methods and properties except 'goods' with a spy. This simplifies testing by focusing only on the relevant parts of the dependency. ```tsx const fakeGoodsList = cartRepositoryFaker.makeGoodsList(2); const cartStoreMock = mock({ goods: fakeGoodsList, }); const sut = new CardPaymentStore(cartStoreStub); ``` -------------------------------- ### Mapped Types in TypeScript Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/typescript.md Provides an example of Mapped Types in TypeScript, demonstrating their use for creating new object types based on existing ones, where index signatures are appropriately used. ```ts type OptionsFlags = { [Property in keyof TFields]: boolean; }; ``` -------------------------------- ### TypeScript Type Definition for Form Values Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/architecture/modules/validations.md Provides an example of a TypeScript type definition for form validation data, intended to be placed in a separate 'types.ts' file to manage dependencies effectively. ```typescript export type BookFormValues = { name: string; } ``` -------------------------------- ### UIStore Initialization within Component for useLogic (TSX) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/features/use-logic.md Shows the pattern for initializing the UIStore within a React component and then passing it to the useLogic hook. This highlights the dependency flow where the component manages the store's lifecycle. ```tsx import { useLocalObservable } from 'mobx-react-lite'; import { createUIStore } from './ui-store'; const Card = (props: Props) => { const uiStore = useLocalObservable(createUIStore); const { fullName, isShowDescription, description } = useLogic(uiStore); return ( {fullName} {isShowDescription && {description}} ); }; ``` -------------------------------- ### String Concatenation for Display (Invalid TSX) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/features/ui-logic.md This invalid example illustrates string concatenation directly within a UI component to form a full name. This logic should be externalized. ```tsx export const Card = ({ name, surname }: Props) => { return ( {`${name} ${surname}`} ); }; ``` -------------------------------- ### Valid Kebab-Case Directory Names (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/architecture/data/sources.md Demonstrates the correct use of kebab-case for naming source directories, promoting consistency and readability within the project structure. ```tree ├── sources/ | ├── user-network-sources/ | └── index.ts ``` -------------------------------- ### Valid: 'on' prefix for handler props (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/react/props.md Demonstrates the recommended naming convention for handler props, which should always start with the 'on' prefix to clearly identify their purpose as event handlers. ```ts type Props = { onClick: () => void; onChange: () => void; onDelete: () => void; }; ``` -------------------------------- ### Valid: Lowercase prop names (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/react/props.md Shows the correct convention for naming props, where all prop names start with a lowercase letter. This simplifies prop formation and improves code readability. ```ts type Props = { title: string; userName: string; onClick: () => void; footer: ReactNode; header: FunctionComponent; }; ``` -------------------------------- ### GoodsListStore with BookRepository dependency Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/mock-and-stub.md This TypeScript class, GoodsListStore, depends on BookRepository to fetch and format a list of books. The BookRepository is assumed to interact with a backend service. ```tsx class GoodsListStore { constructor(private readonly bookRepository: BookRepository) { makeAutoObservable(this); } public async getList(): Promise { const data = await this.bookRepository.getBookList(); return data.map(({ id, name, price }) => ({ id, name, price: formatPriceToView(price), store: createProductCartManagerStore(id), })); } } ``` -------------------------------- ### Faker for Source Testing Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/data.md Provides an example of using a 'faker' utility alongside 'Sources' to generate mock data for stubbing during repository testing. This facilitates isolated testing of repository logic. ```tsx export const cartNetworkSourcesFaker = { makeGoodsList(length: number = 10): CartNetworkSourcesDTO.GoodsList { return { data: Array.from({ length }).map(() => this.makeGoodsItem()), }; }, makeGoodsItem( data?: Partial, ): CartNetworkSourcesDTO.CartGoodsItemDTO { return { name: faker.commerce.productName(), id: faker.string.uuid(), price: faker.number.int(100000), count: faker.number.int(5), ...data, }; }, }; ``` -------------------------------- ### Repository Index for DTOs (TypeScript/TSX) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/data.md An example of an index file for a repository's DTOs. It exports all DTOs and types defined in the repository's dto.ts file, making them easily accessible. ```tsx export * as UserRepositoryDTO from './dto'; ``` -------------------------------- ### Dependency Injection for Repositories Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/data.md Illustrates the implementation of Dependency Injection (DI) in repositories, where dependencies are managed through the constructor. This promotes dependency control, simplifies testing, and reduces coupling. ```tsx import { CacheService } from '@shared'; import { UserNetworkSources } from '../../sources'; class UserRepository { private readonly keys = { userInfo: 'user-info', }; constructor( private readonly userNetworkSources: UserNetworkSources, private readonly cache: CacheService, ) {} public getUserInfoQuery = () => this.cache.createQuery( async () => { const { data } = await this.userNetworkSources.getPersonInfo(); return data; }, { queryKey: [this.keys.userInfo], }, ); public invalidateUserInfo = () => { this.cache.invalidate([this.keys.userInfo]); }; } ``` -------------------------------- ### Example Shared Layer Structure (React) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/overview.md Details the internal structure of the 'Shared' layer, commonly used in React projects. It highlights reusable components, utilities, types, and state management. ```tree ├── app/ ├── screens/ ├── modules/ ├── data/ └── shared/ | ├── constants/ | ├── types/ | ├── utils/ | ├── services/ | ├── stores/ | ├── ui/ | | ├── components/ | | ├── hooks/ | | ├── external.ts | | └── index.ts | └── index.ts ``` -------------------------------- ### Concatenate Strings for Full Name using UIStore Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/modules/features/ui-store.md Shows how to combine first and last names into a full name string for display using UIStore. This example leverages MobX for reactive state management. ```typescript export class UIStore { constructor(private readonly params: { name: string; surname: string }) { makeAutoObservable(this); } public get fullName() { return `${this.params.name} ${this.params.surname}`; } } ``` ```tsx import { useLocalObservable } from 'mobx-react-lite'; import { createUIStore } from './ui-store'; export const Card = (props: Props) => { const { fullName } = useLocalObservable(() => createUIStore(props)); return ( {fullName} ); }; ``` -------------------------------- ### Injecting Fake Cart Network Sources into Repository Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/contract-first.md This TypeScript snippet demonstrates how Dependency Injection (DI) is used to substitute real network sources with fake ones. By passing `fakeCartNetworkSources` to the `CartRepository` constructor, the system can be tested with mock data, ensuring that the repository logic works correctly independently of the actual network implementation. ```tsx export const cartRepository = new CartRepository( fakeCartNetworkSources, cacheService, ); ``` -------------------------------- ### Valid kebab-case file structure Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/kebab-case.md Demonstrates a valid directory structure adhering to the kebab-case naming convention. This structure is recommended for all project files and directories. ```bash ├── services/ | |── file-service/ | | |── async-file-service/ | | |── utils/ | | |── file-service.ts | | |── file-service.test.ts | | |── constants.ts | | |── enums.ts | | └── index.ts | |── error-service/ | └── index.ts ``` -------------------------------- ### Switching to Real Cart Network Sources Source: https://github.com/r3d-stack/docs/blob/main/docs/en/architecture/contract-first.md This TypeScript code shows the process of switching from fake data sources back to the real ones after the API implementation is complete. By updating the `CartRepository` constructor to use `cartNetworkSources` instead of `fakeCartNetworkSources`, the application can then interact with the actual backend services. ```tsx export const cartRepository = new CartRepository( cartNetworkSources, cacheService, ); ``` -------------------------------- ### CartScreenStore Payment Logic Source: https://github.com/r3d-stack/docs/blob/main/docs/en/unit-testing/test-case-formatting.md This code snippet demonstrates the CartScreenStore class, responsible for managing the cart screen's state and actions. It includes methods for opening a modal, initiating a payment process via the CardPaymentStore, and navigating the user upon successful payment. It also checks if card payment is available before proceeding. ```typescript export class CartScreenStore { ... public openModal = () => { this.pay(); this.modalStore.setTrue(); }; ... public pay = () => { if (!this.cardPaymentStore.isAllowCardPayment) { this.notifyService.info('Card payment not available'); return; } this.cardPaymentStore.pay({ onSuccess: () => { this.routerService.navigate('/popular'); }, }); }; } ``` -------------------------------- ### Use 'type' for Props and Logic Hooks (Invalid Interface Example) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/typescript.md Shows the incorrect usage of 'interface' for defining component props and hook parameters/return types, contrasting with the preferred 'type' alias approach. ```tsx interface Props { title: string; userName: string; onClick: () => void; }; export const UserInfo = ({ title, userName, onClick }: Props) => { ... }; ``` ```ts interface UseLogicParams { data: unknown[]; }; interface UseLogicResult { isShow: boolean; }; const useLogic = (params: UseLogicParams): UseLogicResult => {}; ``` ```ts export interface UserDTO { data: unknown[]; }; ``` -------------------------------- ### String and Number Concatenation with Template Literals (TypeScript) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/coercion.md Highlights the use of template literals for seamlessly concatenating strings and numbers. It shows an invalid example using the '+' operator for mixed-type concatenation. ```TypeScript const str = 'str'; const number = 22; const string = `${str} - ${number}`; ``` -------------------------------- ### Valid Module Directory Structure (kebab-case) Source: https://github.com/r3d-stack/docs/blob/main/docs/en/style-guides/architecture/modules/creation.md Demonstrates the correct directory structure for modules using kebab-case naming. This convention signifies that each directory is a container for a module. ```shell ├── modules/ | ├── cart/ | ├── payment/ | ├── request/ | ├── user-profile/ | └── layout/ ```