Skip to content

Latest commit

 

History

History
1035 lines (763 loc) · 26.5 KB

File metadata and controls

1035 lines (763 loc) · 26.5 KB

Frontend - Echo & Script

A modern Angular 20 single-page application for the Echo & Script social blogging platform, featuring real-time communication, rich content creation, and comprehensive social interaction capabilities.

Table of Contents

Technologies

Core Framework & Language

  • Angular: 20.3.1 - Modern web framework with standalone components architecture
  • TypeScript: 5.8.0 - Strongly-typed superset of JavaScript with enhanced IDE support
  • RxJS: 7.8.0 - Reactive Extensions library for composing asynchronous and event-based programs
  • Zone.js: 0.15.0 - Execution context that persists across async tasks
  • Node.js: 20+ - JavaScript runtime (required for development)

UI Component Libraries

  • Angular Material: 20.2.4 - Google's official Material Design component library
    • Pre-built UI components (buttons, cards, dialogs, etc.)
    • Accessibility features built-in
    • Consistent design language
  • Angular CDK: 20.2.4 - Component Development Kit for building custom components
    • Layout utilities
    • Accessibility helpers
    • Overlay and portal services

Icon Libraries

  • Font Awesome: 7.0.1 - Comprehensive icon library with 10,000+ icons
    • @fortawesome/angular-fontawesome: 3.0.0 - Angular integration
    • @fortawesome/fontawesome-svg-core: 7.1.0 - Core SVG functionality
    • @fortawesome/free-solid-svg-icons: 7.0.1 - Solid icon style
    • @fortawesome/free-regular-svg-icons: 7.1.0 - Regular icon style
    • SVG-based rendering for crisp icons at any size
  • Lucide Angular: 0.548.0 - Modern, lightweight icon library with 1000+ icons
    • Designed for simplicity and consistency
    • Fully customizable stroke width and color

Rich Text Editors

  • Quill.js: 2.0.3 - Powerful WYSIWYG rich text editor
    • Toolbar customization
    • Format support (bold, italic, lists, code blocks, etc.)
    • Image and media embedding
  • ngx-quill: 28.0.2 - Angular wrapper for Quill.js
    • Two-way data binding with Angular forms
    • Custom toolbar configuration
    • Event handling integration
  • Editor.js: 2.31.0 - Block-style editor with modular architecture
    • Alternative editor option
    • Plugin-based extensibility
    • JSON output format

Real-Time Communication

  • @stomp/ng2-stompjs: 8.0.0 - STOMP protocol client for Angular
    • WebSocket communication with STOMP messaging protocol
    • Angular service integration
  • @stomp/rx-stomp: 2.2.0 - RxJS wrapper for STOMP
    • Observable-based message streams
    • Easy subscription management
  • @stomp/stompjs: 7.2.1 - Core STOMP JavaScript library
    • Text-oriented messaging protocol
    • Message framing and headers
  • SockJS Client: 1.6.1 - WebSocket emulation library
    • Fallback transport mechanisms (polling, streaming)
    • Cross-browser WebSocket support
    • Automatic connection retry

Styling Technologies

  • SCSS - Sassy CSS preprocessor
    • Variables for theme colors
    • Mixins for reusable styles
    • Nesting for organized code
    • Functions for dynamic styling
  • CSS Variables - Native CSS custom properties
    • Dynamic theme switching (light/dark mode)
    • Runtime color adjustments
    • Cascade-based inheritance
  • Responsive Design - Mobile-first approach
    • Flexbox layouts
    • CSS Grid for complex layouts
    • Media queries for breakpoints

Build Tools & Development

  • Angular CLI: 20.3.3 - Official command-line interface
    • Project scaffolding
    • Development server with hot reload
    • Build optimization
    • Code generation
  • Angular Build: 20.1.6 - Build system powered by Vite
    • Fast HMR (Hot Module Replacement)
    • Optimized production builds
    • Tree shaking for smaller bundles
  • TypeScript Compiler: 5.8.0 - Transpiles TypeScript to JavaScript
    • Type checking
    • Modern JavaScript features
    • Source maps for debugging

TypeScript Type Definitions

  • @types/express: 5.0.1 - TypeScript definitions for Express
  • @types/jasmine: 5.1.0 - TypeScript definitions for Jasmine
  • @types/node: 20.17.19 - TypeScript definitions for Node.js APIs
  • @types/sockjs-client: 1.5.4 - TypeScript definitions for SockJS

Additional Development Tools

  • rimraf: 6.1.2 - Cross-platform rm -rf utility for cleaning build directories
  • tslib: 2.3.0 - TypeScript runtime library with helper functions
  • baseline-browser-mapping: 2.9.2 - Browser compatibility baseline
  • Angular Platform Browser: 20.3.0 - APIs for browser-specific rendering
  • Angular Animations: 20.3.1 - Animation library for smooth transitions
  • Angular Forms: 20.3.0 - Form handling with validation
  • Angular Router: 20.3.0 - Client-side routing and navigation
  • Angular Compiler: 20.3.0 - Template compilation and code generation

Features

User Experience

  • Landing Page with modern design, animations, and feature showcase
  • Dark Mode with theme persistence across sessions
  • Responsive Design optimized for desktop, tablet, and mobile
  • Infinite Scroll for seamless content browsing
  • Toast Notifications for user feedback
  • Smooth Animations and transitions throughout

Authentication

  • Email/Password Login with form validation
  • OAuth2 Integration:
    • Google Sign-In
    • GitHub Authentication
    • Facebook Login
  • JWT Token Management with automatic header injection
  • Session Persistence via localStorage
  • Guest Mode for browsing without authentication

Content Management

  • Rich Text Editor (Quill.js) with formatting, lists, and code blocks
  • Post Creation with title, description, banner image, and categories
  • Post Editing with live preview
  • Category System (Technology, Science, Health, Sports, Business)
  • Search & Filter with 500ms debounce for optimal performance
  • Post Interactions:
    • Like/unlike posts
    • Save posts for later reading
    • Comment on posts
    • Share posts
    • Report inappropriate content

Social Features

  • User Profiles with customizable avatars and bios
  • Follow System to stay updated with favorite authors
  • Followers & Following Lists with user stats
  • Friends List (mutual follows) with online status
  • Profile Statistics (posts, likes, followers, following)

Real-Time Communication

  • WebSocket Integration using STOMP over SockJS
  • Live Notifications:
    • Like notifications
    • Comment notifications
    • Follow notifications
    • New post alerts from followed users
  • Direct Messaging:
    • Real-time chat with friends
    • Online/offline status indicators
    • Message history
    • Typing indicators
  • User Status Updates (online/offline) via WebSocket

Admin Features

  • Admin Dashboard with analytics
  • User Management (view, ban, delete users)
  • Post Moderation (hide, delete posts)
  • Report Management (review and resolve reports)
  • Statistics Dashboard (user count, post count, comment count, report count)

Content Moderation

  • Report System for posts, comments, and users
  • Priority Levels (Low, Medium, High)
  • Status Tracking (Solved/Unsolved)
  • Confirmation Dialogs for destructive actions

Project Structure

frontend/
├── src/
│   ├── app/
│   │   ├── pages/                          # Page components (12 pages)
│   │   │   ├── home/
│   │   │   ├── feed/
│   │   │   ├── login/
│   │   │   ├── register/
│   │   │   ├── profile/
│   │   │   ├── posting/
│   │   │   ├── post-page/
│   │   │   ├── read-later/
│   │   │   ├── admin-panel/
│   │   │   ├── report/
│   │   │   ├── privacy-policy/
│   │   │   └── not-found/
│   │   │
│   │   ├── helper_components/              # Reusable UI components (12 components)
│   │   │   ├── navbar/
│   │   │   ├── chat-component/
│   │   │   ├── comments-container/
│   │   │   ├── post-component/
│   │   │   ├── posts/
│   │   │   ├── toast-component/
│   │   │   ├── user-list/
│   │   │   ├── user-table/
│   │   │   ├── post-table/
│   │   │   ├── reports-table/
│   │   │   ├── logo/
│   │   │   ├── confirmation-popup/
│   │   │   └── confirm-dialog-component/
│   │   │
│   │   ├── servises/                       # Services (NOTE: directory has typo)
│   │   │   ├── data-service.ts
│   │   │   ├── WebsocketService.ts
│   │   │   ├── user-s.ts
│   │   │   ├── post-servise.ts             # (NOTE: filename typo)
│   │   │   ├── comment-service.ts
│   │   │   ├── notif-service.ts
│   │   │   ├── chat-service.ts
│   │   │   ├── analytics-service.ts
│   │   │   ├── report-serise.ts            # (NOTE: filename typo)
│   │   │   ├── oauth2-service.ts
│   │   │   ├── media.ts
│   │   │   ├── helper-service.ts
│   │   │   └── toaster-service.ts
│   │   │
│   │   ├── models/                         # TypeScript data models (16 models)
│   │   ├── interceptors/                   # HTTP interceptors
│   │   ├── guards/                         # Route guards
│   │   ├── shared/                         # Shared modules
│   │   ├── app.ts
│   │   ├── app.config.ts
│   │   └── app.routes.ts
│   │
│   ├── public/                             # Static assets
│   ├── package.json
│   ├── angular.json
│   ├── tsconfig.json
│   ├── Dockerfile
│   └── README.md

Getting Started

Prerequisites

  • Node.js: 20 or higher
  • npm: 10+ (comes with Node.js)
  • Angular CLI: 20.3+ (optional but recommended)

Installation

  1. Navigate to frontend directory
cd frontend
  1. Install dependencies
npm install
  1. Configure API endpoint (if different from default)

Edit src/app/servises/ service files to point to your backend:

// Default: http://localhost:8080
private apiUrl = 'http://localhost:8080/api';

Note: The services directory is named servises (with a typo) in the actual codebase.

  1. Start development server
npm start
# or
ng serve

The application will be available at http://localhost:4200

Available Scripts

# Start development server
npm start

# Build for production
npm run build

# Run unit tests
npm test

# Run linter
npm run lint

# Serve production build with SSR
npm run serve:ssr:frontend

# Build with SSR
ng build --configuration production

Environment Configuration

The application uses the following default configuration:

Architecture

Standalone Components Pattern

All components use Angular 15+ standalone pattern:

  • No NgModule required
  • Direct component imports
  • Simplified dependency management
  • Better tree-shaking

Service-Based Architecture

Services handle all business logic and API communication:

  • DataService: Central state management
  • WebsocketService: Real-time communication
  • API Services: REST endpoints (User, Post, Comment, etc.)
  • Helper Services: Utility functions

Important Note: The services directory is named servises/ (with a typo) in the codebase. Some service files also contain typos:

  • post-servise.ts (should be post-service.ts)
  • report-serise.ts (should be report-service.ts)

Observable Patterns

Heavy use of RxJS for reactive programming:

  • BehaviorSubjects for state management
  • Observables for HTTP requests
  • Operators: map, filter, debounceTime, distinctUntilChanged
  • Subscriptions managed in components

Components

Page Components

Home (pages/home/)

Landing page with:

  • Hero section with gradient title and call-to-action buttons
  • Statistics section showing platform metrics
  • Features section with Lucide icons
  • "How It Works" step-by-step guide
  • Testimonials from users
  • Call-to-action section
  • Responsive design with animations

Feed (pages/feed/)

Paginated post feed with:

  • Infinite scroll loading
  • Category filtering tabs
  • Search functionality with debounce
  • Post cards with interactions

Post Page (pages/post-page/)

Individual post view with:

  • Full post content with Quill rendering
  • Comment section with nested replies
  • Like and save functionality
  • Edit mode for post owners
  • Delete confirmation
  • Report functionality

Profile (pages/profile/)

User profile management:

  • View own or other users' profiles
  • Edit profile (name, email, bio, avatar)
  • User statistics (posts, followers, following, likes)
  • Posts grid
  • Followers/following lists
  • Follow/unfollow button

Posting (pages/posting/)

Post creation/editing:

  • Quill rich text editor
  • Title and description fields
  • Banner image upload
  • Category selection (multiple)
  • Preview mode
  • Validation

Admin Panel (pages/admin-panel/)

Administrative dashboard:

  • Statistics cards (users, posts, comments, reports)
  • User management table
  • Post management table
  • Reports table
  • Ban/delete/hide actions

Helper Components

Navbar (helper_components/navbar/)

Main navigation:

  • Logo with routing
  • Menu toggle (mobile)
  • Notification dropdown with WebSocket updates
  • Chat toggle
  • Write button
  • User avatar with menu
  • Dark mode toggle
  • Logout and delete account

Posts Container (helper_components/posts/)

Reusable post feed:

  • Infinite scroll with pagination (10 posts per page)
  • Category filtering
  • Search with 500ms debounce
  • Dynamic API parameter building
  • Loading states

Post Component (helper_components/post-component/)

Individual post card:

  • Post title, description, banner
  • Author info with avatar
  • Like button with count
  • Save button
  • Menu with report/delete options
  • Confirmation dialogs

Comments Container (helper_components/comments-container/)

Nested comment system:

  • Load all comments for a post
  • Submit new comments
  • Reply to comments (nested structure)
  • Like comments
  • Delete comments with confirmation
  • Time-ago display

Chat Component (helper_components/chat-component/)

Real-time messaging:

  • Friends list with online status
  • Tab switching (all friends / online only)
  • Message history
  • WebSocket message receiving
  • Auto-scroll to latest message

Toast Component (helper_components/toast-component/)

Notification messages:

  • Success, error, info types
  • Auto-dismiss after timeout
  • Customizable duration
  • Accessible design

Services

DataService (services/data-service.ts)

Central state management:

  • Stores current user data in data$ BehaviorSubject
  • Fetches user on app initialization
  • Manages login/logout lifecycle
  • Coordinates with WebSocketService
  • Provides isLoggedIn() helper

WebsocketService (services/WebsocketService.ts)

Real-time communication:

  • STOMP over SockJS connection
  • JWT token in query parameter
  • Subscriptions:
    • /user/{userId}/queue/notifications - Notifications
    • /user/{userId}/queue/chat - Messages
    • /topic/user-status - Online/offline status
  • Publishing:
    • /app/chat - Send messages
  • Auto-reconnection with 5-second delay
  • BehaviorSubjects: notification$, message$, userStatus$

User Service (services/user-s.ts)

User operations:

  • Register new users
  • Login with Basic auth
  • Get current user
  • Get user profile by ID
  • Update user profile
  • Delete account
  • Toggle follow relationship
  • Fetch followers/followings/friends
  • Admin ban toggle

Post Service (services/post-service.ts)

Post operations:

  • Create posts
  • Update posts
  • Delete posts
  • Get single post by ID
  • Get posts with filters (pagination, category, search, author)
  • Toggle like on posts
  • Toggle save (read-later)
  • Delete comments

Comment Service (services/comment-service.ts)

Comment operations:

  • Create comments (top-level or reply)
  • Get comments for post
  • Nested comment structure support
  • Parent comment type parameter

Notification Service (services/notif-service.ts)

Notification management:

  • Fetch all notifications
  • Mark notification as read
  • Mark all notifications as read

Chat Service (services/chat-service.ts)

Chat operations:

  • Retrieve message history with specific user
  • Used alongside WebSocketService for real-time updates

Analytics Service (services/analytics-service.ts)

Admin operations:

  • Get platform statistics (user, post, comment, report counts)
  • Get all posts
  • Get all users
  • Delete user
  • Hide/unhide post
  • Delete post

Report Service (services/report-service.ts)

Report management:

  • Submit reports for posts/comments/users
  • Get all reports (admin)
  • Delete report (admin)
  • Toggle report resolution status (admin)

OAuth2 Service (services/oauth2-service.ts)

Third-party authentication:

  • Redirect to Google OAuth2
  • Redirect to GitHub OAuth2
  • Redirect to Facebook OAuth2
  • Handles callback and token extraction

Helper Service (services/helper-service.ts)

Utility functions:

  • isGuestMode(): Check if user is authenticated
  • timeAgo(): Format timestamps as relative time (e.g., "2h ago")
  • avatarUrl(): Resolve avatar URLs (external, local, default)
  • bannerUrl(): Resolve banner URLs (base64, external, local)

Media Service (services/media.ts)

Media handling:

  • Upload images/videos
  • Retrieve media files
  • UUID-based file naming

Routing

Routes defined in app.routes.ts:

Route Component Description
/ Home Landing page
/feed Feed Paginated post feed
/register Register User registration
/login Login Authentication page
/report Report General report submission
/report/post/:post_id Report Report specific post
/report/comment/:comment_id Report Report specific comment
/report/user/:user_id Report Report specific user
/profile Profile Current user's profile
/profile/:id Profile Specific user's profile
/post/:id PostPage Single post detail view
/posting Posting Create new post
/read-later ReadLater Saved posts
/privacy-policy PrivacyPolicy Privacy policy
/dashboard AdminPanel Admin dashboard
/notFound NotFound 404 error page
/** NotFound Wildcard redirect

State Management

Observable-Based State

No global state management library (NgRx, Akita) - uses pure RxJS:

Central State (DataService):

data$: BehaviorSubject<User | null> = new BehaviorSubject(null);

Real-Time State (WebsocketService):

notification$: BehaviorSubject<FullNotification | null>
message$: BehaviorSubject<Message | null>
userStatus$: BehaviorSubject<UserStatusMessage | null>

Component-Level State:

  • Local component properties
  • Angular Signals for reactive updates
  • URL parameters for routing context

Data Flow

  1. Authentication Flow:

    • User logs in → UserService → JWT token stored in localStorage
    • DataService fetches current user → stores in data$
    • WebSocketService connects with JWT token
    • Components subscribe to data$ for user state
  2. Real-Time Flow:

    • WebSocket receives message → WebSocketService emits to notification$
    • Navbar component subscribes → displays toast notification
    • User clicks notification → navigates to relevant page
  3. HTTP Flow:

    • Component calls service method
    • Service makes HTTP request
    • AuthInterceptor adds JWT token
    • Response mapped to model
    • Component updates UI

Real-Time Features

WebSocket Connection

Endpoint: ws://localhost:8080/ws?token=<jwt_token>

Protocol: STOMP over SockJS (fallback support)

Subscription Channels

Private Notifications:

/user/{userId}/queue/notifications

Receives:

  • Like notifications (posts/comments)
  • Comment notifications
  • Follow notifications
  • New post alerts

Private Messages:

/user/{userId}/queue/chat

Receives:

  • Direct messages from other users
  • Message history on reconnection

Public User Status:

/topic/user-status

Receives:

  • Online/offline status updates
  • Broadcasted to all connected users

Publishing Messages

Send Chat Message:

/app/chat

Payload:

{
  "senderId": 1,
  "receiverId": 2,
  "content": "Hello!",
  "createdAt": "2025-01-01T12:00:00Z"
}

Reconnection Strategy

  • Automatic reconnection on disconnect
  • 5-second delay between attempts
  • Cleans up old subscriptions
  • Re-subscribes to all channels on reconnect

Styling & Theming

SCSS Architecture

Global styles in styles.scss:

  • CSS variables for theming
  • Dark mode support
  • Responsive breakpoints
  • Reusable mixins

CSS Variables:

:root {
  --primary-text-color: #1a1a1a;
  --second-text-color: #666;
  --background: #ffffff;
  --accent-color: #1a8917;
  --border-radius-lg: 12px;
  --transition-base: 0.3s ease;
  --shadow-lg: 0 10px 40px rgba(0, 0, 0, 0.1);
}

body.dark {
  --primary-text-color: #e8e8e8;
  --second-text-color: #a8a8a8;
  --background: #1a1a1b;
  --accent-color: #1a8917;
}

Dark Mode

Toggle between light and dark themes:

  • Persisted in localStorage
  • Applied via body class (body.dark)
  • CSS variables for dynamic color switching
  • Smooth transitions between themes

Responsive Design

Breakpoints:

  • Desktop: > 1200px
  • Tablet: 768px - 1199px
  • Mobile: < 767px

Responsive Patterns:

  • Mobile-first approach
  • Flexbox and Grid layouts
  • Media queries in component styles
  • Collapsible navigation on mobile

Animations

Smooth animations using:

  • CSS transitions
  • Keyframe animations (@keyframes fadeInUp, float, etc.)
  • Staggered animations for list items
  • Hover effects with transforms

HTTP Interceptors

AuthInterceptor (interceptors/auth-interceptor.ts)

Automatically adds JWT token to requests:

  • Reads token from localStorage
  • Adds Authorization: Bearer <token> header
  • Skips for login/register endpoints
  • Enables credentials (cookies) on all requests

ResponseInterceptor (interceptors/response-interceptor.ts)

Handles global error responses:

  • 401 Unauthorized: Logs out user, redirects to login
  • 403 Forbidden: Redirects to home page
  • Clears user state on authentication errors

Development Guidelines

Code Style

  • Use TypeScript strict mode
  • Follow Angular style guide
  • Use meaningful variable names
  • Add comments for complex logic
  • Keep components focused and small

Component Creation

# Generate new component
ng generate component pages/my-page --standalone

# Generate service
ng generate service services/my-service

Best Practices

  1. Unsubscribe from Observables: Use takeUntil or async pipe
  2. Use Signals: For reactive local state
  3. Lazy Loading: For large feature modules
  4. Type Safety: Define interfaces for all data structures
  5. Error Handling: Use try-catch and RxJS catchError
  6. Accessibility: Use semantic HTML and ARIA labels

Testing

Unit Tests

# Run all tests
npm test

# Run tests with coverage
ng test --code-coverage

# Run specific test
ng test --include='**/user-s.spec.ts'

End-to-End Tests

# Run E2E tests (if configured)
ng e2e

Build & Deployment

Production Build

# Build for production
npm run build

# Output in dist/frontend/browser/

Build Optimizations:

  • Ahead-of-Time (AOT) compilation
  • Tree shaking
  • Minification
  • Bundle optimization

Deployment

Static Hosting (Netlify, Vercel, GitHub Pages):

  1. Build the project: npm run build
  2. Deploy dist/frontend/browser/ directory
  3. Configure redirects for Angular routing

Server-Side Rendering (SSR):

The application includes full SSR support via Angular Universal:

# Build for SSR
ng build --configuration production

# Serve with SSR (port 4000 by default)
npm run serve:ssr:frontend

SSR Configuration Files:

  • app.config.server.ts - Server-specific configuration
  • server.ts - Express server setup (auto-generated)
  • Output location: dist/frontend/server/

Benefits of SSR:

  • Improved SEO and social media sharing
  • Faster initial page load
  • Better performance on low-powered devices

Environment Variables

For production, update service URLs:

  • Backend API endpoint
  • WebSocket endpoint
  • OAuth2 client IDs (Google, GitHub, Facebook)

Performance Optimization

Implemented Optimizations

  1. Lazy Loading: Route-level code splitting
  2. Infinite Scroll: Load posts on demand (10 per page)
  3. Debounced Search: 500ms delay to reduce API calls
  4. OnPush Change Detection: For performance-critical components
  5. Image Optimization: Lazy loading images with loading attribute
  6. Bundle Splitting: Vendor bundles separated from app code

Monitoring

  • Chrome DevTools Lighthouse for audits
  • Angular DevTools for debugging
  • Network tab for API performance

Security Considerations

  1. XSS Prevention: Angular sanitizes templates automatically
  2. JWT Storage: Stored in localStorage (consider httpOnly cookies for production)
  3. CORS: Backend configured with allowed origins
  4. Input Validation: Client-side validation (server validates too)
  5. Secure OAuth2: State parameter for CSRF protection

Troubleshooting

Common Issues

WebSocket Connection Failed:

  • Check backend is running on port 8080
  • Verify JWT token is valid
  • Check browser console for errors

Posts Not Loading:

  • Verify backend API is accessible
  • Check network tab for 401/403 errors
  • Confirm user is authenticated

OAuth2 Login Not Working:

  • Verify OAuth2 client IDs are configured
  • Check redirect URIs match backend configuration
  • Review browser console for errors

Dark Mode Not Persisting:

  • Check localStorage for theme key
  • Verify body.dark class is applied
  • Clear browser cache

Contributing

  1. Follow Angular coding conventions
  2. Write unit tests for new features
  3. Update documentation
  4. Use TypeScript types
  5. Test in both light and dark modes
  6. Ensure responsive design

Support

For issues and questions, please refer to the main project documentation or contact the development team.