PROJECT OVERVIEW:
The application, codenamed 'ArtDi' (Artistic Dimensions), is a web-based platform that empowers users to create, share, and explore interactive 3D visualizations. It bridges the gap between art and mathematics by simplifying the creation of complex visual concepts like M. C. Escher-inspired spirals, fractal geometries, and scientific simulations. The core value proposition is to make advanced mathematical and artistic concepts accessible and engaging through interactive visualization, inspired by content like 3Blue1Brown's educational videos.
TECH STACK:
- Frontend: React (Next.js App Router)
- Styling: Tailwind CSS
- UI Components: shadcn/ui
- State Management: Zustand or Jotai for global state, React Context for local state.
- Database: PostgreSQL
- ORM: Drizzle ORM
- Authentication: NextAuth.js (with PostgreSQL adapter)
- 3D Rendering: Three.js (for WebGL rendering and scene management)
- Shader Language: GLSL (for custom fragment shaders)
- Deployment: Vercel
- Other: React Hook Form (for forms), Zod (for schema validation), Recharts (for potential analytics dashboards).
DATABASE SCHEMA:
1. **users**
- `id` (UUID, primary key)
- `name` (VARCHAR(255))
- `email` (VARCHAR(255), unique)
- `emailVerified` (TIMESTAMPZ)
- `image` (VARCHAR(255))
- `createdAt` (TIMESTAMPZ, default NOW())
- `updatedAt` (TIMESTAMPZ)
2. **accounts** (NextAuth.js requirement)
- `id` (VARCHAR(255), primary key)
- `userId` (UUID, foreign key to users.id)
- `type` (VARCHAR(255))
- `provider` (VARCHAR(255))
- `providerAccountId` (VARCHAR(255))
- `refresh_token` (TEXT)
- `access_token` (TEXT)
- `expires_at` (BIGINT)
- `token_type` (VARCHAR(255))
- `scope` (VARCHAR(255))
- `id_token` (TEXT)
- `session_state` (TEXT)
3. **sessions** (NextAuth.js requirement)
- `sessionToken` (VARCHAR(255), primary key)
- `userId` (UUID, foreign key to users.id)
- `expires` (TIMESTAMPZ)
4. **verificationTokens** (NextAuth.js requirement)
- `identifier` (VARCHAR(255))
- `token` (VARCHAR(255))
- `expires` (TIMESTAMPZ)
5. **visualizations**
- `id` (UUID, primary key)
- `userId` (UUID, foreign key to users.id, nullable if public creation allowed without auth)
- `title` (VARCHAR(255), not null)
- `description` (TEXT)
- `shaderCode` (TEXT, GLSL code)
- `parameters` (JSONB, e.g., {'zoom': 1.0, 'color': '#FF0000', 'iterations': 10})
- `isPublic` (BOOLEAN, default false)
- `createdAt` (TIMESTAMPZ, default NOW())
- `updatedAt` (TIMESTAMPZ)
- `thumbnailUrl` (VARCHAR(255), optional)
6. **likes**
- `id` (BIGSERIAL, primary key)
- `userId` (UUID, foreign key to users.id)
- `visualizationId` (UUID, foreign key to visualizations.id)
- `createdAt` (TIMESTAMPZ, default NOW())
- UNIQUE (`userId`, `visualizationId`)
7. **comments**
- `id` (BIGSERIAL, primary key)
- `userId` (UUID, foreign key to users.id)
- `visualizationId` (UUID, foreign key to visualizations.id)
- `content` (TEXT, not null)
- `createdAt` (TIMESTAMPZ, default NOW())
CORE FEATURES & USER FLOW:
**1. User Authentication:**
- Flow: User lands on the homepage -> Clicks 'Sign In' -> Presented with options (Google, GitHub, Email/Password) -> Logs in via chosen provider -> Redirected to dashboard/homepage with authenticated state.
- Components: SignIn button, Auth providers component, SignOut button.
- Edge Cases: Invalid credentials, OAuth callback errors, email verification pending.
**2. Visualization Editor:**
- Flow: Authenticated user navigates to 'Editor' page -> Sees a default visualization (e.g., simple spiral) -> Can modify parameters (sliders, color pickers) via UI controls -> The 3D canvas updates in real-time using Three.js and the fragment shader.
- User can optionally edit the GLSL shader code directly in a code editor component.
- User clicks 'Save' -> Modal appears to enter title, description, set privacy (public/private) -> Visualization is saved to the database.
- Components: VisualizationCanvas (Three.js scene), ParameterControls (sliders, color pickers), ShaderEditor (Monaco Editor or similar), SaveModalForm.
- Edge Cases: Shader compilation errors, invalid parameter values, saving errors, unauthorized access to edit private visualizations.
**3. Gallery & Exploration:**
- Flow: User navigates to 'Gallery' page -> Sees a grid of publicly shared visualizations (thumbnails or dynamic previews) -> Can filter/sort (e.g., by date, likes) -> Clicks on a visualization -> Navigates to a detail page displaying the visualization, its title, description, creator, and comments.
- Components: VisualizationGrid, VisualizationCard, FilterSortControls, VisualizationDetailView.
- Edge Cases: Empty gallery, loading states, pagination if many visualizations exist.
**4. Liking & Commenting:**
- Flow: On the Visualization Detail page, authenticated users see 'Like' button and 'Comment' input -> Clicks 'Like' -> Button state updates, like count increments.
- User types a comment in the input field and clicks 'Submit' -> Comment appears in the comment list below.
- Components: LikeButton, CommentForm, CommentList.
- Edge Cases: Liking/commenting without authentication, duplicate likes, profanity filtering (optional).
API & DATA FETCHING:
- **API Routes (Next.js App Router - `app/api/...` or Server Actions):**
- `POST /api/auth/...`: Handled by NextAuth.js.
- `POST /api/visualizations`: Save new visualization (requires auth). Payload: `{ title, description, shaderCode, parameters, isPublic }`. Response: `{ success: true, id: '...' }`.
- `PUT /api/visualizations/[id]`: Update existing visualization (requires auth, ownership check). Payload: Similar to POST.
- `GET /api/visualizations`: Fetch public visualizations (for gallery). Query params: `?page=1&limit=20&sortBy=createdAt&order=desc`.
- `GET /api/visualizations/[id]`: Fetch single visualization details.
- `POST /api/visualizations/[id]/like`: Like a visualization (requires auth). Response: `{ liked: true/false, count: ... }`.
- `DELETE /api/visualizations/[id]/like`: Unlike a visualization (requires auth).
- `POST /api/visualizations/[id]/comments`: Add a comment (requires auth). Payload: `{ content }`. Response: `{ success: true, comment: {...} }`.
- `GET /api/visualizations/[id]/comments`: Fetch comments for a visualization.
- **Data Fetching:** Use Server Components where possible for initial data loads (e.g., Gallery, Visualization Details). Use Client Components with libraries like SWR or React Query for dynamic data updates (e.g., like counts, comments) or client-side state requiring interaction.
COMPONENT BREAKDOWN:
- **Pages (`app/...`):**
- `layout.tsx`: Root layout, global providers, navigation.
- `page.tsx` (Homepage): Introduction, featured visualizations, call to action.
- `editor/page.tsx`: Main visualization editor interface.
- `gallery/page.tsx`: Grid display of public visualizations.
- `visualizations/[id]/page.tsx`: Detail view of a single visualization.
- `auth/[...nextauth]/route.ts`: NextAuth.js API route.
- `profile/page.tsx`: User profile page (view owned visualizations, settings).
- `settings/page.tsx`: Account settings page.
- **UI Components (`components/ui`, `components/shared`, `components/editor` etc.):**
- `Navbar`: Site navigation, logo, auth status.
- `Footer`: Standard footer links.
- `SignInButton`: Initiates the sign-in process.
- `SignOutButton`: Logs the user out.
- `VisualizationCard`: Renders a preview/thumbnail of a visualization in grids/lists.
- `VisualizationCanvas`: The core WebGL/Three.js component rendering the visualization.
- `ParameterControls`: UI elements (sliders, inputs, color pickers) for adjusting visualization parameters.
- `ShaderEditor`: Integrated code editor for GLSL shader programming.
- `SaveModalForm`: Form for saving/updating visualization details.
- `CommentForm`: Input field and submit button for adding comments.
- `CommentList`: Displays comments for a visualization.
- `LikeButton`: Toggles like status for a visualization.
- `LoadingSpinner`: Generic loading indicator.
- `ErrorMessage`: Displays error messages.
- `ResponsiveContainer`: Wrapper for making canvases responsive.
- **State Management:**
- Global state (e.g., auth status, user preferences) via Zustand/Context.
- Editor state (current shader code, parameters, scene objects) managed within the `Editor` page or using a state management library. `useThree` hooks within the `VisualizationCanvas` component.
- Form state managed by React Hook Form.
- Server cache state managed by SWR/React Query.
UI/UX DESIGN & VISUAL IDENTITY:
- **Style:** Modern, clean, with a touch of minimalist elegance and subtle futuristic elements. Focus on showcasing the visualizations themselves.
- **Color Palette:**
- Primary: Dark background (e.g., `#0A0A0A` - Deep Space Black)
- Accent 1: Vibrant, glowing cyan (`#00FFFF` - Electric Cyan) for interactive elements, highlights, and active states.
- Accent 2: A softer, scientific blue (`#4D90FE` - Cerulean Blue) for secondary information and UI elements.
- Text: Off-white (`#F0F0F0` - Ghost White).
- **Typography:** A clean, sans-serif font family like 'Inter' or 'Poppins' for readability. Use varying weights for hierarchy.
- **Layout:** Utilize a responsive grid system (Tailwind CSS). Generous spacing. Content areas should feel focused. The `VisualizationCanvas` should dominate its container. Sidebar for editor controls if needed.
- **Animations:** Subtle, smooth transitions for UI elements (e.g., button hovers, modal appearances). Loading animations should be non-intrusive (e.g., subtle spinners, skeleton loaders). Canvas animations driven by WebGL/shader performance.
- **Responsive Rules:** Mobile-first approach. Navigation collapses into a hamburger menu. Grids adapt to screen size. Editor controls might become a bottom sheet or collapsible sidebar on smaller screens.
ANIMATIONS:
- **UI Elements:** Tailwind CSS transitions on hover for buttons, links, cards (`transition-all duration-300 ease-in-out`).
- **Modals/Drawers:** Fade-in/slide-in animations using libraries like Framer Motion or CSS transitions.
- **Loading States:** `LoadingSpinner` component with a subtle rotation or pulsing effect. For data loading, use skeleton screens that mimic the card/list structure.
- **Canvas:** Animations inherent to the visualizations created via shaders and Three.js. Ensure smooth frame rates.
EDGE CASES:
- **Initial State (Empty Gallery/Profile):** Display friendly messages and clear calls to action (e.g., 'Create your first visualization!', 'No public visualizations yet. Be the first!'). Use placeholder cards or empty states.
- **Authentication:** Handle scenarios where a user tries to access protected routes without being logged in (redirect to sign-in). Ensure proper session management and token refresh.
- **Error Handling:** Implement global error handling (e.g., using Context API or a dedicated error boundary) and specific error messages for API failures, shader compilation errors, invalid inputs. Display user-friendly error messages.
- **Validation:** Use Zod for robust server-side and client-side validation of forms (visualization details, comments) and API payloads.
- **Shader Errors:** Provide clear feedback to the user if their GLSL code fails to compile, highlighting the error lines if possible.
- **Unsaved Changes:** Warn users if they try to navigate away from the editor with unsaved changes.
SAMPLE DATA:
1. **User:**
```json
{
"id": "uuid-user-1",
"name": "Alex Glitch",
"email": "alex.glitch@example.com",
"image": "https://example.com/avatars/alex.png"
}
```
2. **Visualization (Escher-like Spiral):**
```json
{
"id": "uuid-vis-1",
"userId": "uuid-user-1",
"title": "Infinite Escher Spiral",
"description": "A recursive spiral effect inspired by M. C. Escher's gallery print.",
"shaderCode": "uniform float iTime; uniform vec2 iResolution; ... (GLSL code) ...",
"parameters": {"zoom": 1.2, "colorA": "#FF00FF", "colorB": "#00FFFF", "iterations": 15, "speed": 0.5},
"isPublic": true,
"createdAt": "2023-10-27T10:00:00Z",
"thumbnailUrl": "/thumbnails/vis-1.jpg"
}
```
3. **Visualization (Mandelbrot Set):**
```json
{
"id": "uuid-vis-2",
"userId": null, // Publicly created example
"title": "Classic Mandelbrot Explorer",
"description": "Interactive Mandelbrot set fractal visualization.",
"shaderCode": "uniform float iTime; uniform vec2 iResolution; ... (GLSL code) ...",
"parameters": {"iterations": 100, "escapeRadius": 2.0, "centerX": -0.75, "centerY": 0.0, "zoom": 1.0},
"isPublic": true,
"createdAt": "2023-10-26T14:30:00Z",
"thumbnailUrl": "/thumbnails/vis-2.jpg"
}
```
4. **Comment:**
```json
{
"id": 1,
"userId": "uuid-user-1",
"visualizationId": "uuid-vis-2",
"content": "Incredible detail! How did you achieve that smooth color transition?",
"createdAt": "2023-10-27T11:00:00Z",
"user": {"name": "Alex Glitch", "image": "https://example.com/avatars/alex.png"} // Included for display
}
```
5. **Like:**
```json
{
"id": 101,
"userId": "uuid-user-1",
"visualizationId": "uuid-vis-1",
"createdAt": "2023-10-27T10:05:00Z"
}
```
6. **User Profile Data (for profile page):**
```json
{
"user": {"name": "Alex Glitch", "email": "...", "image": "..."},
"visualizations": [
// Array of visualization objects created by Alex
{ "id": "uuid-vis-1", "title": "Infinite Escher Spiral", "isPublic": true, "updatedAt": "..." },
{ "id": "uuid-vis-3", "title": "My Abstract Shape", "isPublic": false, "updatedAt": "..." }
]
}
```
7. **Gallery Fetch Response:**
```json
{
"visualizations": [
// Array of visualization objects for the gallery grid
{ "id": "uuid-vis-1", "title": "Infinite Escher Spiral", "thumbnailUrl": "...", "user": {"name": "Alex Glitch"}, "likeCount": 25 },
{ "id": "uuid-vis-2", "title": "Classic Mandelbrot Explorer", "thumbnailUrl": "...", "user": {"name": "Guest Artist"}, "likeCount": 42 }
],
"hasNextPage": true,
"totalPages": 15
}
```