|
| 1 | +# Smart Task Hub Frontend - AI Copilot Instructions |
| 2 | + |
| 3 | +## Project Overview |
| 4 | +**Smart Task Hub** is a collaborative kanban board application built with React + TypeScript. It features real-time collaboration via WebSockets, role-based access control, and drag-and-drop task management. |
| 5 | + |
| 6 | +**Stack**: Vite, React 18, TypeScript, Redux Toolkit, TailwindCSS, @dnd-kit, Axios, WebSockets |
| 7 | + |
| 8 | +--- |
| 9 | + |
| 10 | +## Architecture |
| 11 | + |
| 12 | +### State Management (Redux Toolkit with Persistence) |
| 13 | +- **Store**: `src/store/index.ts` - Configured with redux-persist (only `auth` slice persisted) |
| 14 | +- **Auth slice** (`src/store/slices/authSlice.ts`): Handles login, logout, role management |
| 15 | +- **Domain slices**: `columnsSlice`, `tasksSlice`, `membersSlice`, `archiveColumnsSlice`, `archiveTasksSlice` |
| 16 | +- **Pattern**: Async thunks for API calls + normalized state shape (byId/allIds objects) |
| 17 | +- **Selectors** (`src/store/selectors/`): Use reselect-like pattern to avoid redundant renders |
| 18 | +- **Key exports**: `useAppDispatch`, `useAppSelector` from `src/store/index.ts` |
| 19 | + |
| 20 | +### Authentication & Authorization |
| 21 | +- **Custom hook** `useAuth()` (`src/hooks/useAuth.ts`): Returns `isAuthenticated`, `userRole`, `isLoading`, `isInitialized` |
| 22 | +- **Protected routes**: `src/components/guards/ProtectedRoute.tsx` - Guards routes by role, redirects to login if needed |
| 23 | +- **Roles**: `'admin' | 'user'` (stored in Redux, persisted to localStorage) |
| 24 | +- **API**: Auth status checked on app start via `checkAuthStatus()` thunk |
| 25 | + |
| 26 | +### Real-Time Collaboration (WebSocket) |
| 27 | +- **Connection**: `src/services/websocketService.ts` - Connects to `ws://localhost:9000/ws/project/{projectId}` |
| 28 | +- **Message handler**: `src/websocket/boardHandler.ts` - Routes incoming WS messages to Redux actions |
| 29 | +- **Patterns handled**: `COLUMN_MOVED`, `COLUMN_CREATED`, `TASK_MOVED`, `TASK_CREATED`, `COLUMN_STATUS_UPDATED`, `TASK_ASSIGNED`, etc. |
| 30 | +- **Integration**: Board component calls `connectToProjectWS()` on mount, disconnects on unmount |
| 31 | + |
| 32 | +### Service Layer Pattern |
| 33 | +- **Centralized axios client**: `src/services/axiosClient.ts` - Interceptors handle response unwrapping (returns `response.data`) |
| 34 | +- **Service modules**: `boardService.ts`, `taskService.ts`, `authService.ts`, `memberService.ts`, `workspaceService.ts` |
| 35 | +- **Base URL**: From `VITE_API_URL` env var (defaults to `http://localhost:9000/api`) |
| 36 | +- **Naming convention**: Service functions use snake_case (e.g., `fetchBoardDetail`, `updateColumnPosititon`) |
| 37 | + |
| 38 | +### Drag-and-Drop (dnd-kit) |
| 39 | +- **Library**: `@dnd-kit/core` + `@dnd-kit/sortable` |
| 40 | +- **Setup**: `src/components/board/BoardContent.tsx` - Uses `DndContext`, `DragOverlay`, `SortableContext` |
| 41 | +- **Components**: `DroppableColumn` (container), `DraggableItem` (tasks) |
| 42 | +- **Position tracking**: Columns/tasks use numeric `position` field (typically incremented by 1000) |
| 43 | +- **Handlers**: `onDragEnd()` calls `updateColumnPosititon()` or `reorderTasksInColumn()` to sync backend |
| 44 | + |
| 45 | +--- |
| 46 | + |
| 47 | +## Key Files & Patterns |
| 48 | + |
| 49 | +### Routing Architecture |
| 50 | +- **File**: `src/router/AppRouter.tsx` |
| 51 | +- **Pattern**: Nested routes with layout wrappers (`AdminLayout`, `UserLayout`) |
| 52 | +- **Guards**: Every non-public route wrapped in `ProtectedRoute` with role check |
| 53 | +- **Fallbacks**: `UnauthorizedFallback`, `NotFound` components for error states |
| 54 | + |
| 55 | +### Type System |
| 56 | +- **Centralized types**: `src/types/` directory with `board.ts`, `user.types.ts`, `workspace.ts`, `collaboration.ts` |
| 57 | +- **Normalized shapes**: |
| 58 | + ```tsx |
| 59 | + // Tasks stored as: { byId: Record<number, Task>, allIds: number[] } |
| 60 | + // Columns stored similarly |
| 61 | + // Selectors extract data: selectTaskById(id)(state) |
| 62 | + ``` |
| 63 | + |
| 64 | +### Component Organization |
| 65 | +- **Layout components**: `src/components/layout/` (AuthLayout, MainLayout, SidebarLayout) |
| 66 | +- **Domain components**: `src/components/board/` (BoardContent, DraggableItem, TaskDetailModal) |
| 67 | +- **UI primitives**: `src/components/ui/` (LoadingSpinner, LoadingContent, card.tsx) |
| 68 | +- **Guards**: `src/components/guards/` (ProtectedRoute, RoleRedirect) |
| 69 | +- **Memo optimization**: Used on expensive components like `DraggableItem` to prevent re-renders |
| 70 | + |
| 71 | +### Custom Hooks |
| 72 | +- **`useAuth()`**: Authentication state + login/logout/checkAuth methods |
| 73 | +- **`useBoardData()`**: Fetches board, columns, tasks, members on mount |
| 74 | +- **`useBoardOperations()`**: CRUD operations for columns (create, update, delete, archive) |
| 75 | + |
| 76 | +### Styling |
| 77 | +- **Framework**: TailwindCSS v4 with @tailwindcss/vite plugin |
| 78 | +- **Custom theme**: `tailwind.config.ts` extends colors (primary, gray) and animations |
| 79 | +- **Utility classes**: Use standard Tailwind + custom animations (fade-in, slide-up, spin-slow) |
| 80 | + |
| 81 | +--- |
| 82 | + |
| 83 | +## Developer Workflows |
| 84 | + |
| 85 | +### Development |
| 86 | +```bash |
| 87 | +npm run dev # Start Vite dev server on port 3000 |
| 88 | +npm run build # TypeScript build + Vite bundle |
| 89 | +npm run lint # ESLint check (4-space indentation, Prettier rules) |
| 90 | +npm run format # Auto-format with Prettier (80-char line width) |
| 91 | +``` |
| 92 | + |
| 93 | +### Testing |
| 94 | +```bash |
| 95 | +npm run test # Run Vitest in watch mode |
| 96 | +npm run test:ui # UI dashboard for test execution |
| 97 | +npm run test:run # Single run (CI mode) |
| 98 | +npm run test:coverage # Coverage report (v8 provider) |
| 99 | +``` |
| 100 | + |
| 101 | +### Type Checking |
| 102 | +```bash |
| 103 | +npx tsc --noEmit # Check for TypeScript errors without emitting |
| 104 | +tsc -b # Used in build script |
| 105 | +``` |
| 106 | + |
| 107 | +### Environment Setup |
| 108 | +- **`.env`**: Set `VITE_API_URL` (e.g., `http://localhost:9000/api`) |
| 109 | +- **Port**: Dev server runs on `localhost:3000` |
| 110 | +- **WebSocket**: Connects to same API host (ws:// scheme) |
| 111 | + |
| 112 | +--- |
| 113 | + |
| 114 | +## Project-Specific Conventions |
| 115 | + |
| 116 | +### Naming |
| 117 | +- **Services**: Action verbs + nouns (`fetchBoardDetail`, `updateColumnTitle`, `archiveColumn`) |
| 118 | +- **State slices**: Plural domain names (`columns`, `tasks`, `members`, `archiveColumns`) |
| 119 | +- **Actions**: PascalCase (`columnCreated`, `taskMoved`, `taskAssigned`) |
| 120 | +- **Thunks**: Suffix with `Thunk` or `Async` (e.g., `archiveColumnThunk`) |
| 121 | + |
| 122 | +### Imports |
| 123 | +- **Path alias**: `@/` resolves to `src/` (configured in vite.config.ts & tsconfig.json) |
| 124 | +- **Pattern**: Import types separately → `import type { Board } from '@/types'` |
| 125 | + |
| 126 | +### Redux Best Practices (enforced) |
| 127 | +1. **State normalization**: Complex data stored by ID (tasks/columns byId + allIds) |
| 128 | +2. **Selectors for derived data**: Avoid inline selectors in components |
| 129 | +3. **Async thunks**: API calls wrapped in thunks, not in components |
| 130 | +4. **Persist only auth**: Other slices reset on page refresh by design |
| 131 | +5. **Immutable updates**: Redux Toolkit handles this via Immer |
| 132 | + |
| 133 | +### Testing Setup |
| 134 | +- **Config**: `vitest.config.ts` + `src/test/setup.ts` |
| 135 | +- **Mocks**: ResizeObserver, IntersectionObserver, window.matchMedia pre-configured |
| 136 | +- **Provider wrapping**: Tests wrap components in Redux Provider + mocked Router |
| 137 | +- **Coverage exclusions**: node_modules, dist, .d.ts, config files |
| 138 | + |
| 139 | +### ESLint & Formatting |
| 140 | +- **Indentation**: 4 spaces (enforced, not tabs) |
| 141 | +- **Semicolons**: Required at statement ends |
| 142 | +- **Quotes**: Single quotes preferred (except JSX attributes) |
| 143 | +- **Line width**: 80 characters (Prettier) |
| 144 | +- **Config**: `eslint.config.js` (new flat config format) |
| 145 | + |
| 146 | +--- |
| 147 | + |
| 148 | +## Common Patterns |
| 149 | + |
| 150 | +### Adding a New Column Type |
| 151 | +1. Create slice in `src/store/slices/myFeatureSlice.ts` |
| 152 | +2. Add to combineReducers in `src/store/index.ts` |
| 153 | +3. Create selectors in `src/store/selectors/myFeatureSelectors.ts` |
| 154 | +4. Use `useAppSelector` + `useAppDispatch` in components |
| 155 | + |
| 156 | +### Creating a Service |
| 157 | +1. Add functions to `src/services/{feature}Service.ts` |
| 158 | +2. Use `axiosClients.get/post/patch/delete` with base URL already set |
| 159 | +3. Type responses with `ApiResponse<T>` wrapper |
| 160 | +4. Call from thunks, not components directly |
| 161 | + |
| 162 | +### Handling Real-Time Updates |
| 163 | +1. Board component establishes WS connection via `connectToProjectWS(boardId, onMessage)` |
| 164 | +2. onMessage handler receives JSON, calls `handleBoardWSMessage()` with store dispatch |
| 165 | +3. WebSocket handler dispatches Redux actions (columnCreated, taskMoved, etc.) |
| 166 | +4. Components re-render automatically via selector changes |
| 167 | + |
| 168 | +### Protected Route Patterns |
| 169 | +```tsx |
| 170 | +<ProtectedRoute adminOnly fallback={<UnauthorizedFallback />}> |
| 171 | + <AdminDashboard /> |
| 172 | +</ProtectedRoute> |
| 173 | + |
| 174 | +// OR with specific role |
| 175 | +<ProtectedRoute requiredRole="user" redirectTo="/login"> |
| 176 | + <UserBoard /> |
| 177 | +</ProtectedRoute> |
| 178 | +``` |
| 179 | + |
| 180 | +--- |
| 181 | + |
| 182 | +## Testing Examples |
| 183 | +- **Unit tests**: Mock Redux store + React Query, test component props/interactions |
| 184 | +- **Integration tests**: Use Redux Provider + mock axios, test data flow |
| 185 | +- **Example**: `src/App.test.tsx` - Mocks AppRouter, renders with store Provider |
| 186 | + |
| 187 | +--- |
| 188 | + |
| 189 | +## Quick Troubleshooting |
| 190 | + |
| 191 | +| Issue | Solution | |
| 192 | +|-------|----------| |
| 193 | +| WebSocket not connecting | Check `ws://` URL format, verify backend on port 9000 | |
| 194 | +| State not persisting | Only `auth` slice persists by design; check redux-persist config | |
| 195 | +| Redux DevTools not opening | Set `NODE_ENV` correctly; uses devTools only in dev | |
| 196 | +| Type errors on async thunks | Import `AppDispatch` from store for dispatch typing | |
| 197 | +| Drag-drop not working | Ensure item has unique `id`, wrapped in `SortableContext` | |
| 198 | + |
| 199 | +--- |
| 200 | + |
| 201 | +## External Resources |
| 202 | +- Redux Toolkit: https://redux-toolkit.js.org |
| 203 | +- dnd-kit: https://docs.dndkit.com |
| 204 | +- Vite: https://vitejs.dev |
| 205 | +- TailwindCSS: https://tailwindcss.com |
0 commit comments