Reusable UI Components
Relevant source files
The following files were used as context for generating this wiki page:
The ElmecV2 application is built using a component-based architecture with React Native and Expo. This approach promotes code reuse, maintainability, and a consistent user interface across the application. Components range from simple, single-purpose elements like an image viewer to complex, feature-rich modules like an administrative dashboard.
These components often encapsulate specific functionality, manage their own state, and interact with application-wide contexts like AuthContext and ChatContext. The project leverages lucide-react-native for iconography, ensuring a clean and consistent visual language. This document details some of the key reusable components and composite UI screens found within the project.
Admin Dashboard
The AdminDashboard component provides a comprehensive overview of system metrics for users with the 'admin' role. It is a self-contained module that displays key statistics, charts, and quick actions. The component ensures that only authorized users can view its content.
Sources: components/AdminDashboard.tsx
Architecture and Composition
The dashboard is composed of several nested, memoized functional components to optimize rendering performance. It fetches and displays mock statistical data, indicating its current state as a template for future API integration.
The following diagram illustrates the component hierarchy of the AdminDashboard.
Sources: components/AdminDashboard.tsx:18-350
Core Components
StatCard
A reusable card to display a single, prominent statistic. It includes an icon, title, value, and an optional trend indicator.
| Prop | Type | Description |
|---|---|---|
title | string | The main label for the statistic. |
value | string | number | The primary value to display. |
subtitle | string | Optional text displayed below the title. |
icon | React.ReactNode | An icon element, typically from lucide-react-native. |
color | string | The base color for the icon and its background. |
trend | { value: number; isPositive: boolean } | Optional trend data to show percentage change. |
| Sources: components/AdminDashboard.tsx:97-103 |
SimpleChart
A basic bar chart component for visualizing data distributions. It dynamically calculates bar heights based on the maximum value in the dataset.
Sources: components/AdminDashboard.tsx:150-176
Data Handling
Currently, the dashboard uses a static, mock DashboardStats object initialized within a useEffect hook. This data is used to populate the StatCard components and the SimpleChart. In a production environment, this would be replaced with API calls to a backend service.
// Mock data - En producción esto vendría de la API
useEffect(() => {
const mockStats: DashboardStats = {
totalUsers: 156,
activeUsers: 89,
totalRequests: 342,
pendingRequests: 23,
resolvedRequests: 298,
totalMessages: 1247,
avgResponseTime: 2.4,
satisfactionRate: 4.6,
};
setTimeout(() => {
setStats(mockStats);
setLoading(false);
}, 1000);
}, [selectedPeriod]);
Sources: components/AdminDashboard.tsx:43-61
Access Control
The component checks the user.rol property from the useAuth context. If the role is not 'admin', it renders an "Access Denied" message.
Sources: components/AdminDashboard.tsx:178-189
System Health Check
The HealthCheck component is a diagnostic tool that provides a real-time status of the application's connection to backend services, primarily Supabase. It leverages the useSupabaseHealth custom hook to perform checks and display the results.
Sources: components/HealthCheck.tsx
Features
- Connection Status: Verifies network connectivity.
- Authentication Check: Confirms the user is authenticated with Supabase.
- Database Accessibility: Ensures the database is reachable.
- Real-time Service: Checks the status of the real-time (WebSocket) connection.
- Error Reporting: Lists any errors encountered during the checks.
- Manual Refresh: Allows the user to trigger a new health check on demand.
The following flowchart shows the logic for displaying the status of a single health check item.
Sources: components/HealthCheck.tsx:13-23
Status Items
The component renders a list of system aspects and their current health.
| Service | Icon | Checked Property |
|---|---|---|
| Conexión | Wifi | health.isConnected |
| Autenticación | Shield | health.isAuthenticated |
| Base de Datos | Database | health.databaseAccessible |
| Tiempo Real | Zap | health.realtimeConnected |
| Sources: components/HealthCheck.tsx:29-54 |
Chat Room UI
The chat room screen, located at app/(tabs)/chat/[roomId].tsx, is a complex composite component that brings together numerous UI elements to create a feature-rich messaging interface similar to modern chat applications like WhatsApp.
Sources: app/(tabs)/chat/[roomId].tsx
UI Composition
The screen is structured into several distinct parts:
- Header: Displays the other participant's name and status (online or typing).
- Message List: A
FlatListthat renders the conversation history usingrenderMessage. - Input Area: A highly dynamic section for text input, sending messages, and accessing other features.
- Modals & Overlays: Several components that appear over the main UI, such as the emoji picker, attachment menu, message actions menu, and image viewer.
This diagram shows the user interaction flow for sending a message with an attachment.
Key UI Features
Message Input Bar
The input bar dynamically changes based on user input and actions.
- If the text input is empty, it shows a
Micicon for voice recording. - If the user is typing, it shows a
Sendbutton. - If a message is being edited, it shows "Save" and "Cancel" buttons.
Sources: app/(tabs)/chat/[roomId].tsx:1280-1329
Message Actions
A long-press on any message bubble triggers a context menu with several actions. The available actions depend on whether the user is the sender of the message.
| Action | Availability | Icon |
|---|---|---|
| Copiar | Always | Copy |
| Responder | Always | Reply |
| Editar | Sender only | Edit3 |
| Eliminar | Sender only | Trash2 |
| Sources: app/(tabs)/chat/[roomId].tsx:1332-1383 |
Attachment Handling
The chat interface supports sending images, photos from the camera, and general documents. Each action involves:
- Requesting necessary permissions (
ImagePicker.request...PermissionsAsync). - Launching the native picker (
ImagePicker.launch...Async,DocumentPicker.getDocumentAsync). - Uploading the selected file to Supabase Storage via
uploadFileToStorage. - Sending a new message of type
image,audio, orfilewith the public URL.
Sources: app/(tabs)/chat/[roomId].tsx:405-580
Image Viewer
A modal component used for displaying images in full-screen. It is used within the chat screen to view image attachments.
Sources: components/ImageViewer.tsx, app/(tabs)/chat/[roomId].tsx:806-819, 1386-1391
Props
| Prop | Type | Description |
|---|---|---|
images | { uri: string }[] | An array of image objects to be displayed in the gallery view. |
imageIndex | number | The initial index of the image to display from the images array. |
visible | boolean | Controls the visibility of the image viewer modal. |
onRequestClose | () => void | A callback function to handle the closing of the viewer. |
| Sources: components/ImageViewer.tsx, app/(tabs)/chat/[roomId].tsx:1386-1391 |
Usage
When a user taps on an image in the chat, the handleImagePress function is called. This function filters all messages to find images, sets the imageViewerImages state, calculates the correct starting index, and then sets imageViewerVisible to true, which renders the ImageViewer component.
Sources: app/(tabs)/chat/[roomId].tsx:806-819
Conclusion
The ElmecV2 project demonstrates a strong, component-oriented design. By creating reusable components like AdminDashboard, HealthCheck, and ImageViewer, and by composing them into complex screens like the chat room, the application achieves a high degree of code reuse and separation of concerns. This modularity simplifies development, testing, and future maintenance. The consistent use of hooks for state management and side effects further enhances the clarity and predictability of the codebase.