UNPKG

sourabhrealtime

Version:

ROBUST RICH TEXT EDITOR: Single-pane contentEditable with direct text selection formatting, speech features, undo/redo, professional UI - Perfect TipTap alternative

672 lines (590 loc) 26.2 kB
import React, { useState, useEffect, useRef, useCallback } from 'react'; import io from 'socket.io-client'; const SaaSCollaboration = ({ apiUrl = 'http://localhost:3002' }) => { // State const [currentUser, setCurrentUser] = useState(null); const [isAuthenticated, setIsAuthenticated] = useState(false); const [showLogin, setShowLogin] = useState(true); const [loading, setLoading] = useState(false); const [connected, setConnected] = useState(false); // Project state const [projects, setProjects] = useState([]); const [currentProject, setCurrentProject] = useState(null); const [projectContent, setProjectContent] = useState(''); // UI state const [showCreateProject, setShowCreateProject] = useState(false); const [showAdminPanel, setShowAdminPanel] = useState(false); // Data const [allUsers, setAllUsers] = useState([]); const [invitations, setInvitations] = useState([]); const [notifications, setNotifications] = useState([]); const [collaborators, setCollaborators] = useState([]); const [typingUsers, setTypingUsers] = useState([]); const [mouseCursors, setMouseCursors] = useState([]); // Forms const [loginForm, setLoginForm] = useState({ email: '', password: '' }); const [projectForm, setProjectForm] = useState({ name: '', description: '' }); const [selectedUsersToInvite, setSelectedUsersToInvite] = useState([]); const socketRef = useRef(null); // Supabase API const supabaseAPI = { async authenticateUser(email, password) { try { const response = await fetch(`https://supabase.merai.app/rest/v1/users?email=eq.${encodeURIComponent(email)}&select=*`, { headers: { 'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJzZXJ2aWNlX3JvbGUiLAogICAgImlzcyI6ICJzdXBhYmFzZS1kZW1vIiwKICAgICJpYXQiOiAxNjQxNzY5MjAwLAogICAgImV4cCI6IDE3OTk1MzU2MDAKfQ.DaYlNEoUrrEn2Ig7tqibS-PHK5vgusbcbo7X36XVt4Q', 'Authorization': `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJzZXJ2aWNlX3JvbGUiLAogICAgImlzcyI6ICJzdXBhYmFzZS1kZW1vIiwKICAgICJpYXQiOiAxNjQxNzY5MjAwLAogICAgImV4cCI6IDE3OTk1MzU2MDAKfQ.DaYlNEoUrrEn2Ig7tqibS-PHK5vgusbcbo7X36XVt4Q`, 'Content-Type': 'application/json' } }); if (response.ok) { const users = await response.json(); if (users.length > 0) { const user = users[0]; return { success: true, user: { id: user.id, email: user.email, name: user.name, role: user.role || 'user', avatar: user.avatar_url, color: user.color || '#6366f1' } }; } } return { success: false, message: 'Invalid credentials' }; } catch (error) { return { success: false, message: 'Authentication failed' }; } } }; const UserRole = { SUPER_ADMIN: 'super_admin', ADMIN: 'admin', USER: 'user' }; // Load session useEffect(() => { const savedUser = localStorage.getItem('saas_user'); const savedToken = localStorage.getItem('saas_token'); if (savedUser && savedToken) { const user = JSON.parse(savedUser); setCurrentUser(user); setIsAuthenticated(true); setShowLogin(false); loadUserData(user); connectSocket(user); } }, []); const addNotification = useCallback((message, type = 'info') => { const notification = { id: Date.now(), message, type }; setNotifications(prev => [...prev, notification]); setTimeout(() => { setNotifications(prev => prev.filter(n => n.id !== notification.id)); }, 4000); }, []); const handleLogin = useCallback(async (e) => { e.preventDefault(); setLoading(true); try { const result = await supabaseAPI.authenticateUser(loginForm.email, loginForm.password); if (result.success) { setCurrentUser(result.user); setIsAuthenticated(true); setShowLogin(false); localStorage.setItem('saas_user', JSON.stringify(result.user)); localStorage.setItem('saas_token', 'dummy-token'); addNotification(`Welcome ${result.user.name}! 🎉`, 'success'); loadUserData(result.user); connectSocket(result.user); } else { addNotification(result.message, 'error'); } } catch (error) { addNotification('Login failed', 'error'); } finally { setLoading(false); } }, [loginForm, addNotification]); const loadUserData = useCallback(async (user) => { try { // Load projects const projectsRes = await fetch(`${apiUrl}/api/projects?userId=${user.id}&userRole=${user.role}`); if (projectsRes.ok) { const data = await projectsRes.json(); setProjects(data.projects || []); } // Load invitations const invitationsRes = await fetch(`${apiUrl}/api/invitations/${user.id}`); if (invitationsRes.ok) { const data = await invitationsRes.json(); setInvitations(data.invitations || []); } } catch (error) { console.error('Error loading user data:', error); } }, [apiUrl]); const connectSocket = useCallback((user) => { if (socketRef.current) return; try { const socket = io(apiUrl); socketRef.current = socket; socket.on('connect', () => { setConnected(true); addNotification('Connected to server', 'success'); // Register user socket.emit('register-user', { userId: user.id, userInfo: user }); }); socket.on('disconnect', () => { setConnected(false); addNotification('Disconnected from server', 'error'); }); // All users event for super admin socket.on('all-users', (users) => { setAllUsers(users); console.log(`Received ${users.length} users for admin panel`); }); // Project events socket.on('project-created', (data) => { if (data.success) { setProjects(prev => [data.project, ...prev]); addNotification(`Project "${data.project.name}" created!`, 'success'); } }); socket.on('project-joined', (data) => { setCurrentProject(data.project); setProjectContent(data.project.content); setCollaborators(data.roomUsers || []); }); socket.on('user-joined-project', (data) => { setCollaborators(prev => [...prev.filter(u => u.id !== data.user.id), data.user]); addNotification(`${data.user.name} joined`, 'info'); }); socket.on('user-left-project', (data) => { setCollaborators(prev => prev.filter(u => u.id !== data.userId)); }); socket.on('content-updated', (data) => { setProjectContent(data.content); }); // Invitation events socket.on('pending-invitations', (invitations) => { setInvitations(invitations); if (invitations.length > 0) { addNotification(`You have ${invitations.length} pending invitations!`, 'info'); } }); socket.on('invitation-received', (invitation) => { setInvitations(prev => [...prev, invitation]); addNotification(`New invitation: "${invitation.projectName}"`, 'success'); }); socket.on('invitation-sent', (data) => { if (data.success) { addNotification('Invitation sent!', 'success'); } }); socket.on('invitation-accepted', (result) => { if (result.success) { setProjects(prev => [...prev, result.project]); setInvitations(prev => prev.filter(inv => inv.projectId !== result.project.id)); addNotification(`Joined "${result.project.name}"!`, 'success'); } }); // Real-time features socket.on('user-typing', (data) => { if (data.isTyping) { setTypingUsers(prev => [...prev.filter(u => u.user.id !== data.user.id), data]); } else { setTypingUsers(prev => prev.filter(u => u.user.id !== data.user.id)); } }); socket.on('mouse-update', (data) => { setMouseCursors(prev => { const filtered = prev.filter(c => c.user.id !== data.user.id); return [...filtered, data]; }); setTimeout(() => { setMouseCursors(prev => prev.filter(c => c.timestamp > Date.now() - 2000)); }, 2000); }); socket.on('error', (data) => { addNotification(data.message, 'error'); }); } catch (error) { addNotification('Failed to connect', 'error'); } }, [apiUrl, addNotification]); const createProject = useCallback(async (e) => { e.preventDefault(); if (currentUser.role !== UserRole.SUPER_ADMIN) { addNotification('Only super admins can create projects', 'error'); return; } if (socketRef.current) { socketRef.current.emit('create-project', { projectData: projectForm, creatorId: currentUser.id, userRole: currentUser.role }); } setShowCreateProject(false); setProjectForm({ name: '', description: '' }); }, [currentUser, projectForm, addNotification]); const joinProject = useCallback((project) => { setCurrentProject(project); setProjectContent(project.content); if (socketRef.current) { socketRef.current.emit('join-project', { projectId: project.id, user: currentUser }); } addNotification(`Joined "${project.name}"`, 'success'); }, [currentUser, addNotification]); const handleContentChange = useCallback((newContent) => { setProjectContent(newContent); if (socketRef.current && currentProject) { socketRef.current.emit('content-update', { projectId: currentProject.id, content: newContent, userId: currentUser.id }); } }, [currentProject, currentUser]); const inviteUsers = useCallback(() => { if (!currentProject || selectedUsersToInvite.length === 0) return; selectedUsersToInvite.forEach(userId => { if (socketRef.current) { socketRef.current.emit('send-invitation', { projectId: currentProject.id, targetUserId: userId, invitedByUserId: currentUser.id, role: 'editor' }); } }); setSelectedUsersToInvite([]); addNotification(`Invitations sent to ${selectedUsersToInvite.length} users!`, 'success'); }, [currentProject, selectedUsersToInvite, currentUser, addNotification]); const acceptInvitation = useCallback((invitationId) => { if (socketRef.current) { socketRef.current.emit('accept-invitation', { invitationId, userId: currentUser.id }); } }, [currentUser]); const logout = useCallback(() => { localStorage.removeItem('saas_user'); localStorage.removeItem('saas_token'); if (socketRef.current) socketRef.current.disconnect(); setCurrentUser(null); setIsAuthenticated(false); setShowLogin(true); setProjects([]); setCurrentProject(null); addNotification('Logged out', 'info'); }, [addNotification]); const isSuperAdmin = currentUser?.role === UserRole.SUPER_ADMIN; if (showLogin) { return React.createElement('div', { className: 'auth-container' }, React.createElement('div', { className: 'auth-card' }, React.createElement('h1', { className: 'auth-title' }, '🚀 SaaS Collaboration'), React.createElement('form', { onSubmit: handleLogin }, React.createElement('div', { className: 'form-group' }, React.createElement('label', { className: 'form-label' }, 'Email'), React.createElement('input', { type: 'email', className: 'form-input', value: loginForm.email, onChange: (e) => setLoginForm(prev => ({ ...prev, email: e.target.value })), required: true }) ), React.createElement('div', { className: 'form-group' }, React.createElement('label', { className: 'form-label' }, 'Password'), React.createElement('input', { type: 'password', className: 'form-input', value: loginForm.password, onChange: (e) => setLoginForm(prev => ({ ...prev, password: e.target.value })), required: true }) ), React.createElement('button', { type: 'submit', className: 'btn btn-primary btn-lg', disabled: loading, style: { width: '100%', marginTop: '20px' } }, loading ? '⏳ Signing In...' : '🚀 Sign In') ), React.createElement('div', { style: { marginTop: '24px', padding: '20px', background: '#f8fafc', borderRadius: '12px', fontSize: '14px', color: '#64748b' } }, React.createElement('p', { style: { fontWeight: '600', marginBottom: '8px' } }, '🎯 Test Credentials'), React.createElement('p', null, 'Super Admin: superadmin@realtimecursor.com / admin123'), React.createElement('p', null, 'Regular User: john@example.com / any password') ) ) ); } return React.createElement('div', { className: 'saas-platform' }, // Notifications React.createElement('div', { className: 'notifications' }, notifications.map(notification => React.createElement('div', { key: notification.id, className: `notification ${notification.type}` }, notification.message) ) ), // Invitation Banner invitations.length > 0 && React.createElement('div', { className: 'invitation-banner' }, React.createElement('div', null, React.createElement('h3', null, `📨 ${invitations.length} Project Invitations`), React.createElement('div', { style: { marginTop: '12px' } }, invitations.slice(0, 3).map(invitation => React.createElement('div', { key: invitation.id, className: 'invitation-item' }, React.createElement('div', null, React.createElement('strong', null, invitation.projectName), React.createElement('div', { style: { fontSize: '0.9rem', opacity: 0.9 } }, `Role: ${invitation.role}`) ), React.createElement('button', { onClick: () => acceptInvitation(invitation.id), className: 'btn btn-success btn-sm' }, '✅ Accept') ) ) ) ) ), // Header React.createElement('header', { className: 'header' }, React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '24px' } }, React.createElement('h1', { className: 'header-title' }, '🚀 SaaS Collaboration'), React.createElement('div', { className: 'status-indicator' }, React.createElement('div', { className: 'status-dot' }), connected ? 'Connected' : 'Disconnected' ) ), React.createElement('div', { className: 'header-actions' }, React.createElement('div', { className: 'user-info' }, React.createElement('div', { className: 'user-name' }, currentUser?.name), React.createElement('div', { className: 'user-role' }, currentUser?.role) ), isSuperAdmin && React.createElement('button', { onClick: () => setShowCreateProject(true), className: 'btn btn-success' }, '➕ New Project'), isSuperAdmin && React.createElement('button', { onClick: () => setShowAdminPanel(!showAdminPanel), className: 'btn btn-primary' }, '👑 Admin Panel'), React.createElement('button', { onClick: logout, className: 'btn btn-danger' }, '🚪 Logout') ) ), // Admin Panel showAdminPanel && isSuperAdmin && React.createElement('div', { className: 'admin-panel' }, React.createElement('h2', { style: { fontSize: '1.8rem', fontWeight: '700', marginBottom: '24px' } }, '👑 Admin Panel'), React.createElement('div', { style: { marginBottom: '32px' } }, React.createElement('h3', { style: { marginBottom: '16px' } }, '📊 Statistics'), React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px' } }, React.createElement('div', { style: { padding: '20px', background: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)', color: 'white', borderRadius: '12px' } }, React.createElement('div', { style: { fontSize: '2rem', fontWeight: '700' } }, projects.length), React.createElement('div', null, 'Total Projects') ), React.createElement('div', { style: { padding: '20px', background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)', color: 'white', borderRadius: '12px' } }, React.createElement('div', { style: { fontSize: '2rem', fontWeight: '700' } }, allUsers.length), React.createElement('div', null, 'Total Users') ), React.createElement('div', { style: { padding: '20px', background: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)', color: 'white', borderRadius: '12px' } }, React.createElement('div', { style: { fontSize: '2rem', fontWeight: '700' } }, collaborators.length), React.createElement('div', null, 'Online Now') ) ) ), React.createElement('div', null, React.createElement('h3', { style: { marginBottom: '16px' } }, '👥 User Directory'), React.createElement('div', { className: 'user-grid' }, allUsers.map(user => React.createElement('div', { key: user.id, className: 'user-card' }, React.createElement('div', { className: 'user-info-card' }, React.createElement('div', { className: 'user-name-card' }, user.name), React.createElement('div', { className: 'user-email' }, user.email), React.createElement('span', { className: `user-role-badge role-${user.role}` }, user.role) ), React.createElement('button', { onClick: () => { if (selectedUsersToInvite.includes(user.id)) { setSelectedUsersToInvite(prev => prev.filter(id => id !== user.id)); } else { setSelectedUsersToInvite(prev => [...prev, user.id]); } }, className: `btn btn-sm ${selectedUsersToInvite.includes(user.id) ? 'btn-success' : 'btn-primary'}` }, selectedUsersToInvite.includes(user.id) ? '✅ Selected' : '📧 Select') ) ) ), selectedUsersToInvite.length > 0 && currentProject && React.createElement('div', { style: { marginTop: '24px', padding: '20px', background: '#eff6ff', borderRadius: '12px', border: '2px solid #3b82f6', display: 'flex', justifyContent: 'space-between', alignItems: 'center' } }, React.createElement('div', null, React.createElement('strong', null, `Ready to invite ${selectedUsersToInvite.length} users`), React.createElement('div', { style: { color: '#6b7280', fontSize: '0.9rem' } }, `To: ${currentProject.name}`) ), React.createElement('button', { onClick: inviteUsers, className: 'btn btn-primary' }, '📧 Send Invitations') ) ) ), // Main Content React.createElement('div', { className: 'main-container' }, // Sidebar React.createElement('div', { className: 'sidebar' }, React.createElement('h3', { className: 'sidebar-title' }, isSuperAdmin ? '📁 All Projects' : '📁 My Projects'), projects.length === 0 ? React.createElement('div', { className: 'empty-state' }, React.createElement('h3', null, isSuperAdmin ? 'No projects yet' : 'No projects assigned'), React.createElement('p', null, isSuperAdmin ? 'Create your first project!' : 'Wait for invitations') ) : React.createElement('div', { className: 'project-list' }, projects.map(project => React.createElement('div', { key: project.id, className: `project-card ${currentProject?.id === project.id ? 'active' : ''}`, onClick: () => joinProject(project) }, React.createElement('div', { className: 'project-name' }, `🔓 ${project.name}`), React.createElement('div', { className: 'project-description' }, project.description), React.createElement('div', { className: 'project-meta' }, React.createElement('span', null, `👥 ${project.memberCount || 1} members`), React.createElement('span', null, new Date(project.created_at).toLocaleDateString()) ) ) ) ) ), // Editor React.createElement('div', { className: 'editor-container' }, currentProject ? [ React.createElement('div', { key: 'header', className: 'editor-header' }, React.createElement('h3', { className: 'editor-title' }, `✨ ${currentProject.name}`), React.createElement('div', { className: 'editor-meta' }, React.createElement('span', null, `👥 ${collaborators.length} online`), React.createElement('span', null, `v${currentProject.version || 1}`) ) ), React.createElement('div', { style: { flex: 1, padding: '20px', background: 'white', minHeight: '400px', border: 'none', outline: 'none', fontSize: '16px', fontFamily: 'Inter, sans-serif' }, contentEditable: true, suppressContentEditableWarning: true, onInput: (e) => handleContentChange(e.target.innerHTML), dangerouslySetInnerHTML: { __html: projectContent } }, null), // Simplified editor for now React.createElement('div', { style: { padding: '10px 20px', background: '#f8fafc', borderTop: '1px solid #e5e7eb', fontSize: '12px', color: '#6b7280' } }, `${projectContent.replace(/<[^>]*>/g, '').length} characters • ${typingUsers.length > 0 ? `${typingUsers.map(t => t.user.name).join(', ')} typing...` : 'Ready'}`), React.createElement('div', { key: 'collaborators', className: 'collaborators-bar' }, React.createElement('span', { style: { fontWeight: '600', marginRight: '12px' } }, '👥 Collaborators:'), ...collaborators.map(collaborator => React.createElement('div', { key: collaborator.id, className: 'collaborator-avatar', style: { background: collaborator.color || `#${Math.floor(Math.random()*16777215).toString(16)}` }, title: collaborator.name }, collaborator.name.charAt(0)) ), collaborators.length === 0 && React.createElement('span', { style: { color: '#9ca3af', fontStyle: 'italic' } }, 'No collaborators online') ) ] : React.createElement('div', { style: { flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', color: '#6b7280', textAlign: 'center', padding: '40px' } }, React.createElement('div', { style: { fontSize: '4rem', marginBottom: '24px' } }, '🚀'), React.createElement('h3', { style: { fontSize: '1.5rem', marginBottom: '16px' } }, 'Select a project to collaborate'), React.createElement('p', null, isSuperAdmin ? 'Choose a project or create a new one' : 'Choose a project you\'ve been invited to') ) ) ), // Create Project Modal showCreateProject && React.createElement('div', { className: 'modal-overlay' }, React.createElement('div', { className: 'modal' }, React.createElement('h2', { className: 'modal-title' }, '🚀 Create New Project'), React.createElement('form', { onSubmit: createProject }, React.createElement('div', { className: 'form-group' }, React.createElement('label', { className: 'form-label' }, 'Project Name'), React.createElement('input', { type: 'text', className: 'form-input', value: projectForm.name, onChange: (e) => setProjectForm(prev => ({ ...prev, name: e.target.value })), required: true }) ), React.createElement('div', { className: 'form-group' }, React.createElement('label', { className: 'form-label' }, 'Description'), React.createElement('textarea', { className: 'form-input', value: projectForm.description, onChange: (e) => setProjectForm(prev => ({ ...prev, description: e.target.value })), style: { minHeight: '100px' } }) ), React.createElement('div', { className: 'modal-actions' }, React.createElement('button', { type: 'button', onClick: () => setShowCreateProject(false), className: 'btn btn-secondary' }, 'Cancel'), React.createElement('button', { type: 'submit', className: 'btn btn-primary' }, '🚀 Create') ) ) ) ) ); }; export default SaaSCollaboration;