### Fetcher Implementation Example Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Shows an example of a 'docsFetcher' implementing queries and mutations using a cacheService. It defines how to execute a query to get a document and a mutation to create one. ```typescript const docsFetcher = { queries: { doc: cacheService.createQuerySet((id: string) => ({ execute: () => docsEndpoint.getDoc(id).then(({ data }) => data) })) }, mutations: { createDoc: cacheService.createMutationSet((data) => docsEndpoint.createDoc(data) ) } }; ``` -------------------------------- ### Module Directory Structure Example (TypeScript) Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch This example demonstrates the typical directory structure for a module, including README.md, features, domain, and index files. This organization helps in maintaining a clear separation of concerns within each module. ```tree modules/ └── cart/ ├── README.md ├── features/ ├── domain/ └── index.ts ``` -------------------------------- ### Payment Module Feature Structure Example (TypeScript) Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch An illustration of the nested structure within a feature module, showing components like PaymentSwitch, CardPayment, and domain logic. This detailed breakdown aids in understanding the scope and organization of individual features. ```tree modules/ └── payment/ ├── features/ │ ├── PaymentSwitch/ │ │ ├── PaymentSwitch.tsx │ │ ├── PaymentSwitch.test.tsx │ │ ├── SwitchBtn/ │ │ ├── styles.ts │ │ ├── utils/ │ │ ├── UIStore/ │ │ ├── constants.ts │ │ ├── types.ts │ │ └── index.ts │ ├── CardPayment/ │ ├── CashPayment/ │ └── index.ts └── domain/ ``` -------------------------------- ### Domain Layer Data Formatting and Aggregation Example (TypeScript) Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates how the Domain layer handles data formatting and aggregation. It uses fetchers from the API layer to retrieve data and then processes it within a store, combining information from different sources. ```typescript import { docsFetcher, orgFetcher, type DocsFetcher, type OrgFetcher } from '#api'; class CurrentOrgStore { constructor( private readonly _params: { orgID: string }, private readonly _docsFetcher: DocsFetcher, private readonly _orgFetcher: OrgFetcher, ) {} public get info() { const org = this.orgQuery.data; const docList = this.myDocListQuery.data; if (!org || !docList) { return null; } return { ...org, myDocList: docList, }; } private get orgQuery() { return this._orgFetcher.queries.org.create(this._params.orgID); } private get myDocListQuery() { return this._docsFetcher.queries.myDocList.create(this._params.orgID); } } ``` -------------------------------- ### Write Unit Tests for Fetcher-Based Store with Mock Data Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Provides testing example using @astral/mobx-query with mockFetcher and fake data generators. Tests verify that store correctly formats fetched data for display, demonstrates proper MobxQuery initialization per test to avoid cache pollution, and uses async/await with MobX when() for async state verification. ```typescript import { when } from 'mobx'; import { makeFakeBookList } from '#api/_fakers'; import { mockFetcher } from '#shared/_fakers'; describe('BooksListStore', () => { it('Список книг форматируется для отображения', async () => { // Для каждого теста необходимо инициализировать свой instance MobxQuery, // в противном случае каждый тест будет модифицировать кэш const mobxQuery = createMobxQuery(); const fakeBookList = makeFakeBookList(2, { price: 1000 }); const fakeBookListItem = fakeBookList.data[0]; const booksFetcherMock = mockFetcher({ queries: { bookList: () => mobxQuery.createQuerySet(() => ({ execute: async () => fakeBookList, })), }, }); const sut = new BooksListStore(booksFetcherMock); // Ждем автоматической загрузки данных // Загрузка данных начнется автоматически при обращении к sut.list за счет параметра enabledAutoFetch await when(() => Boolean(sut.list?.length)); expect(sut.list[0]).toEqual({ id: fakeBookListItem.id, name: fakeBookListItem.name, price: '1 000 руб.', }); }); }); ``` -------------------------------- ### Organize useLogic directory structure Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Shows the correct directory layout for useLogic with supporting utilities, hooks, constants, enums, and types colocated in a single directory alongside the Cart component. ```none ├── Cart/ │ ├── useLogic/ │ | |── utils/ │ | |── hooks/ │ | |── useLogic.ts │ | |── useLogic.test.ts │ | |── constants.ts │ | |── enums.ts │ | |── types.ts │ | └── index.ts │ ├── Cart.tsx │ └── index.ts ``` -------------------------------- ### Dependency Injection Example - TypeScript Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates the use of Dependency Injection (DI) in TypeScript for managing dependencies, specifically within a `CatalogStore` class. DI makes dependencies explicit, improving maintainability and testability by allowing easy substitution of dependencies with mock or test entities. ```typescript import { makeAutoObservable } from 'mobx'; import { CartStore } from '@astral/modules/cart'; export class CatalogStore { constructor(private readonly _cartStore: CartStore) { makeAutoObservable(this, {}, { autoBind: true }); } addToCart = (productID: string) => { this._cartStore.add(productID); }; } ``` -------------------------------- ### Consuming UIStore for Mounting ReactNode Messages (TypeScript/JSX) Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch A React functional component example demonstrating how to use a `UIStore` to mount and display a `ReactNode` message. It uses `useState` to initialize the store and `useEffect` to call the `mount` method with a constructed message. ```tsx const Alert = () => { const [{ mount }] = useState(createUIStore); const message = Hello; useEffect(() => { mount(message); }, []); ... }; ``` -------------------------------- ### Component Props Formation from Various Sources (TypeScript) Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Shows how component props can be composed from different sources, including `UIStore` types, DTOs from an `api` layer, props from other features, and props from shared components. This example defines a `Props` type by combining these sources. ```typescript type Props = { data: UIStore['data']; list: RequestsDTO.List; onClick: ButtonProps['onClick']; }; **`UIStore` при этом не зависит от props компонента своей фичи**. ``` -------------------------------- ### Project Directory Structure Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Root-level directory organization for Astral Frontend architecture. Shows the main folders representing each architectural layer and their hierarchical relationship within the project. ```plaintext ├── app/ ├── screens/ ├── modules/ ├── api/ └── shared/ ``` -------------------------------- ### React Component Using useLogic Hook Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Shows how to properly initialize UIStore in a component and consume data exclusively through useLogic hook. The component should contain no business logic, only structural rendering based on data provided by useLogic. ```typescript const Card = (props: Props) => { const [uiStore] = useState(() => createUIStore(props)); const { fullName, isShowDescription, description } = useLogic(uiStore); return ( {fullName} {isShowDescription && {description}} ); }; ``` -------------------------------- ### UI Component vs. Feature Logic Separation (TypeScript) Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch This code snippet illustrates the principle of separating UI rendering from feature logic. The invalid example shows direct date formatting within the UI component, while the valid example demonstrates moving this logic to a UIStore. ```tsx // ❌ Invalid: export const Card = ({ date }: Props) => { return {date.toLocaleDateString()}; }; // ✅ Valid: export const Card = (props: Props) => { const [{ issueDate }] = useState(() => createUIStore(props)); return {issueDate}; }; ``` -------------------------------- ### Example Endpoint Definition Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Illustrates how an endpoint is defined using a generic httpService to fetch document data. It specifies the expected DTO type for the response. ```typescript export const docsEndpoints = { getDoc: (id: string) => httpService.get(`/api/v1/docs/${id}`), } ``` -------------------------------- ### Contract First: Mocking Data with Fakers Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates the Contract First approach by using fakers to generate mock data for 'DocsDTO.Doc'. The endpoint is then updated to use this faker for development purposes. ```typescript // api/_fakers/docs.ts export const docsFaker = { makeDoc: (): DocsDTO.Doc => ({ id: faker.string.uuid(), name: 'Документ #1' }) } // api/endpoints/docs.ts - подмена для разработки export const docsEndpoints = { getDoc: async (id: string) => ({ data: docsFaker.makeDoc() }) } ``` -------------------------------- ### Organize business logic in UIStore directory structure Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates the correct file organization pattern where utils, services, and stores are colocated within the UIStore directory. UIStore serves as the single entry point for all business logic consumption. ```none ├── Cart/ │ ├── UIStore/ │ | |── stores/ │ | |── utils/ │ | |── services/ │ | |── UIStore.ts │ | └── index.ts │ ├── Cart.tsx │ └── index.ts ``` -------------------------------- ### Module Structure Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Outlines the directory structure for a module, typically named 'payment'. It includes specific directories for 'features', 'domain', 'external' dependencies, and the module's public API export. ```text modules/ └── payment/ ├── features/ # CardPayment, CashPayment ├── domain/ # CardPaymentStore, CashPaymentStore ├── external.ts # Зависимости от других модулей └── index.ts # Публичное API модуля ``` -------------------------------- ### API Structure Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Defines the directory structure for the API layer, including fakers for mock data, fetchers for data retrieval, endpoints, and services. The index.ts file exports essential components. ```text api/ ├── _fakers/ # Генерация фейковых данных для тестов ├── fetchers/ # Queries, Mutations ├── endpoints/ # повторяют структуру API ├── services/ # HttpService, CacheService └── index.ts # Экспортируются fetchers, DTO и services ``` -------------------------------- ### Browser API Abstraction in UIStore Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates abstraction of Browser APIs (localStorage, IntersectionObserver) through service dependencies injected into UIStore. This pattern improves testability by allowing mock implementations and decouples store logic from direct API usage. ```TypeScript export class UIStore { constructor(private readonly _storage: LocalStorageService) { makeAutoObservable(this); } public setSearch = (search: string) => { this._storage.setItem('search', search); }; } ``` ```TypeScript export class UIStore { constructor(private readonly _intersectionObserver: IntersectionObserver) { makeAutoObservable(this); } public mount = (itemRef: Ref) => { this._intersectionObserver(this.showAction, { root: itemRef.current }); }; } ``` -------------------------------- ### useLogic Hook Implementation with UIStore Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates how to implement useLogic hook that accepts a UIStore instance and returns an abstract interface for the component. The hook serves as the single entry point for all component data, abstracting away the implementation details of the underlying store. ```typescript export const useLogic = (store: UIStore) => { const isShowDescription = useEndScroll(); return { isShowDescription, fullName: store.fullName, description: store.description, }; }; ``` -------------------------------- ### Dependency Injection Pattern for UIStore Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Illustrates proper dependency injection in UIStore using constructor parameters with private readonly modifiers. Dependencies are explicitly declared, making them visible for testing and allowing easy substitution of mock implementations. ```TypeScript import { makeAutoObservable } from 'mobx'; import { CartStore } from '@astral/modules/cart'; export class CatalogStore { constructor(private readonly _cartStore: CartStore) { makeAutoObservable(this, {}, { autoBind: true }); } public addToCart = (productID: string) => { this._cartStore.add(productID); }; } ``` -------------------------------- ### Import External Dependencies Through external.ts Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates the correct pattern for importing external module dependencies through the local external.ts file. This centralizes dependency management and makes module coupling explicit and traceable. ```typescript import { UserStore } from '../../../external'; ``` -------------------------------- ### Write UIStore test with describe block named 'UIStore' Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Establishes the convention of naming the describe block 'UIStore' for consistency, as the file path already provides the feature context. This avoids redundant naming like 'CartUIStore'. ```typescript describe('UIStore', () => { ... }); ``` -------------------------------- ### Prop Formatting Refactoring in TypeScript Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates refactoring prop formatting for React components. It moves the logic for preparing props like 'viewerTitle' and 'descriptions' from the component into a UIStore, simplifying the component's render method. ```tsx export const Card = () => { const [{ name, list }] = useState(createUIStore); return description)} />; }; ``` ```tsx export const Card = () => { const [{ viewerTitle, descriptions }] = useState(createUIStore); return ; }; ``` -------------------------------- ### Factory Method for UIStore Creation Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates factory pattern for UIStore instantiation encapsulating dependency creation logic. Factory methods hide implementation details, enable store reusability, and should be used instead of inline constructor calls in React components. ```TypeScript export class UIStore { constructor(private readonly _payService: PaymentService) { makeAutoObservable(this, {}, { autoBind: true }); } } export const createUIStore = () => new UIStore(payService); ``` ```TSX export const Payment = () => { const [{ pay }] = useState(createUIStore); return ; }; ``` -------------------------------- ### Create Cache Service for API Layer Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Initializes MobxQuery instance with error handling and auto-fetch enabled for caching API responses. Exports both factory function and singleton instance for use throughout the API layer services. ```typescript import { MobxQuery } from '#shared'; import { type ApiDataError } from '../ApiHttpClient'; export const createCacheService = () => new MobxQuery({ autoFetch: true }); export const cacheService = createCacheService(); ``` -------------------------------- ### Form useLogic with Validation and Types Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Shows the proper structure for a form component with useLogic hook that includes validation and type definitions. The BookFormValues type is separated to prevent circular dependencies between useLogic, validation, and UIStore modules. ```typescript export type BookFormValues = { name: string; }; ``` -------------------------------- ### Implement Contract-First API Endpoints with Faker Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Replaces actual server requests with faker-generated data in endpoint methods to enable contract-first development. Returns mock responses matching the HttpServiceResponse type structure before real backend implementation is available. ```typescript import { DocsDTO } from './dto'; import { docsFaker } from '../_fakers'; import { HttpServiceResponse } from '../services'; export const docsEndpoints = { getDocInfo: async (id: string) => ({ data: docsFaker.makeDocInfo() }) as HttpServiceResponse, }; ``` -------------------------------- ### Implement useLogic hook in separate directory Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Creates a useLogic hook in its own directory with associated utilities, types, and tests. This pattern establishes a clear visual and structural connection between the React component and its logic, enabling easy relocation. ```typescript export const useLogic = () => {}; ``` -------------------------------- ### Routing with Dynamic Parameters - React Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates routing with dynamic route parameters using router hooks. Handles cases where required parameters are missing by rendering NotFoundScreen. Uses conditional logic to determine which screen to display based on parameter availability. ```tsx import { useRouter, router } from '#shared'; import { NotFoundScreen, RequestsScreen } from '#screens'; export const IndexPage = () => { const { id } = router.routeParams; if (!id) { return ; } return ; }; ``` -------------------------------- ### Module Naming Convention - camelCase - File System Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Specifies the naming convention for module directories within the `modules` layer. Module names should be in camelCase to indicate that they are directory containers, not classes or components. This convention improves clarity and consistency. ```plaintext ├── modules/ | ├── cart/ | ├── payment/ ``` -------------------------------- ### UI Store for Action Icons with Rendered Components (TypeScript) Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Illustrates how a `UIStore` can manage action icons by using `RenderComponentInDomain` to dynamically render components like `EditIcon`. The `actions` getter returns an array of action configurations, where each icon is a rendered React node. ```typescript import { EditIcon } from '#shared'; import type { ActionCellProps } from '#shared'; type ActionIcons = { renderEdit: RenderComponentInDomain; }; export class UIStore { constructor(private readonly _actionIcons: ActionIcons) { makeAutoObservable(this); } public get actions(): ActionCellProps { return [ { icon: this._actionIcons.renderEdit(), onClick: () => this.edit(), }, ]; } } export const createUIStore = () => new UIStore({ renderEdit: adaptComponentToDomain(EditIcon), }); ``` -------------------------------- ### Payment Store Integration with Custom Notification (TypeScript) Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates integrating a custom payment message rendering into a `Notify` service. The `PaymentStore` constructor accepts a `RenderComponentInDomain` for payment messages, which is used in the `pay` method to display a success notification with custom content. ```typescript import { PaymentMessage } from '../../features'; export class PaymentStore { constructor( private readonly _notify: Notify, private readonly _renderPaymentMessage: RenderComponentInDomain<{ productID: string; }>, private readonly _paymentFetcher: PaymentFetcher, ) { makeAutoObservable(this); } public pay = async (productID: string) => { await this._paymentFetcher.pay(productID); this._notify.success('Оплачено', { content: this._renderPaymentMessage({ productID }), }); }; } export const createPaymentStore = () => new PaymentStore( notifyService, paymentFetcher, adaptComponentToDomain(PaymentMessage), ); ``` -------------------------------- ### Create UIStore Factory Function TypeScript Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Factory function pattern for instantiating UIStore class. Creates a new UIStore instance that can contain UI-related logic for React components. This pattern enables dependency injection and easier testing of store logic. ```typescript export class UIStore {}; export const createUIStore = () => new UIStore(); ``` -------------------------------- ### Domain Entity Grouping - Directory Structure Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Illustrates the recommended directory structure for grouping different types of software entities within the `domain` layer to enhance maintainability. Common groupings include `utils`, `stores`, `validations`, `types`, `constants`, and `enums`. ```plaintext ├── domain/ | ├── utils/ | ├── stores/ | ├── validations/ | ├── enums/ | ├── types/ | ├── constants/ | └── index.ts ``` ```plaintext ├── domain/ | ├── utils/ | ├── stores/ | ├── validations/ | ├── enums.ts | ├── types.ts | ├── constants.ts | └── index.ts ``` -------------------------------- ### UI Store for Managing ReactNode Messages (TypeScript) Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch This `UIStore` class is designed to hold and send a `ReactNode` message. It provides `mount` to set the message and `send` to notify using the provided `Notify` service. This is useful for displaying alerts or messages dynamically. ```typescript import type { ReactNode } from 'react'; export class UIStore { private alertMessage: ReactNode; constructor(private readonly _notify: Notify) { makeAutoObservable(this); } public mount = (message: ReactNode) => { this.alertMessage = message; }; public send = () => { this._notify(this.alertMessage); }; } ``` -------------------------------- ### Forward Ref to UIStore for Service Integration Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Shows how to pass HTML element references through UIStore to services. The setContainerRef method receives a ref and forwards it to the Scroller service for scroll container setup, enabling abstraction of ref handling within the store. ```TypeScript export class UIStore { constructor(private readonly _scroller: Scroller) { makeAutoObservable(this); } public setContainerRef = (ref: Ref) => { this._scroller.setScrollContainer(ref); }; } ``` -------------------------------- ### Create Docs Fetcher with Queries, Infinite Queries, and Mutations Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Implements a fetcher module that defines queries for single and paginated document retrieval, plus mutations for editing. Uses cacheService to create QuerySet, InfiniteQuerySet, and MutationSet instances with proper TypeScript typing. Dependencies include docsEndpoint and cacheService. ```typescript // api/fetchers/docs.ts import { docsEndpoint } from '../endpoints'; import { cacheService } from '../services'; const docsFetcher = { queries: { doc: cacheService.createQuerySet((id: string) => ({ execute: () => docsEndpoint.getDoc(id).then(({ data }) => data), })), }, infiniteQueries: { docList: cacheService.createInfiniteQuerySet( (filters: Omit) => ({ execute: ({ offset, count }) => docsEndpoint .getDocList({ offset, count, ...filters }) .then(({ data }) => data.list), }), ), }, mutations: { editDoc: cacheService.createMutationSet( (params: DocsDTO.EditDocInput) => docsEndpoint.editDoc(params), ), }, }; export type DocsFetcher = typeof docsFetcher; ``` -------------------------------- ### Implement API Formatting Function - TypeScript Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Implements a function within `domain/apiFormatters` to handle the transformation of data, specifically from a DTO to a domain model. The naming convention is `format${'DTO' | ENTITY}${'from' | 'to'}${'DTO' | ENTITY}`. This example shows formatting a Passport from a User DTO. ```typescript import { type UserDTO } from '#api'; import { Passport } from '../../types'; export const formatPassportFromDTO = ({ fullName, ...data }: UserDTO.Passport): Passport => ({ ...data, name: parseName(fullName), surname: parseSurname(fullName), }); ``` -------------------------------- ### Data Transfer Object (DTO) Definition Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Defines the structure for a 'Doc' object using a TypeScript namespace. This DTO specifies the expected properties for document data. ```typescript export namespace DocsDTO { export type Doc = { id: string; name: string; } } ``` -------------------------------- ### Implement Document Store with Fetcher Integration Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates usage of DocsFetcher in a MobX store for managing document state. The store receives the fetcher dependency, creates reactive queries using makeAutoObservable, and exposes document data through computed getters that access cached fetcher data. ```typescript // modules/docs/domain/stores/DocStore/DocStore.ts import { type DocsFetcher, type DocsDTO } from '#api'; class DocStore { constructor( private readonly _docID: string, private readonly _docsFetcher: DocsFetcher, ) { this.creationsDocMutation = _docsFetcher.mutations.createDoc.create(); makeAutoObservable(this, {}, { autoBind: true }); } public get docName() { return this.docQuery.data?.name || ''; } public createDoc = (data: DocsDTO.CreateDocInput) => { this.creationDocMutation.sync(); }; private get docQuery() { return this._docsFetcher.queries.doc.create(this._docID); } } ``` -------------------------------- ### Define External Dependencies in external.ts Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Shows how to centralize incoming dependencies from other modules in an external.ts file. This allows tracing module dependencies and avoiding unwanted coupling by explicitly declaring what external modules are used. ```typescript export { UserStore } from '@astral/modules/auth'; ``` -------------------------------- ### Configuration Service Location - File System Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Illustrates the recommended location for the `Config` service within the `shared` layer of the application. This service is responsible for providing access to application configuration parameters (e.g., API URLs, brand name) throughout the entire application. ```plaintext |── shared/ | ├── services/ | | ├── ConfigService/ | | └── index.ts | └── index.ts ``` -------------------------------- ### Use UIStore method in React component onClick handler Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Consumes UIStore methods in a React component by passing them directly to event handlers like onClick. The React component is responsible for the handler semantics, not UIStore. ```typescript import { createUIStore } from './UIStore'; const DeleteItem = () => { const [{ deleteItem }] = useState(createUIStore); return ( ); }; ``` -------------------------------- ### useLogic Hook Implementation with Sub-hooks Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates the correct pattern for implementing a useLogic hook that aggregates sub-hooks from a hooks directory. The main useLogic serves as the single entry point for component logic, delegating to specialized hooks like useScrollToTop stored in useLogic/hooks subdirectory. ```typescript import { useScrollToTop } from './hooks'; export const useLogic = () => { const { scrollToTop } = useScrollToTop(); return { scrollToTop } }; ``` -------------------------------- ### UIStore Mount/Unmount Lifecycle Binding with MobX Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates UIStore class with mount and unmount lifecycle methods synchronized with React component lifecycle using useEffect. The store manages observer subscriptions and passes container references to services. Mount initializes observers and sets scroll container, unmount cleans up observer subscriptions. ```TypeScript export class UIStore { private unobserveSearch: () => void = () => {}; public search: string = ''; constructor( private readonly _listStore: ListStore, private readonly _scroller: Scroller, ) { makeAutoObservable(this); } private observeSearch = () => autorun(() => { this._listStore.changeParams({ search: this.search }); }); public mount = (containerRef: Ref) => { this._scroller.setScrollContainer(containerRef); this.unobserveSearch = this.observeSearch(); }; public unmount = () => { this.unobserveSearch(); }; } ``` ```TSX const List = () => { const containerRef = useRef(); const [{ mount, unmount }] = useState(createUIStore); useEffect(() => { mount(containerRef); return unmount; }, []); // ... }; ``` -------------------------------- ### Configure MobxRouter with route definitions in TypeScript Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Sets up MobxRouter with ReactRouterProvider to define application routes with patterns and path generation functions. Demonstrates route configuration for home, user detail with ID parameter, and profile with optional userId parameter. Exports router instance and type for application-wide routing access through RouterService. ```typescript import { MobxRouter } from '@astral/mobx-router'; import { ReactRouterProvider } from '@astral/mobx-router-react'; export const reactRouterProvider = new ReactRouterProvider(); const routesConfig = { home: MobxRouter.defineRoute({ pattern: '/home', }), user: MobxRouter.defineRoute({ pattern: '/user/:id', generatePath: (params: { id: string }) => `/user/${params.id}`, }), profile: MobxRouter.defineRoute({ pattern: '/profile/:userId?', generatePath: ({ userId }: { userId?: string }) => userId ? `/profile/${userId}` : '/profile' , }), }; export const router = new MobxRouter(reactRouterProvider, routesConfig); export type Router = typeof router; ``` -------------------------------- ### Import Faker in TypeScript Test Module Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Demonstrates importing faker data generators from the _fakers directory in test files. The _fakers directory uses underscore prefix to indicate it is internal and should not be exported from api/index.ts for production use. ```typescript // modules/domain/DocStore/DocStore.test.ts import { docsFaker } from '#api/_fakers'; ``` -------------------------------- ### UIStore with Dependency Injection TypeScript Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch UIStore class accepting store dependencies through constructor. Demonstrates composition pattern where UIStore manages UI logic while delegating specialized concerns like switch state to injected stores. The SwitchStore is imported from the stores subdirectory within UIStore. ```typescript import { SwitchStore } from './stores'; export class UIStore { constructor(private readonly _switchStore: SwitchStore) {} }; ``` -------------------------------- ### Create ConfigService TypeScript abstraction for environment variables Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Defines a ConfigService class that abstracts environment variable access through getter methods, providing a single source of truth for configuration across the application. The service wraps an environment store object and supplies default values for critical URLs. This pattern decouples the application from the underlying environment mechanism (window.__ENV__, process.env, or import.meta.env). ```typescript export class ConfigService { public constructor(private readonly _envStore: Record) {} public get apiUrl(): string { return this._envStore.PUBLIC_API_URL || 'https://localhost:3000'; } public get stand(): string { return this._envStore.PUBLIC_STAND; } public get identityUrl(): string { return this._envStore.PUBLIC_IDENTITY_URL; } public get personAreaUrl(): string { return this._envStore.PUBLIC_PERSON_AREA_URL; } public get releaseVersion(): string { return this._envStore.PUBLIC_RELEASE_VERSION; } } // window.__ENV__ can be replaced with process.env or import.meta.env export const configService = new ConfigService(window.__ENV__); ``` -------------------------------- ### Define Reusable Common DTOs in TypeScript Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Creates shared data transfer objects for pagination and sorting functionality that are used across multiple endpoints. Organizes common types by purpose rather than entity to promote reusability. ```typescript // api/endpoints/commonDTO/lists/dto.ts export namespace ListsDTO { export type Pagination = { totalCount: number; }; } // api/endpoints/commonDTO/lists/enums.ts export enum SortValue { Asc, Desc } ``` -------------------------------- ### Form Validation Schema with Conditional Rules Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Creates a validation schema for BookFormValues using a validation library, including conditional validation where coAuthor field is required only when isPresentCoAuthor is true. This schema ensures data integrity before form submission. ```typescript const validationSchema = v.object({ name: v.string(), genre: v.object({ id: v.string(), name: v.string(), description: v.optional(v.string()), }), pageCount: v.number(), author: v.object({ name: v.string(), surname: v.string(), }), isPresentCoAuthor: v.optional(v.boolean()), coAuthor: v.when({ is: (_, ctx) => Boolean(ctx.values?.isPresentCoAuthor), then: v.object({ name: v.string(), surname: v.string(), }), otherwise: v.any(), }), }); export const useLogic = () => { const form = useForm({ validationSchema }); }; ``` -------------------------------- ### useLogic Hook for React-Bound Feature Logic Source: https://guides.frontend.cloud.astral-dev.ru/llms-full-arch Structure and pattern for useLogic hook implementation encapsulating feature logic tightly coupled to React hooks, form state management, and React-specific functionality. Includes organized directory structure with utils, hooks, constants, enums, and types subdirectories. ```TypeScript // useLogic directory structure // PaymentForm/ // ├── UIStore/ // ├── useLogic/ // │ ├── utils/ // │ ├── hooks/ // │ ├── useLogic.ts // │ ├── useLogic.test.ts // │ ├── constants.ts // │ ├── enums.ts // │ ├── types.ts // │ └── index.ts // ├── PaymentForm.tsx // └── index.ts ```