## AI Master Prompt for 'Life Database Analyzer' SaaS Application
### 1. PROJECT OVERVIEW
The 'Life Database Analyzer' is a Single Page Application (SPA) designed to empower individuals to collect, analyze, and gain actionable insights from their personal life data. Inspired by the user's journey of "putting their whole life into a single database," this application provides a centralized platform to track diverse metrics such as health, nutrition, sleep, computer usage, social interactions, location, mood, and more. The core value proposition is to transform raw personal data into meaningful knowledge, enabling users to understand the correlations between different aspects of their lives, identify trends, answer personal "what if" questions, and ultimately make data-driven decisions to improve their well-being, productivity, and overall life satisfaction. It aims to be an intuitive, visually engaging, and deeply personal analytics tool.
### 2. TECH STACK
* **Frontend Framework:** React (using functional components and Hooks)
* **State Management:** Zustand (lightweight, performant, and easy to integrate for global state)
* **UI Library/Framework:** Tailwind CSS (for rapid, utility-first styling and responsive design)
* **Routing:** React Router DOM (for client-side routing)
* **Charting Library:** Chart.js or Recharts (for data visualization)
* **Date/Time Handling:** date-fns or Moment.js
* **Form Handling:** React Hook Form (for efficient form validation and management)
* **Build Tool:** Vite (for fast development server and optimized builds)
* **Deployment:** Netlify or Vercel (for seamless SPA deployment)
* **Local Storage:** `localStorage` API for persisting user preferences and potentially caching data for offline access or faster loading.
### 3. CORE FEATURES (MVP)
**A. Data Input Module:**
* **User Flow:** Users navigate to the 'Add Entry' section. They select a category (e.g., 'Nutrition', 'Sleep', 'Computer Time', 'Mood', 'Location'). Based on the category, relevant input fields appear (e.g., for 'Nutrition': Food item, amount, calories, macros; for 'Sleep': Start time, end time, quality rating; for 'Computer Time': Hours spent, primary activity). Users fill in the details and click 'Save'. Upon saving, a success message is displayed, and the user is redirected to the dashboard or confirmation page.
* **Details:** Input forms should be dynamic based on category selection. Include date/time pickers. Implement basic validation (e.g., numbers for calories, valid time formats). Option to add free-text notes for each entry.
**B. Dashboard & Visualization:**
* **User Flow:** Upon login, users are directed to their main dashboard. The dashboard displays a summary of recent entries and key trend charts. Users can select different time ranges (Day, Week, Month, Year, Custom) to view their data. They can click on specific charts or data points to drill down for more details or navigate to the analysis section.
* **Details:** Display a summary card of today's key metrics (e.g., calories consumed vs. goal, hours slept, computer time). Render line charts for time-series data (e.g., weight over time, sleep duration over time, computer hours per day). Include bar charts for categorical comparisons (e.g., mood distribution). Use Chart.js/Recharts for interactive charts.
**C. Basic Analysis & Correlation:**
* **User Flow:** Users navigate to the 'Analysis' section. They can select two or more data points/metrics (e.g., 'Sleep Hours', 'Computer Time', 'Mood Score'). The system calculates and displays potential correlations (e.g., using scatter plots or correlation matrices). Users can ask predefined questions like "How does sleep affect my mood?" or "What is the relationship between computer time and productivity?".
* **Details:** Implement basic statistical calculations for correlation (e.g., Pearson correlation coefficient). For predefined questions, provide curated visualizations that best answer them. Initially, focus on correlations between health metrics, productivity metrics, and mood.
**D. User Profile & Settings:**
* **User Flow:** Users can access their profile to update personal information (height, weight goal, calorie goal, etc.) and manage account settings (password, email). Settings might include preferences for units (kg/lbs, kcal/kJ) and default views.
* **Details:** Store user profile information and preferences. This section is crucial for personalizing goals and calculations (e.g., daily calorie needs).
**E. Authentication:**
* **User Flow:** Users can sign up with email/password or log in. A password reset functionality should be available. Upon successful login, user data is fetched.
* **Details:** Standard email/password authentication. Secure password storage (hashing). Session management using tokens or similar mechanisms.
### 4. UI/UX DESIGN
* **Layout:** A clean, modern, single-page application layout. A persistent sidebar navigation for accessing Dashboard, Data Input, Analysis, and Settings. The main content area displays the relevant section. Responsive design is critical, ensuring usability on desktop, tablet, and mobile devices.
* **Color Palette:** A calming and professional primary color palette (e.g., shades of blue, teal, or grey) with accent colors (e.g., green for positive trends, orange/red for negative alerts or high values) for data visualization and interactive elements. Ensure good contrast for accessibility.
* **Typography:** Use a clean, readable sans-serif font family (e.g., Inter, Poppins, or system fonts). Establish a clear typographic hierarchy for headings, subheadings, body text, and labels.
* **Component Styling:** Tailwind CSS utility classes will be used extensively. Components should be modular and reusable. Focus on clarity and ease of use for data entry and interpretation.
* **Responsive Design:** Mobile-first approach. Sidebar might collapse into a hamburger menu on smaller screens. Charts and tables should adapt to screen width, potentially stacking or scrolling horizontally.
* **Micro-interactions:** Subtle animations on button clicks, form submissions, and data loading states to provide visual feedback and enhance the user experience.
### 5. DATA MODEL & STATE MANAGEMENT
* **State Management (Zustand):** Global state will manage user authentication status, profile data, fetched datasets, UI states (loading, error), and potentially application settings. Local component state will handle form inputs, UI element states (e.g., dropdown open/closed), and temporary UI interactions.
* **Data Structures (Mock Data Examples):**
```json
// User Profile
{
"id": "user123",
"email": "felix@example.com",
"heightCm": 193,
"weightKg": 81.8,
"weightHistory": [
{"date": "2023-10-26T10:00:00Z", "weightKg": 81.8}
],
"goals": {
"caloriesPerDay": 2920,
"proteinPerDayGrams": 200,
"fatPerDayGrams": 80,
"carbsPerDayGrams": 350,
"sleepHoursPerNight": 8
},
"settings": {
"units": "metric", // or "imperial"
"theme": "light" // or "dark"
}
}
// Food Entry
{
"entryId": "food_abc",
"userId": "user123",
"timestamp": "2023-10-27T08:00:00Z",
"category": "Nutrition",
"details": {
"foodName": "Club Mate",
"amount": "500 ml",
"calories": 210,
"proteinGrams": 0,
"carbsGrams": 23,
"fatGrams": 0
},
"notes": "Morning hydration"
}
// Sleep Entry
{
"entryId": "sleep_def",
"userId": "user123",
"category": "Sleep",
"details": {
"startTime": "2023-10-26T23:00:00Z",
"endTime": "2023-10-27T08:00:00Z",
"durationHours": 9,
"quality": 5 // Scale 1-5
},
"notes": "Felt very rested."
}
// Computer Time Entry
{
"entryId": "comp_ghi",
"userId": "user123",
"timestamp": "2023-10-27T14:30:00Z", // Approximate start of session
"category": "Computer Usage",
"details": {
"durationHours": 4.5,
"primaryActivity": "Development",
"details": "Worked on data visualization graphs."
},
"notes": "Focused work session."
}
// Mood Entry
{
"entryId": "mood_jkl",
"userId": "user123",
"timestamp": "2023-10-27T18:00:00Z",
"category": "Mood",
"details": {
"mood": "Happy", // Options: Happy, Excited, Neutral, Sad, Angry, etc.
"intensity": 7 // Scale 1-10
},
"notes": "Good progress on project."
}
```
* **Data Storage:** Initially, use `localStorage` for simplicity and offline capability. For a production SaaS, this would be replaced by a backend database (e.g., PostgreSQL, MongoDB) with API endpoints for data fetching and storage.
### 6. COMPONENT BREAKDOWN
* **`App.js`:** Main application component, sets up routing and global layout.
* **`Layout.js`:** Wrapper component containing the sidebar navigation and main content area.
* **`Sidebar.js`:** Navigation menu component. Renders links to different app sections. Manages active link state.
* **`DashboardPage.js`:** Main dashboard view. Fetches and displays summary data and key charts.
* **`SummaryCard.js`:** Displays key metrics for the current day/period.
* **`TimeSeriesChart.js`:** Reusable chart component for displaying data over time (e.g., weight, sleep).
* **`CategoryDistributionChart.js`:** Reusable chart for displaying categorical data (e.g., mood, food types).
* **`DataInputPage.js`:** Page for adding new data entries.
* **`DataEntryForm.js`:** Dynamic form component that renders input fields based on selected category.
* **`CategorySelector.js`:** Dropdown or buttons to select data category.
* **`InputField.js`:** Generic input field component.
* **`DatePicker.js`:** Date and time picker component.
* **`TextArea.js`:** For notes.
* **`SaveButton.js`:** Handles form submission logic.
* **`AnalysisPage.js`:** Page for exploring data correlations and trends.
* **`CorrelationMatrix.js`:** Displays correlation coefficients between selected metrics.
* **`ScatterPlot.js`:** Visualizes the relationship between two specific metrics.
* **`PredefinedQuestionViewer.js`:** Component to display results for curated analytical questions.
* **`SettingsPage.js`:** User profile and application settings.
* **`ProfileForm.js`:** Form for updating user profile details.
* **`SettingsForm.js`:** Form for managing preferences (units, theme).
* **`AuthPage.js`:** Handles Login and Sign Up forms.
* **`LoginForm.js`:** Email/password login form.
* **`SignUpForm.js`:** Email/password registration form.
* **`LoadingSpinner.js`:** Global loading indicator component.
* **`ErrorMessage.js`:** Component for displaying error messages.
### 7. ANIMATIONS & INTERACTIONS
* **Page Transitions:** Subtle fade-in/fade-out transitions between different sections using `react-router-dom` and CSS.
* **Chart Interactions:** Hover effects on chart data points to show tooltips with precise values. Smooth transitions when updating chart data.
* **Button Interactions:** Subtle scale or background color changes on hover and click for buttons.
* **Form Feedback:** Input field validation errors appear with a slight shake or color change. Successful submission shows a temporary success message or animation.
* **Loading States:** Display `LoadingSpinner` components overlaid on charts or data sections while data is being fetched. Skeleton loaders can be used for a smoother perceived performance.
* **Sidebar Toggle:** Smooth slide or fade animation when the sidebar collapses/expands on smaller screens.
### 8. EDGE CASES & ACCESSIBILITY (a11y)
* **Empty States:** Display informative messages and clear calls-to-action when there is no data (e.g., "No sleep data yet. Add your first entry to start tracking!"). This applies to the dashboard, charts, and analysis sections.
* **Error Handling:** Gracefully handle API errors or data fetching failures. Display user-friendly error messages using `ErrorMessage.js` component. Implement retry mechanisms where appropriate.
* **Input Validation:** Robust validation on all input fields using `react-hook-form`. Ensure data integrity before saving.
* **Data Type Consistency:** Ensure all data entries adhere to expected formats (numbers, dates, strings). Implement type checking.
* **Accessibility (a11y):**
* Use semantic HTML elements (`<nav>`, `<main>`, `<button>`, etc.).
* Ensure sufficient color contrast for text and UI elements.
* Provide `alt` text for meaningful images and icons.
* Ensure keyboard navigability for all interactive elements.
* Use ARIA attributes where necessary to enhance screen reader experience.
* Labels for form elements are correctly associated.
* **Offline Support:** Basic data entry and viewing might be possible using `localStorage` even when offline (requires a service worker implementation for more robust offline capabilities).
### 9. SAMPLE DATA (Additional Examples)
```json
// Location Entry
{
"entryId": "loc_mno",
"userId": "user123",
"timestamp": "2023-10-20T12:00:00Z",
"category": "Location",
"details": {
"city": "Vienna",
"country": "AT",
"type": "Current Location"
},
"notes": "Attending a conference."
}
// Website Visitors Entry (Example Aggregate Data)
{
"entryId": "web_pqr",
"userId": "user123",
"timestamp": "2023-08-01T00:00:00Z", // Represents data since this date
"category": "Website Analytics",
"details": {
"uniqueVisitorsSinceStart": 162457,
"totalVisitsSinceStart": 500000 // Example
},
"notes": "Website analytics tracking started."
}
// Last Code Commit Entry
{
"entryId": "code_stu",
"userId": "user123",
"timestamp": "2023-10-27T17:00:00Z", // Example timestamp
"category": "Development",
"details": {
"repository": "krausefx.com",
"commitMessage": "Improve design of graph on GitHub repo",
"commitHash": "a1b2c3d4e5f67890",
"author": "KrauseFx"
},
"notes": "Minor UI adjustment."
}
```
### 10. DEPLOYMENT NOTES
* **Build Command:** `npm run build` (or `yarn build`) using Vite. This generates optimized static assets in the `dist` folder.
* **Environment Variables:** Use `.env` files for managing environment variables (e.g., `NODE_ENV`, API URLs if a backend is added later). Ensure sensitive variables are not committed to version control.
* **Routing Configuration:** For SPAs deployed on platforms like Netlify/Vercel, ensure a `_redirects` file or equivalent configuration is in place to handle client-side routing correctly (e.g., `/* /index.html 200`).
* **Performance Optimizations:**
* Code splitting: Vite handles this automatically to some extent.
* Lazy loading: Implement lazy loading for components, especially routes that are not critical for initial view (e.g., Analysis page, Settings).
* Image optimization: If images are added, use appropriate formats and sizes.
* Memoization: Use `React.memo`, `useMemo`, `useCallback` judiciously to prevent unnecessary re-renders.
* **Local Storage Limits:** Be mindful of browser `localStorage` limits (typically 5-10MB). For applications expecting very large datasets, a backend solution is necessary.
* **Initial Data Load:** Optimize the initial data fetch on the dashboard to load essential data quickly. Consider fetching less critical data asynchronously.