# Design Document: Ultimate Lists App ## Overview The Ultimate Lists App is a Next.js 14-based Progressive Web App that provides an enhanced task management experience. The application uses a server-side architecture with React Server Components for optimal performance, Prisma ORM with MySQL for data persistence, and PWA capabilities for offline functionality and home screen installation on iOS devices. The system is built on a three-tier architecture: 1. **Presentation Layer**: React components with Server Components and Client Components 2. **Business Logic Layer**: Server Actions for data mutations and queries 3. **Data Layer**: Prisma ORM with MySQL database The application leverages Next.js App Router for routing, Server Actions for data mutations, and implements PWA features through a service worker and web app manifest. ## Architecture ### High-Level Architecture ``` ┌─────────────────────────────────────────────────────────┐ │ Client Browser │ │ ┌──────────────────────────────────────────────────┐ │ │ │ React Components (RSC + Client) │ │ │ │ ┌────────────┐ ┌────────────┐ ┌───────────┐ │ │ │ │ │ Pages │ │ Components │ │ Hooks │ │ │ │ │ └────────────┘ └────────────┘ └───────────┘ │ │ │ └──────────────────────────────────────────────────┘ │ │ ┌──────────────────────────────────────────────────┐ │ │ │ Service Worker (PWA) │ │ │ │ Cache API + Offline Support │ │ │ └──────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────┘ │ │ HTTP/Server Actions ▼ ┌─────────────────────────────────────────────────────────┐ │ Next.js Server │ │ ┌──────────────────────────────────────────────────┐ │ │ │ Server Actions │ │ │ │ (lib/actions.ts - Business Logic) │ │ │ └──────────────────────────────────────────────────┘ │ │ ┌──────────────────────────────────────────────────┐ │ │ │ Prisma Client │ │ │ │ (lib/db.ts - Data Access) │ │ │ └──────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────┘ │ │ SQL ▼ ┌─────────────────────────────────────────────────────────┐ │ MySQL Database │ │ (Lists, Items, Metadata) │ └─────────────────────────────────────────────────────────┘ ``` ### Technology Stack - **Framework**: Next.js 14 with App Router - **Language**: TypeScript - **UI Library**: React 18 with Server Components - **Styling**: Tailwind CSS - **Database**: MySQL - **ORM**: Prisma - **Icons**: Lucide React - **PWA**: Service Worker + Web App Manifest ## Components and Interfaces ### Data Access Layer **Prisma Client (`lib/db.ts`)** - Singleton Prisma client instance - Connection pooling management - Type-safe database queries **Server Actions (`lib/actions.ts`)** - `getLists()`: Retrieve all lists with item counts - `createList(title, color)`: Create a new list - `updateList(id, data)`: Update list properties - `deleteList(id)`: Delete a list and cascade to items - `getListWithItems(listId)`: Retrieve a specific list with all items - `createItem(listId, title, description, metadata)`: Create a new item - `updateItem(id, data)`: Update item properties - `deleteItem(id)`: Delete an item - `toggleItem(id)`: Toggle item completion status - `searchItems(query)`: Search across all items - `getItemsByFilter(listId, filters)`: Filter items by criteria ### Presentation Layer **Pages** - `/` - Home page displaying all lists - `/list/[id]` - Individual list view with items - `/list/[id]/item/[itemId]` - Item detail view **Components** - `ListCard`: Display list summary with item count - `ListForm`: Create/edit list form - `ItemCard`: Display individual item - `ItemForm`: Create/edit item form with metadata - `ItemDetail`: Full item view with all metadata - `SearchBar`: Search input with live results - `FilterPanel`: Filter controls for sorting and filtering - `PriorityBadge`: Visual priority indicator - `DueDateDisplay`: Due date with overdue indication - `TagList`: Display and manage item tags **Client Hooks** - `useOptimisticUpdate`: Optimistic UI updates - `useSearch`: Search functionality with debouncing - `useFilters`: Filter state management - `useOfflineSync`: Handle offline data synchronization ### PWA Layer **Service Worker (`public/sw.js`)** - Cache static assets (HTML, CSS, JS, images) - Cache API responses with stale-while-revalidate strategy - Offline fallback pages - Background sync for pending mutations **Web App Manifest (`public/manifest.json`)** - App metadata (name, icons, colors) - Display mode: standalone - Start URL and scope - Icon definitions for various sizes ## Data Models ### Database Schema **List Model** ```typescript { id: string (cuid) title: string color: string (hex color) createdAt: DateTime updatedAt: DateTime items: Item[] } ``` **Item Model** ```typescript { id: string (cuid) title: string description: string | null completed: boolean priority: 'low' | 'medium' | 'high' dueDate: DateTime | null tags: string[] (JSON) notes: string | null createdAt: DateTime updatedAt: DateTime listId: string list: List } ``` ### Client State Models **FilterState** ```typescript { priority: 'low' | 'medium' | 'high' | null completed: boolean | null tags: string[] dueDateRange: { start: Date | null, end: Date | null } sortBy: 'createdAt' | 'dueDate' | 'priority' | 'title' sortOrder: 'asc' | 'desc' } ``` **SearchState** ```typescript { query: string results: Item[] isSearching: boolean } ``` ## Correctness Properties *A property is a characteristic or behavior that should hold true across all valid executions of a system—essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.* ### Task Management Properties **Property 1: Task creation preserves description** *For any* valid task description and list, creating a task with that description should result in a task that, when retrieved, has the exact same description. **Validates: Requirements 1.1** **Property 2: Task updates preserve identity** *For any* task and any valid update data, updating the task should preserve the task's unique identifier while changing the specified fields. **Validates: Requirements 1.2** **Property 3: Task deletion removes from queries** *For any* task, after deleting that task, querying for tasks should not return the deleted task. **Validates: Requirements 1.3** **Property 4: Task metadata round-trip** *For any* task and any valid metadata (priority, due date, tags, notes), setting the metadata then retrieving the task should return equivalent metadata values. **Validates: Requirements 1.4, 5.1, 5.2, 5.3, 5.4** **Property 5: Task completion toggle** *For any* task, toggling its completion status should result in the opposite completion state when retrieved. **Validates: Requirements 1.5** ### List Management Properties **Property 6: List creation with unique identifiers** *For any* valid list name, creating a list should result in a list with a unique identifier that differs from all existing list identifiers. **Validates: Requirements 2.1** **Property 7: List retrieval completeness** *For any* set of created lists, querying all lists should return exactly those lists with accurate item counts. **Validates: Requirements 2.2** **Property 8: List filtering correctness** *For any* list, querying items for that list should return only items where the listId matches, and should return all such items. **Validates: Requirements 2.3** **Property 9: Cascade deletion** *For any* list with associated items, deleting the list should result in both the list and all its items being removed from the database. **Validates: Requirements 2.4** **Property 10: List rename preserves items** *For any* list with items, renaming the list should preserve the count and identifiers of all associated items. **Validates: Requirements 2.5** ### Data Persistence Properties **Property 11: Application state round-trip** *For any* application state (lists and items), persisting the state, simulating an app restart, and loading the state should result in equivalent data. **Validates: Requirements 3.1, 3.2, 3.3, 3.4, 3.5** ### Offline and PWA Properties **Property 12: Offline resource availability** *For any* cached resource, when the application is offline, requesting that resource should succeed using the cached version. **Validates: Requirements 4.4** **Property 13: Offline mutation synchronization** *For any* mutation performed while offline, when connectivity is restored, the mutation should be applied to the server and reflected in subsequent queries. **Validates: Requirements 4.5** ### Enhanced Features Properties **Property 14: Overdue task identification** *For any* task with a due date in the past relative to the current time, the task should be marked as overdue. **Validates: Requirements 5.5** ### Sorting and Filtering Properties **Property 15: Sort order correctness** *For any* list of tasks and sort criteria (createdAt, dueDate, priority, title), the sorted result should be ordered according to the specified criteria and direction. **Validates: Requirements 6.1** **Property 16: Filter matching correctness** *For any* filter criteria, all returned tasks should match the criteria, and all tasks in the database matching the criteria should be returned. **Validates: Requirements 6.2** **Property 17: Compound filter conjunction** *For any* set of multiple filter criteria, all returned tasks should match every criterion (AND logic). **Validates: Requirements 6.3** **Property 18: Filter clear restoration** *For any* filtered view, clearing all filters should return the complete unfiltered task list. **Validates: Requirements 6.4** **Property 19: Null due date sorting** *For any* list of tasks sorted by due date, tasks without due dates should appear after all tasks with due dates. **Validates: Requirements 6.5** ### Navigation Properties **Property 20: Scroll position preservation** *For any* scroll position in a view, navigating away and returning to that view should restore the same scroll position. **Validates: Requirements 7.4** ### Search Properties **Property 21: Search result completeness** *For any* search query, all returned tasks should contain the query text in their description, notes, or tags, and all tasks containing the query should be in the results. **Validates: Requirements 8.1** **Property 22: Search highlight correctness** *For any* search query and matching text, the highlight function should mark all occurrences of the query text in the result. **Validates: Requirements 8.2** **Property 23: Search clear restoration** *For any* search state, clearing the search query should restore the previous unfiltered view. **Validates: Requirements 8.3** **Property 24: Search scope correctness** *For any* search query, when no list is selected, results should include matches from all lists; when a list is selected, results should only include matches from that list. **Validates: Requirements 8.5** ## Error Handling ### Database Errors **Connection Failures** - Retry logic with exponential backoff - Graceful degradation to cached data - User notification of connectivity issues **Constraint Violations** - Validate data before database operations - Return descriptive error messages - Prevent orphaned records through transactions **Query Failures** - Catch and log database errors - Return empty results rather than crashing - Provide user-friendly error messages ### Client-Side Errors **Invalid Input** - Validate form inputs before submission - Display inline validation errors - Prevent submission of invalid data **Network Errors** - Queue mutations for retry when offline - Show offline indicator - Sync when connection restored **State Inconsistencies** - Implement optimistic updates with rollback - Validate state before rendering - Recover from corrupted local storage ### PWA-Specific Errors **Service Worker Registration** - Gracefully handle registration failures - Fall back to online-only mode - Log errors for debugging **Cache Failures** - Handle quota exceeded errors - Implement cache eviction strategy - Provide fallback for uncached resources ## Testing Strategy ### Unit Testing The application will use **Vitest** as the testing framework for unit tests. Unit tests will focus on: **Data Access Layer** - Server action functions (create, read, update, delete operations) - Database query correctness - Error handling in database operations **Business Logic** - Filter logic implementation - Sort algorithm correctness - Search algorithm accuracy - Date calculations (overdue detection) **Utility Functions** - Data serialization/deserialization - Input validation - Text highlighting for search results **Component Logic** - Form validation - State management - Event handlers Unit tests will use realistic test data and verify specific examples, edge cases, and error conditions. They complement property-based tests by catching concrete bugs in specific scenarios. ### Property-Based Testing The application will use **fast-check** as the property-based testing library. Property-based tests will verify the universal correctness properties defined in this document. **Configuration Requirements:** - Each property-based test MUST run a minimum of 100 iterations - Each test MUST be tagged with a comment referencing the correctness property - Tag format: `// Feature: ultimate-lists-app, Property {number}: {property_text}` - Each correctness property MUST be implemented by a SINGLE property-based test **Property Test Coverage:** - Task CRUD operations (Properties 1-5) - List CRUD operations (Properties 6-10) - Data persistence and round-trips (Property 11) - Offline functionality (Properties 12-13) - Enhanced features (Property 14) - Sorting and filtering (Properties 15-19) - Navigation behavior (Property 20) - Search functionality (Properties 21-24) **Test Data Generation:** Property-based tests will use custom generators for: - Valid task descriptions (non-empty strings) - List names (non-empty strings) - Priority levels (low, medium, high) - Due dates (past, present, future) - Tags (arrays of strings) - Filter criteria (combinations of filters) - Sort options (field and direction) - Search queries (substrings of existing data) ### Integration Testing Integration tests will verify: - End-to-end user flows (create list → add items → complete items) - Server Action integration with database - PWA installation and offline functionality - Service worker caching behavior ### Manual Testing Manual testing will cover: - PWA installation on iOS Safari - Offline functionality in real-world scenarios - UI/UX on various screen sizes - Touch interaction quality - Visual design and accessibility ## Performance Considerations ### Database Optimization - Index frequently queried fields (listId, completed, dueDate, priority) - Use database-level sorting and filtering where possible - Implement pagination for large lists - Use connection pooling for efficient database access ### Client-Side Optimization - Use React Server Components for initial page loads - Implement optimistic updates for perceived performance - Lazy load item details - Debounce search input - Virtualize long lists ### Caching Strategy - Cache static assets aggressively (CSS, JS, images) - Use stale-while-revalidate for API responses - Implement cache versioning for updates - Set appropriate cache expiration times ### Bundle Optimization - Code splitting by route - Tree shaking unused code - Minimize and compress assets - Use Next.js automatic optimizations ## Security Considerations ### Input Validation - Sanitize all user inputs - Validate data types and formats - Prevent SQL injection through Prisma's parameterized queries - Limit input lengths to prevent abuse ### Data Protection - Use environment variables for sensitive configuration - Implement HTTPS in production - Secure database credentials - Validate all server-side inputs ### PWA Security - Serve service worker over HTTPS - Validate cached resources - Implement Content Security Policy - Use Subresource Integrity for external resources ## Deployment Considerations ### Environment Setup - Development: Local MySQL database - Production: Managed MySQL instance (e.g., PlanetScale, AWS RDS) - Environment variables for database connection - Separate environments for testing and production ### Build Process 1. Run database migrations (`prisma db push`) 2. Generate Prisma client 3. Build Next.js application 4. Generate service worker 5. Optimize and compress assets ### Hosting - Deploy to Vercel (recommended for Next.js) - Configure custom domain - Set up SSL certificate - Configure environment variables ### Monitoring - Error tracking (e.g., Sentry) - Performance monitoring - Database query performance - User analytics (optional) ## Future Enhancements ### Potential Features - Collaborative lists (multi-user) - Recurring tasks - Task dependencies - Attachments and file uploads - Calendar integration - Notifications and reminders - Dark mode - Customizable themes - Export/import functionality - Task templates - Subtasks and checklists - Time tracking - Analytics and insights ### Technical Improvements - Real-time synchronization with WebSockets - Backend API for mobile apps - Advanced caching strategies - Performance optimizations - Accessibility improvements - Internationalization (i18n)