### MobX Store Implementation with Lifecycle Management Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Demonstrates the implementation of a MobX store for managing user profile state. It includes lifecycle watchers (watchAssignUser, watchRunApp), bound methods, observable properties, getters for accessing other stores, and asynchronous actions handled with try-catch blocks and `runInAction`. ```typescript // mobile/src/store/stores/user-profile/UserProfile.ts import { makeAutoObservable, runInAction } from 'mobx' import Root from '~store/Root' import { StoreInstance } from '~store/Root.types' import Api from '~services/Api' import ErrorHandler from '~services/ErrorHandler' /** * Manages user profile data and authentication state */ export default class UserProfile implements StoreInstance { rootStore: Root // Private properties private isLoading: boolean = false // Public observable properties userName: string = '' isAuthenticated: boolean = false constructor(rootStore: Root) { this.rootStore = rootStore ?? {} // Bind all methods BEFORE makeAutoObservable this.fetchProfile = this.fetchProfile.bind(this) this.setUserName = this.setUserName.bind(this) this.logout = this.logout.bind(this) makeAutoObservable(this) } // Getters for other stores get authStore() { return this.rootStore.authStore } get t() { return this.rootStore.t } // Lifecycle watcher - runs after user is assigned watchAssignUser({ runAfterRunApp }) { runAfterRunApp(async () => { await this.fetchProfile() }) } // Lifecycle watcher - runs on app start watchRunApp({ runSync }) { runSync(() => { this.isAuthenticated = false }) } // Async action with runInAction async fetchProfile() { try { this.isLoading = true const { data } = await Api.getUserProfile() runInAction(() => { this.userName = data.name this.isAuthenticated = true this.isLoading = false }) } catch (error) { ErrorHandler.capture(error, { tags: { store: 'UserProfile', method: 'fetchProfile' } }) runInAction(() => { this.isLoading = false }) } } // Synchronous action setUserName(name: string) { this.userName = name } logout() { this.userName = '' this.isAuthenticated = false } } ``` ```typescript // mobile/src/store/stores/user-profile/index.ts export { default } from './UserProfile' ``` ```typescript // Register in mobile/src/store/Root.ts import UserProfileStore from './stores/user-profile' class Root { userProfileStore: UserProfileStore constructor() { this.userProfileStore = new UserProfileStore(this) } } ``` -------------------------------- ### Organize Shared Components with Element/Pattern/Template Prefixes Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Defines directory structure for shared components using naming conventions: ElButton for atomic Elements with no dependencies, PtCard for composite Patterns composed from Elements, and TmUserProfile for Templates containing business logic. Each component folder includes index.ts, component file, types file, and optional styles file for modularity and co-location of related files. ```typescript // Shared components structure mobile/src/components/ ├── ElButton/ # Element - atomic, no dependencies │ ├── index.ts │ ├── ElButton.tsx │ └── ElButton.types.ts ├── PtCard/ # Pattern - composed from Elements │ ├── index.ts │ ├── PtCard.tsx │ ├── PtCard.types.ts │ └── PtCard.styles.ts └── TmUserProfile/ # Template - self-contained with business logic ├── index.ts ├── TmUserProfile.tsx ├── TmUserProfile.types.ts ├── TmUserProfile.styles.ts └── components/ # Sub-components without prefixes └── ProfileSection/ ├── index.ts ├── ProfileSection.tsx └── ProfileSection.types.ts ``` -------------------------------- ### Implement Profile Settings Screen with Navigation and Analytics (TypeScript) Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt This TypeScript code implements the Profile Settings screen for a mobile application. It integrates with navigation, tracks user analytics events on screen focus, and allows users to edit their profile or log out. It utilizes MobX for state management and React hooks for lifecycle and event handling. ```typescript // mobile/src/screens/profile-settings/ProfileSettings.tsx import { FC, useCallback, useState } from 'react' import { observer } from 'mobx-react-lite' import { useFocusEffect } from '@react-navigation/native' import { useStore } from '~/hooks/context/useStore' import { ProfileRoute, ProfileScreenProps } from '~navigation/groups' import { TmScreenContainer, ElText, ElButton } from '~/components' import Analytics, { EVENTS } from '~services/Analytics' import Navigation from '~services/Navigation' import { useTranslation } from 'react-i18next' /** * Profile settings screen for user preferences and account management */ const ProfileSettings: FC> = observer(({ route }) => { const { userProfileStore, settingsStore } = useStore() const { userId } = route?.params ?? {} const { t } = useTranslation() const [isEditing, setIsEditing] = useState(false) // Track screen visit on focus useFocusEffect( useCallback(() => { Analytics.track(EVENTS.VISIT_PROFILE_SETTINGS, { userId: userId }) }, [userId]) ) const handleSave = useCallback(async () => { try { await userProfileStore.updateProfile({ name: userProfileStore.userName }) setIsEditing(false) Navigation.goBack() } catch (error) { // Error handled in store } }, [userProfileStore]) const handleLogout = useCallback(() => { userProfileStore.logout() Navigation.navigate(ProfileRoute.Login) }, [userProfileStore]) return ( {t('mobile.profile.settings.title')} {userProfileStore.userName} {isEditing ? ( {t('mobile.common.save')} ) : ( setIsEditing(true)}> {t('mobile.common.edit')} ts)} {t('mobile.profile.logout')} ) }) export default ProfileSettings ``` ```typescript // mobile/src/screens/profile-settings/index.tsx export { default } from './ProfileSettings' ``` -------------------------------- ### Rebuild Mobile Project After Adding Translations Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Command to rebuild the mobile project after modifying translation keys. This ensures the prebuild script processes updated translation files and makes them available to the application. ```bash # After adding new translations, rebuild cd mobile && yarn prebuild ``` -------------------------------- ### Organize Screen-Level Sub-Components Without Prefixes Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Defines directory structure for screen-level components that contain local sub-components without El/Pt/Tm prefixes. Dashboard screen includes local MetricsCard and ActivityFeed components in a dedicated components folder. Each sub-component maintains standard file structure (index.ts, component file, types file) following co-location principles. ```typescript // Screen with local sub-components mobile/src/screens/dashboard/ ├── index.tsx ├── Dashboard.tsx ├── Dashboard.types.ts └── components/ # Local components, no El/Pt/Tm prefix ├── MetricsCard/ │ ├── index.ts │ ├── MetricsCard.tsx │ └── MetricsCard.types.ts └── ActivityFeed/ ├── index.ts ├── ActivityFeed.tsx └── ActivityFeed.types.ts ``` -------------------------------- ### Implement Template Component with Sub-Component Composition Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Shows Template component (TmUserProfile) that uses sub-components (ProfileSection) without prefixes. Demonstrates importing from local components folder, using TypeScript props interface, and composing multiple instances of sub-components with different content. Illustrates separation of concerns where Template handles layout and orchestration while sub-components handle specific UI sections. ```typescript // TmUserProfile.tsx - Template component using sub-component import { FC } from 'react' import { ElBox } from '~/components' import { ProfileSection } from './components/ProfileSection' import type { TmUserProfileProps } from './TmUserProfile.types' const TmUserProfile: FC = ({ userId, userName }) => { return ( ) } export { TmUserProfile } ``` -------------------------------- ### Implement Component Using Semantic Generic Types Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Demonstrates usage of semantic generic types in a component implementation, showing how DataListProps with UserResource generic parameter provides type safety for the items array and render function. ```typescript // Usage with semantic generics const UserList: FC> = ({ items, renderItem }) => { return ( renderItem(item, index)} /> ) } ``` -------------------------------- ### Implement Centralized API Service Class with Axios Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Creates a singleton Api service class using axios for HTTP requests with generic type parameters for type-safe responses. Includes error handling that returns a consistent object structure with data or error properties, eliminating try-catch boilerplate in components. ```typescript // mobile/src/services/Api/Api.ts import axios from 'axios' import type { UserProfileResponse } from '~/types/server/UserProfileResponse' class Api { private baseUrl = 'https://api.example.com' /** * Fetch user profile data */ async getUserProfile(userId: number) { try { const response = await axios.get( `${this.baseUrl}/api/user/${userId}/profile` ) return { data: response.data, error: null } } catch (error) { return { data: null, error } } } /** * Update user profile */ async updateUserProfile(userId: number, data: Partial) { try { const response = await axios.patch( `${this.baseUrl}/api/user/${userId}/profile`, data ) return { data: response.data, error: null } } catch (error) { return { data: null, error } } } } export default new Api() ``` -------------------------------- ### Create Custom Style Hook with Theme Integration (TypeScript) Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt This TypeScript code defines a custom hook `useUserCardStyles` for styling the `UserCard` component. It leverages a `useStyles` hook (presumably from a theme context) to access theme variables like colors, transparencies, and RGBA color generation. The hook accepts props to dynamically adjust styles, such as highlighting the card. ```typescript // mobile/src/components/UserCard/UserCard.styles.ts import { useStyles } from '~/hooks/theme' import type { UserCardProps } from './UserCard.types' const useUserCardStyles = ({ isHighlighted }: Pick) => { const styles = useStyles(({ colors, transparencies, getRGBA }) => ({ container: { padding: isHighlighted ? 20 : 16, borderRadius: 12, backgroundColor: getRGBA( isHighlighted ? colors.primary.base : colors.background.secondary, transparencies.medium ), borderWidth: isHighlighted ? 2 : 0, borderColor: colors.primary.base }, title: { fontSize: 18, fontWeight: '600', color: colors.text.primary, marginBottom: 8 }, subtitle: { fontSize: 14, color: getRGBA(colors.text.secondary, transparencies.strong) } })) return { styles } } export default useUserCardStyles ``` ```typescript // Usage in component import { ElBox, ElText } from '~/components' import useUserCardStyles from './UserCard.styles' const UserCard = ({ isHighlighted = false, title, subtitle }) => { const { styles } = useUserCardStyles({ isHighlighted }) return ( {title} {subtitle} ) } ``` -------------------------------- ### Define Component Constants with TypeScript Enums and Configuration Objects Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Creates a constants file for StatusBadge component using TypeScript enums for status types and const objects for size/style configurations. The StatusType enum defines four status states, BADGE_SIZES object contains responsive padding/font/icon values, and STATUS_COLORS maps enum values to color types. All exports are unified at the end of the file for clean dependency management. ```typescript // mobile/src/components/StatusBadge/StatusBadge.constants.ts /** * Available status types for the badge */ enum StatusType { Active = 1, Pending = 2, Inactive = 3, Error = 4 } /** * Size configurations for different badge variants */ const BADGE_SIZES = { small: { padding: 6, fontSize: 12, iconSize: 14 }, medium: { padding: 8, fontSize: 14, iconSize: 16 }, large: { padding: 12, fontSize: 16, iconSize: 20 } } as const /** * Color mappings for status types */ const STATUS_COLORS = { [StatusType.Active]: 'success', [StatusType.Pending]: 'warning', [StatusType.Inactive]: 'secondary', [StatusType.Error]: 'error' } as const // Unified export at end of file export { StatusType, BADGE_SIZES, STATUS_COLORS } ``` -------------------------------- ### React Native Component File Structure and Unified Exports Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Defines a strict directory structure for React Native components, separating types, styles, constants, and utilities. All exports are consolidated at the end of the component file for improved readability and maintainability. Uses TypeScript for type definitions. ```typescript // ComponentName/ComponentName.types.ts interface UserCardProps { /** User's display name */ name: string /** User age in years * @default 18 */ age?: number /** User role type */ role: 'admin' | 'user' } // Unified export at end of file export type { UserCardProps } ``` ```typescript // ComponentName/ComponentName.tsx import { FC } from 'react' import { observer } from 'mobx-react-lite' import { ElBox, ElText } from '~/components' import useUserCardStyles from './UserCard.styles' import type { UserCardProps } from './UserCard.types' const UserCard: FC = observer(({ name, age = 18, role }) => { const { styles } = useUserCardStyles(role === 'admin') return ( {name} Age: {age} ) }) // Export WITHOUT default export { UserCard } ``` ```typescript // ComponentName/index.ts export { UserCard } from './UserCard' export type { UserCardProps } from './UserCard.types' ``` -------------------------------- ### Import and Use Component Constants in React Component Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Demonstrates consuming constants in a React functional component with TypeScript. The StatusBadge component imports enum and configuration objects, uses type-safe props with keyof operator for size variants, and applies configuration values to element styling. Shows pattern of accessing enum values and configuration properties at render time. ```typescript // Usage in component import type { FC } from 'react' import { ElBox, ElText } from '~/components' import { StatusType, BADGE_SIZES, STATUS_COLORS } from './StatusBadge.constants' interface StatusBadgeProps { status: StatusType size?: keyof typeof BADGE_SIZES } const StatusBadge: FC = ({ status, size = 'medium' }) => { const sizeConfig = BADGE_SIZES[size] const colorType = STATUS_COLORS[status] return ( {StatusType[status]} ) } ``` -------------------------------- ### User Profile Management API Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt This section details the API endpoints for retrieving and updating user profile information. It utilizes TypeScript types for request and response data. ```APIDOC ## GET /api/user/{userId}/profile ### Description Fetches the profile data for a specific user. ### Method GET ### Endpoint `/api/user/{userId}/profile` ### Parameters #### Path Parameters - **userId** (number) - Required - The unique identifier of the user. ### Request Example ```json { "userId": 123 } ``` ### Response #### Success Response (200) - **user** (UserResource) - The user's profile data. - **completeness** (number) - The percentage of profile completion. - **lastLogin** (string) - The timestamp of the user's last login. #### Response Example ```json { "user": { "id": 123, "email": "user@example.com", "name": "John Doe", "role": "user", "createdAt": "2023-10-26T10:00:00Z" }, "completeness": 85, "lastLogin": "2023-10-26T10:00:00Z" } ``` ## PATCH /api/user/{userId}/profile ### Description Updates the profile information for a specific user. ### Method PATCH ### Endpoint `/api/user/{userId}/profile` ### Parameters #### Path Parameters - **userId** (number) - Required - The unique identifier of the user. #### Request Body - **id** (number) - Optional - User's unique identifier. - **email** (string) - Optional - User's email address. - **name** (string) - Optional - User's display name. - **role** (string) - Optional - User's role (admin, user, moderator). ### Request Example ```json { "name": "Jane Doe" } ``` ### Response #### Success Response (200) - **user** (UserResource) - The updated user's profile data. - **completeness** (number) - The updated profile completion percentage. - **lastLogin** (string) - The timestamp of the user's last login. #### Response Example ```json { "user": { "id": 123, "email": "user@example.com", "name": "Jane Doe", "role": "user", "createdAt": "2023-10-26T10:00:00Z" }, "completeness": 90, "lastLogin": "2023-10-26T10:00:00Z" } ``` ``` -------------------------------- ### Define Generic Component Props with JSDoc Annotations Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Creates reusable DataList component props interface using semantic generic type names and JSDoc @default annotations for optional properties. Also defines a union type allowing both full props object or simple array shorthand for flexible usage patterns. ```typescript // mobile/src/components/DataList/DataList.types.ts import type { ViewProps } from 'react-native' import type { ColorType } from '~/types/common' /** * Props for DataList component */ interface DataListProps extends ViewProps { /** Array of items to display */ items: Item[] /** * Render function for each item */ renderItem: (item: Item, index: number) => React.ReactNode /** * Key extractor function * @default (item, index) => index.toString() */ keyExtractor?: (item: Item, index: number) => string /** * Show loading indicator * @default false */ isLoading?: boolean /** * Background color type * @default 'background' */ backgroundColor?: ColorType<'background'> /** * Empty state message * @default 'No items found' */ emptyMessage?: string } // Allow both full props object or simple array shorthand type DataListProp = DataListProps | Item[] export type { DataListProps, DataListProp } ``` -------------------------------- ### Implement Component with i18n Translation Hook Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Demonstrates proper i18n integration by using useTranslation hook inside the component rather than passing translation function as props. Uses t() function with semantic key paths and provides variables object for placeholder interpolation. ```typescript // Component using translations import { FC } from 'react' import { useTranslation } from 'react-i18next' import { ElText, ElButton } from '~/components' const ProfileHeader: FC = () => { // Always get translation inside component, never via props const { t } = useTranslation() const userName = 'John Doe' const loginDate = '2025-11-19' return ( <> {t('mobile.profile.settings.greeting', { userName })} {t('mobile.profile.settings.lastLogin', { loginDate })} {t('mobile.common.save')} ) } ``` -------------------------------- ### Configure i18n Translation Keys in JSON Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Defines translation keys using semantic hierarchical structure in Russian language JSON file. Keys follow a namespace pattern (mobile.section.subsection.key) and use camelCase variables in double curly braces for placeholder interpolation. ```json // front/lang/ru.json { "mobile": { "common": { "save": "Сохранить", "cancel": "Отменить", "edit": "Редактировать" }, "profile": { "settings": { "title": "Настройки профиля", "greeting": "Привет, {{userName}}!", "lastLogin": "Последний вход: {{loginDate}}" }, "logout": "Выйти" }, "errors": { "networkError": "Ошибка сети. Проверьте подключение.", "invalidData": "Некорректные данные" } } } ``` -------------------------------- ### Create Type-Safe API Response Interface Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Defines UserProfileResponse interface that combines UserResource with additional profile metadata. This response type is used with TypeScript's generic axios type parameter to ensure type safety for API responses. ```typescript // mobile/src/types/server/UserProfileResponse.ts import type { UserResource } from './resources/User' interface UserProfileResponse { /** User profile data */ user: UserResource /** Profile completion percentage */ completeness: number /** Last login timestamp */ lastLogin: string } export type { UserProfileResponse } ``` -------------------------------- ### Define TypeScript User Resource Interface Source: https://context7.com/sulumov/mediacube-ai-agent-rules/llms.txt Defines a UserResource interface representing core user data with typed role field. This interface serves as the base data structure for user-related API responses and component props, ensuring type safety across the application. ```typescript // mobile/src/types/server/resources/User.ts interface UserResource { /** Unique user identifier */ id: number /** User's email address */ email: string /** Display name */ name: string /** User role from constants */ role: 'admin' | 'user' | 'moderator' /** Account creation timestamp */ createdAt: string } export type { UserResource } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.