tahamajs/IE / Projects /front /README.md
tahamajs's picture
|
download
raw
23.9 kB
# **IE Research Platform – Frontend**
A comprehensive, production‑ready research collaboration platform built with **React 19**, **TypeScript**, **Vite**, and **Tailwind CSS 4**. This frontend provides real‑time messaging, collaborative document editing, AI‑powered research assistants, lab inventory management, peer review, data visualization, and much more.
[![React](https://img.shields.io/badge/React-19-61dafb?logo=react)](https://react.dev/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.8-3178c6?logo=typescript)](https://www.typescriptlang.org/)
[![Vite](https://img.shields.io/badge/Vite-6-646cff?logo=vite)](https://vitejs.dev/)
[![Tailwind CSS](https://img.shields.io/badge/Tailwind-4-38bdf8?logo=tailwindcss)](https://tailwindcss.com/)
---
## 📋 **Table of Contents**
- [**IE Research Platform – Frontend**](#ie-research-platform--frontend)
- [📋 **Table of Contents**](#-table-of-contents)
- [**1. Overview**](#1-overview)
- [**2. Technology Stack**](#2-technology-stack)
- [**3. Features**](#3-features)
- [**Core Collaboration**](#core-collaboration)
- [**AI‑Powered Tools**](#aipowered-tools)
- [**Research Management**](#research-management)
- [**User Experience**](#user-experience)
- [**4. Getting Started**](#4-getting-started)
- [**Prerequisites**](#prerequisites)
- [**Installation**](#installation)
- [**Environment Variables**](#environment-variables)
- [**Running the Development Server**](#running-the-development-server)
- [**5. Project Structure**](#5-project-structure)
- [**6. Architecture Deep Dive**](#6-architecture-deep-dive)
- [**Routing**](#routing)
- [**State Management (Custom Hooks)**](#state-management-custom-hooks)
- [**Providers \& Context**](#providers--context)
- [**Real‑time Communication (WebSocket)**](#realtime-communication-websocket)
- [**Collaborative Editing (Yjs)**](#collaborative-editing-yjs)
- [**Voice Assistant \& Speech**](#voice-assistant--speech)
- [**Smart Notifications**](#smart-notifications)
- [**RAG (Retrieval‑Augmented Generation)**](#rag-retrievalaugmented-generation)
- [**Workspace \& Panels**](#workspace--panels)
- [**7. Key Pages \& Components**](#7-key-pages--components)
- [**8. Styling \& Theming**](#8-styling--theming)
- [**9. Available Scripts**](#9-available-scripts)
- [**10. Deployment**](#10-deployment)
- [**Building for Production**](#building-for-production)
- [**Serving with Nginx**](#serving-with-nginx)
- [**Environment Variables in Production**](#environment-variables-in-production)
- [**11. Backend API Dependency**](#11-backend-api-dependency)
- [**12. Contributing**](#12-contributing)
- [**13. License**](#13-license)
---
## **1. Overview**
The IE Research Platform Frontend is a **single‑page application** that powers a modern research environment. It connects to a backend REST API (Java Spring Boot / Node.js) and provides a rich, interactive UI for:
- **Messaging & collaboration** (private/group chats, secret chats, voice/video calls)
- **Real‑time collaborative document editing** (papers, grant proposals, protocols)
- **AI‑assisted research** (RAG assistant, gap analysis, grant assistant, multi‑agent debates)
- **Lab inventory management** (chemicals, barcodes, NFPA diamonds)
- **Peer review** (anonymous submissions, reviewing)
- **Personal dashboard** (widgets, streaks, kanban, XP)
- **Data hub** (preregistrations, protocols, research objects)
The application is built with **React 19**, **TypeScript**, **Vite** for blazing fast builds, and **Tailwind CSS 4** for utility‑first styling. It uses **custom hooks** for all business logic, **WebSockets** for real‑time updates, **Yjs** for collaborative editing, and **WebRTC** for voice/video calls.
---
## **2. Technology Stack**
| Category | Technologies |
|----------|--------------|
| **Core** | React 19, TypeScript 5.8, Vite 6 |
| **Routing** | React Router v7 |
| **Styling** | Tailwind CSS 4, tailwindcss-animate, CSS modules (only when needed) |
| **UI Components** | Custom components with Lucide React icons |
| **State & Logic** | React hooks (custom), Context API (few providers) |
| **HTTP Client** | Axios |
| **Real‑time** | Native WebSockets (with fallback via `useWebSocket`) |
| **Collaborative Editing** | Yjs, y-websocket, y-indexeddb, TipTap |
| **Data Visualization** | react-force-graph-2d, d3‑scale, d3‑force |
| **Math & LaTeX** | KaTeX, `@aarkue/tiptap-math-extension` |
| **File Processing** | PapaParse (CSV), Mammoth.js (DOCX), Turndown (HTML→MD) |
| **Export** | jspdf, html2canvas, docx, file‑saver |
| **Voice** | react‑speech‑recognition, Web Speech API |
| **Animation** | Framer Motion |
| **Command Palette** | KBar |
| **Notifications** | react‑toastify |
| **Code Highlighting** | lowlight, react‑syntax‑highlighter |
| **Barcode Scanning** | react‑zxing |
| **Mention Autocomplete** | react‑mentions‑ts |
| **Citations** | citation-js |
---
## **3. Features**
### **Core Collaboration**
- **Unified Inbox** – aggregate messages from direct chats, group chats, project discussions, paper Q&A, and broadcast channels.
- **Real‑time Messaging** – send text, images, files, stickers, voice notes, polls, quizzes; typing indicators, read receipts, reactions.
- **Secret Chats** – end‑to‑end encrypted conversations using Signal protocol.
- **Voice / Video Calls** – WebRTC‑based one‑to‑one calls with screen sharing (optional).
- **Collaborative Document Editor** – real‑time rich text editing (TipTap) with LaTeX math, code blocks, tables, task lists, live preview, and multiple export formats (PDF, DOCX, LaTeX, HTML, Markdown, EPUB).
- **Threaded Comments & Reviews** – inline discussions on documents.
- **Offline Support** – IndexedDB persistence for documents and pending messages.
### **AI‑Powered Tools**
- **RAG Research Assistant** – upload PDFs, ask questions with cited sources (Xenova embeddings, HNSW vector search, LLM backend).
- **Gap Analysis** – knowledge graph visualization (ForceGraph2D) of papers, concepts, methods, findings; AI‑generated hypotheses.
- **Grant Assistant** – upload RFPs, generate proposals, track deadlines.
- **Multi‑Agent Debate** – orchestrate AI agents (Literature Reviewer, Data Extractor, Cross‑Referencer, Paper Analyzer, Summarizer) to discuss research questions.
- **AI Command Palette** – natural language commands with predictive suggestions.
### **Research Management**
- **Lab Inventory** – chemical database with barcode scanning, NFPA 704 diamonds, location management, expiry alerts, compatibility checking.
- **Peer Review** – anonymous paper submission, blind review assignment, scoring, decision letters.
- **Data Hub** – upload research objects (datasets, code, preregistrations), manage lab protocols (with step‑by‑step execution).
- **Project Workspace** – task boards (Kanban), project members, output linking (articles, datasets, presentations).
### **User Experience**
- **Personal Dashboard** – drag‑and‑drop widgets (writing streak, kanban board, discovery feed, XP progress, focus timer, publication stats, upcoming deadlines, quick actions).
- **Voice Assistant** – always‑on speech recognition and synthesis, customizable wake word, context‑aware responses.
- **Smart Notifications** – AI‑priority classification, batching during deep‑work or quiet hours, delivery via toast or batched review panel.
- **Command Palette** (Ctrl+K) – quick navigation, actions, AI predictions.
- **Smart Glass Workspace** – multi‑panel layout (AI chat, editor, browser, lab inventory, gap analysis) with resizable, collapsible, maximizable panels.
- **Dark Mode & 6 Accent Colors** – fully themable, follows system preference.
---
## **4. Getting Started**
### **Prerequisites**
- **Node.js** 20.x or later ([download](https://nodejs.org/))
- **npm** 10+ or **yarn** 1.22+
- Backend API (see [Backend API Dependency](#11-backend-api-dependency)) – must be running for full functionality.
### **Installation**
```bash
# Clone the repository
git clone https://github.com/your-org/ie-research-frontend.git
cd ie-research-frontend
# Install dependencies
npm install
# or
yarn install
```
### **Environment Variables**
Create a `.env` file in the project root. All variables must be prefixed with `VITE_`.
```env
# Backend API (REST)
VITE_API_BASE_URL=http://localhost:3000/api
# Main WebSocket (messaging, presence, notifications)
VITE_WS_URL=ws://localhost:8080/ws
# Collaboration WebSocket (Yjs)
VITE_COLLAB_WS_URL=ws://localhost:9093
# Optional – Google Analytics ID
VITE_GOOGLE_ANALYTICS_ID=G-XXXXXXXXXX
```
> **Note:** These values are compiled at build time. For different environments (staging, production), use `.env.production`, `.env.staging`, etc.
### **Running the Development Server**
```bash
npm run dev
# or
yarn dev
```
The application will be available at `http://localhost:5173`.
The dev server supports hot‑module replacement (HMR) and will automatically reload on changes.
---
## **5. Project Structure**
```
src/
├── App.tsx # Root component: providers, global widgets, routes
├── main.tsx # Entry point
├── index.css # Global styles, Tailwind directives, theme variables
│
├── components/ # Reusable UI components
│ ├── async/ # Offline sync, multi‑agent debate, async video threads
│ ├── authoring/ # Collaborative editor, AI writing assistant, reference manager
│ ├── command‑palette/ # KBar provider and custom actions
│ ├── dashboard/ # Widgets (streak, kanban, xp, discovery, etc.)
│ ├── gap‑analysis/ # Graph canvas, search bar, legend
│ ├── genui/ # Generative UI components (charts, forms, molecules)
│ ├── layout/ # MainLayout, LoadingScreen
│ ├── messages/ # Chat components (ChatSidebar, ChatArea, MessageBubble, etc.)
│ ├── notifications/ # SmartNotificationCenter
│ ├── profile/ # ProfileHub, IdentityVerificationPanel, FeaturedShowcase
│ ├── unified‑chat/ # UnifiedInbox, BroadcastChannelView
│ ├── voice/ # VoiceAssistantWidget, VoiceRecorder, VoiceSettingsModal
│ ├── workspace/ # SmartGlassWorkspace, PanelManager, WebBrowserPanel
│ └── ...
│
├── hooks/ # Custom hooks (all business logic)
│ ├── useAuth.ts # Authentication context
│ ├── useMessaging.ts # Chat, WebSocket, messages
│ ├── useUnifiedInbox.ts # Aggregated inbox
│ ├── useSmartNotifications.ts # Notification batching & AI
│ ├── useRagSystem.ts # RAG assistant (indexing, query)
│ ├── useCollaborativeEditor.ts # Yjs editor, undo/redo
│ ├── useVoiceAssistant.ts # Speech recognition, synthesis
│ ├── useDashboard.ts # User profile, articles, notifications, analytics
│ ├── useProjectTaskManager.ts # Kanban tasks
│ ├── useGapAnalysis.ts # Knowledge graph data
│ └── ... (50+ hooks)
│
├── lib/ # Utilities, API client, WebSocket helpers, types
│ ├── api.ts # Axios instance with auth interceptors
│ ├── auth.ts # AuthProvider context
│ ├── useWebSocket.ts # WebSocket hook (reconnection, message handler)
│ ├── useSecretChat.ts # E2EE (Signal protocol)
│ └── types/ # Shared TypeScript interfaces
│
├── pages/ # Route components (each page imports its own hooks)
│ ├── MessagesPage.tsx
│ ├── UnifiedInboxPage.tsx
│ ├── DashboardPage.tsx
│ ├── SmartGlassPage.tsx
│ ├── CollaborativeAuthoringStudioPage.tsx
│ ├── LabInventoryPage.tsx
│ ├── GapAnalysisPage.tsx
│ ├── GrantAssistantPage.tsx
│ ├── PeerReviewPage.tsx
│ └── ... (40+ pages)
│
├── workers/ # Web Workers (e.g., rag‑worker.ts for embeddings)
│
└── vite-env.d.ts # Vite client types
```
---
## **6. Architecture Deep Dive**
### **Routing**
Routing is entirely client‑side using **React Router v7**. All routes are defined in `App.tsx` inside a `<Routes>` block. The root layout is `<MainLayout>` which provides a collapsible sidebar and top bar.
```tsx
<Route element={<MainLayout />}>
<Route path="/dashboard" element={<DashboardPage />} />
<Route path="/inbox" element={<UnifiedInboxPage />} />
...
</Route>
```
Public routes (login, register, forgot‑password) are not nested in `MainLayout`.
### **State Management (Custom Hooks)**
The application **does not use** Redux, Zustand, or any global state library. Instead, every major feature is encapsulated in a **custom hook** that manages its own state, side effects, and API calls.
Examples:
- `useMessaging` – holds chats, messages, WebSocket connection, sending, reactions.
- `useUnifiedInbox` – fetches and filters messages from multiple origins.
- `useCollaborativeEditor` – Yjs document, undo/redo, export.
- `useRagSystem` – HNSW index, embeddings, query.
Hooks are then imported and used inside pages. This approach keeps components lean and logic testable.
### **Providers & Context**
The root `App` component wraps the entire application with a chain of providers:
1. **`ThemeProvider`** – provides theme mode (light/dark/system) and accent color.
2. **`AuthProvider`** – provides user object, login, logout, token management.
3. **`BrowserRouter`** – React Router.
4. **`KBarProvider`** – command palette library.
5. **`CommandPaletteProvider`** – registers dynamic actions and AI predictions.
6. **`FlowPreservationProvider`** – restores workspace panel state from localStorage.
Global UI widgets (`VoiceAssistantWidget`, `SmartNotificationCenter`, `ToastContainer`) are rendered inside `FlowPreservationProvider` to ensure they are always available.
### **Real‑time Communication (WebSocket)**
A single global WebSocket connection (managed by `useWebSocket`) handles:
- New messages (private / group)
- Typing indicators
- Message status updates (sent/delivered/seen)
- Presence (online/offline)
- Reactions
- Notifications
The connection is established when the user is authenticated and automatically reconnects on failure. The backend should expose a WebSocket endpoint (e.g., `/ws`) that accepts a JWT token.
### **Collaborative Editing (Yjs)**
The **Collaborative Authoring Studio** uses:
- **Yjs** as the CRDT engine.
- **`y-websocket`** for real‑time sync (backend must run a WebSocket server on `ws://localhost:9093` or configurable URL).
- **`y-indexeddb`** for offline persistence – edits are stored locally and synced when online.
- **TipTap** editor with extensions: `Collaboration`, `CollaborationCursor`, `Mathematics`, `CodeBlockLowlight`, etc.
- **UndoManager** from Yjs for undo/redo across collaborators.
All shared data is stored in a Yjs document with a root text field named `"content"`.
### **Voice Assistant & Speech**
- **Speech recognition** uses `react-speech-recognition` (Web Speech API). The hook `useSpeechRecognition` provides transcription, interim results, and error handling with auto‑restart.
- **Speech synthesis** uses the built‑in `speechSynthesis` API. `useSpeechSynthesis` manages voice selection, pitch, rate, and queuing of long texts.
- **Wake word detection** is simulated (custom logic in `useVoiceAssistant`).
- The `VoiceAssistantWidget` is a floating bubble that expands into a full conversation panel.
### **Smart Notifications**
- **User context detection** (`useContextDetector`) monitors activity (mouse, keyboard, scroll, tab focus) to infer whether the user is in deep work, focus, idle, or available.
- **Notification batching**: messages with priority "low" or "informational" are batched for up to 30 minutes, then delivered as a summary toast.
- **AI priority classification** (optional) uses a local transformer model (`useLocalNotificationClassifier`) to override heuristic priority.
- **Settings** are persisted in `localStorage` and synced with the backend.
### **RAG (Retrieval‑Augmented Generation)**
The `useRagSystem` hook implements a complete RAG pipeline client‑side:
- **Document ingestion**: supported formats (PDF, HTML, TXT). Chunked in the **worker** (`rag-worker.ts`) and embedded with `@xenova/transformers` (all‑MiniLM‑L6‑v2).
- **Vector storage**: HNSW index (`mememo`) stored in memory, with IndexedDB backup for chunks.
- **Query**: embeds the user question, searches HNSW for top‑K chunks, builds a prompt with context, sends to LLM backend (`/ai/rag-chat`), and extracts citations.
- **Performance**: Web Worker prevents UI blocking. All models run in‑browser (embeddings) but LLM inference is done server‑side.
### **Workspace & Panels**
`SmartGlassWorkspace` provides a flexible multi‑panel environment:
- **Panel types**: AI chat, generative UI, collaborative editor, molecule viewer, lab inventory, gap analysis, grant assistant, messages, articles, web browser.
- **Layout persistence** in localStorage.
- **Resizable and collapsible** panels with drag‑and‑drop.
- **Custom event `smartglass:open-panel`** allows the command palette to open panels.
- **PanelManager** lazy‑loads each panel component, reducing initial bundle size.
---
## **7. Key Pages & Components**
| Page | Description |
|------|-------------|
| **`MessagesPage`** | Complete messaging interface: sidebar with chat list, chat area with message bubbles, reply preview, file attachments, stickers, voice messages, polls, thread panel, selection mode, multi‑forward, group info, secret chat toggle. |
| **`UnifiedInboxPage`** | Aggregates all messages from across the platform (direct, groups, projects, broadcasts, paper Q&A, AI chats). Filter by tab, priority, search, date range. |
| **`DashboardPage`** | Customizable drag‑and‑drop widget dashboard (streak, kanban, discovery feed, writing goal, pomodoro, publication stats, deadlines, XP). Widgets can be added/removed and layouts saved. |
| **`CollaborativeAuthoringStudioPage`** | Real‑time document editor with AI writing assistant, reference manager (DOI, BibTeX, Zotero, Mendeley), figure manager, comment/review panel, export (PDF, DOCX, LaTeX, HTML, MD, EPUB). |
| **`SmartGlassPage`** | Multi‑panel workspace: user can open any combination of panels (AI chat, editor, browser, lab inventory, gap analysis, etc.) and arrange them. |
| **`LabInventoryPage`** | Chemical inventory management: list view / grid view, barcode scanner modal, NFPA 704 diamond visualisation, location management, expiry alerts, chemical compatibility check. |
| **`GapAnalysisPage`** | Interactive knowledge graph (force‑directed) of papers, concepts, methods, findings, gaps. Node search, filter by type, AI‑generated hypothesis. |
| **`ResearchAssistantPage`** | RAG assistant: upload documents, ask questions, see citations. Shows indexing progress, chat history. |
| **`GrantAssistantPage`** | Upload RFP, generate proposal draft, view deadlines. |
| **`PeerReviewPage`** | Browse submissions (anonymous), claim reviews, submit scores and comments. |
| **`ProfileHubPage`** | User profile with identity verification (email, ORCID, institutional vetting), featured showcase (papers, datasets, presentations). |
---
## **8. Styling & Theming**
- **Tailwind CSS 4** with `@theme` directive defines CSS variables for colors, spacing, radii, etc.
- **Light / dark mode** toggled via CSS class on `<html>`. The `ThemeProvider` adds `.dark` class automatically based on system preference or user selection.
- **Accent colors**: six theme classes (`.theme-blue`, `.theme-green`, `.theme-purple`, `.theme-orange`, `.theme-rose`, `.theme-amber`) override the `--primary` and `--ring` CSS variables.
- **Glassmorphism** – `.glass` class applies a blurred semi‑transparent background with border and shadow.
- **Aurora background** – `.aurora-bg` used on the main layout for a subtle animated gradient.
- All custom components use Tailwind utility classes; there is almost no custom CSS outside `index.css`.
---
## **9. Available Scripts**
| Script | Description |
|--------|-------------|
| `npm run dev` | Start Vite development server (hot reload) |
| `npm run build` | Type‑check (`tsc`) and then build with Vite |
| `npm run preview` | Preview the production build locally |
| `npm run lint` | Run ESLint on the codebase |
---
## **10. Deployment**
### **Building for Production**
```bash
npm run build
```
The built files will be in the `dist` folder.
### **Serving with Nginx**
Example configuration for a static site with API proxying:
```nginx
server {
listen 80;
server_name yourdomain.com;
root /var/www/ie-research-frontend/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://backend-server:3000/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /ws/ {
proxy_pass http://backend-server:8080/ws/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /collab-ws/ {
proxy_pass http://collab-server:9093/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
```
### **Environment Variables in Production**
Because Vite embeds environment variables at build time, you must set them before running `npm run build`. For different environments (staging, production), use `.env.production`, `.env.staging`, etc. Example:
```bash
# .env.production
VITE_API_BASE_URL=https://api.ieresearch.org/api
VITE_WS_URL=wss://api.ieresearch.org/ws
VITE_COLLAB_WS_URL=wss://collab.ieresearch.org
```
Then build with:
```bash
npm run build -- --mode production
```
---
## **11. Backend API Dependency**
This frontend **requires** a backend API implementing the endpoints documented in the [API Documentation](./API.md). Essential endpoints include:
- Authentication (`/login`, `/register`, `/users/me`)
- Articles (`/articles`, `/articles/search`)
- Messaging (`/conversations`, `/groups`, `/messages`)
- Notifications (`/notifications`)
- Real‑time WebSocket for messaging (`/ws`)
- Collaboration WebSocket for Yjs (`/collab`)
- RAG endpoints (`/ai/rag-chat`, `/ai/chat`)
- Lab inventory (`/inventory/chemicals`)
- Peer review (`/peer-review/submissions`)
- Grants, gap analysis, etc.
Without a running backend, the frontend will show errors for any authenticated or data‑fetching operations.
---
## **12. Contributing**
1. **Fork** the repository.
2. **Create a feature branch**: `git checkout -b feature/your-feature`
3. **Make your changes**, ensuring they follow the existing coding style (ESLint, Prettier if configured).
4. **Run linting**: `npm run lint`
5. **Commit** with a clear message.
6. **Push** to your fork and open a Pull Request.
Coding guidelines:
- Use TypeScript strictly – avoid `any` whenever possible.
- Write custom hooks for any reusable logic (keep components dumb).
- Use Tailwind CSS classes; avoid custom CSS.
- Ensure dark mode support for any new UI.
- Add proper error handling and loading states.
---
## **13. License**
This project is proprietary and confidential. All rights reserved. For internal use only.
---
**Built with ❤️ by the IE Research Team**
Questions? Contact `dev@ieresearch.or

Xet Storage Details

Size:
23.9 kB
·
Xet hash:
cea3e9ac63c6c9f30c6e9ec4cf34e57f8787c791ae16932ca4c13f772d0eb1f5

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.