Skip to content

Comprehensive Tab Usage Examples

This page showcases comprehensive examples of content tabs usage across different documentation scenarios.

Documentation Patterns

Getting Started Guide

Quick Start Guide

Get up and running in under 5 minutes:

  1. Install the package

    npm install @example/toolkit
    

  2. Import in your project

    import { Toolkit } from '@example/toolkit';
    

  3. Initialize and use

    const toolkit = new Toolkit();
    toolkit.run();
    

🎉 You're ready to go!

Comprehensive Installation Guide

Prerequisites

Before installing, ensure you have: - Node.js 16 or higher - npm 7 or higher - Git installed

Step-by-Step Installation

  1. Create a new project

    mkdir my-project
    cd my-project
    npm init -y
    

  2. Install the toolkit

    npm install @example/toolkit
    

  3. Install peer dependencies

    npm install react react-dom
    

  4. Create configuration file

    {
      "toolkit": {
        "theme": "default",
        "modules": ["core", "ui", "utils"]
      }
    }
    

  5. Set up your first component

    import React from 'react';
    import { Toolkit, Button } from '@example/toolkit';
    
    function App() {
      return (
        <Toolkit>
          <Button variant="primary">
            Hello World
          </Button>
        </Toolkit>
      );
    }
    
    export default App;
    

Common Issues and Solutions

Installation Problems

Issue: Package not found

npm ERR! 404 Not Found - GET https://registry.npmjs.org/@example/toolkit

Solution: - Verify the package name spelling - Check if you have access to the private registry - Ensure you're logged in: npm login

Issue: Peer dependency warnings

npm WARN @example/toolkit@1.0.0 requires a peer of react@^18.0.0

Solution:

npm install react@^18.0.0 react-dom@^18.0.0

Runtime Errors

Issue: Module not found

Module not found: Can't resolve '@example/toolkit'

Solution: 1. Restart your development server 2. Clear node_modules and reinstall:

rm -rf node_modules package-lock.json
npm install
3. Check your import syntax

Issue: TypeScript errors

Could not find a declaration file for module '@example/toolkit'

Solution:

npm install @types/example__toolkit

Or create a declaration file:

// types/toolkit.d.ts
declare module '@example/toolkit' {
  export interface ToolkitProps {
    children: React.ReactNode;
  }
  export const Toolkit: React.FC<ToolkitProps>;
}

Code Implementation Examples

Authentication Systems

JSON Web Token Authentication

Backend (Node.js/Express)

```javascript const jwt = require('jsonwebtoken'); const bcrypt = require('bcrypt'); const express = require('express'); const app = express();

// Secret key (use environment variable in production)
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// User registration
app.post('/api/register', async (req, res) => {
  try {
    const { email, password } = req.body;

    // Hash password
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);

    // Save user to database
    const user = await User.create({
      email,
      password: hashedPassword
    });

    // Generate JWT
    const token = jwt.sign(
      { userId: user.id, email: user.email },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      message: 'User created successfully',
      token,
      user: { id: user.id, email: user.email }
    });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// User login
app.post('/api/login', async (req, res) => {
  try {
    const { email, password } = req.body;

    // Find user
    const user = await User.findOne({ where: { email } });
    if (!user) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    // Verify password
    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    // Generate JWT
    const token = jwt.sign(
      { userId: user.id, email: user.email },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      message: 'Login successful',
      token,
      user: { id: user.id, email: user.email }
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Middleware to verify JWT
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: 'Access token required' });
  }

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({ error: 'Invalid token' });
    }
    req.user = user;
    next();
  });
};

// Protected route
app.get('/api/profile', authenticateToken, (req, res) => {
  res.json({
    message: 'Profile data',
    user: req.user
  });
});
```
### Frontend (React)

<div class="lazy-content" data-lazy-content="true">

```jsx import React, { useState, useContext, createContext } from 'react'; import axios from 'axios';

// Auth Context
const AuthContext = createContext();

export const useAuth = () => {
  return useContext(AuthContext);
};

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState(localStorage.getItem('token'));

  // Configure axios defaults
  if (token) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  }

  const login = async (email, password) => {
    try {
      const response = await axios.post('/api/login', {
        email,
        password
      });

      const { token, user } = response.data;

      // Store token
      localStorage.setItem('token', token);
      setToken(token);
      setUser(user);

      // Set axios default header
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

      return { success: true };
    } catch (error) {
      return {
        success: false,
        error: error.response?.data?.error || 'Login failed'
      };
    }
  };

  const register = async (email, password) => {
    try {
      const response = await axios.post('/api/register', {
        email,
        password
      });

      const { token, user } = response.data;

      localStorage.setItem('token', token);
      setToken(token);
      setUser(user);
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

      return { success: true };
    } catch (error) {
      return {
        success: false,
        error: error.response?.data?.error || 'Registration failed'
      };
    }
  };

  const logout = () => {
    localStorage.removeItem('token');
    setToken(null);
    setUser(null);
    delete axios.defaults.headers.common['Authorization'];
  };

  const value = {
    user,
    token,
    login,
    register,
    logout,
    isAuthenticated: !!token
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

// Login Component
export const LoginForm = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const { login } = useAuth();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    const result = await login(email, password);

    if (!result.success) {
      setError(result.error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {error && <div className="error">{error}</div>}

      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
      </div>

      <div>
        <label htmlFor="password">Password:</label>
        <input
          type="password"
          id="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
        />
      </div>

      <button type="submit">Login</button>
    </form>
  );
};
```

OAuth 2.0 Authentication

Google OAuth Setup

```javascript // Backend - Google OAuth configuration const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({ clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: "/auth/google/callback" }, async (accessToken, refreshToken, profile, done) => { try { // Check if user already exists let user = await User.findOne({ googleId: profile.id });

if (user) {
  return done(null, user);
}

// Create new user
user = await User.create({
  googleId: profile.id,
  email: profile.emails[0].value,
  name: profile.displayName,
  avatar: profile.photos[0].value
});

return done(null, user);

} catch (error) { return done(error, null); } }));

// Routes app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }) );

app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => { // Generate JWT for the user const token = jwt.sign( { userId: req.user.id, email: req.user.email }, JWT_SECRET, { expiresIn: '24h' } );

// Redirect to frontend with token
res.redirect(`${process.env.FRONTEND_URL}?token=${token}`);

} ); ```

Frontend Google OAuth Integration

```jsx import React from 'react'; import { GoogleLogin } from 'react-oauth/google'; import { GoogleOAuthProvider } from 'react-oauth/google';

const GoogleOAuthButton = () => { const handleGoogleSuccess = async (credentialResponse) => { try { // Send the credential to your backend const response = await fetch('/api/auth/google', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ credential: credentialResponse.credential }) });

  const data = await response.json();

  if (data.success) {
    // Store the JWT token
    localStorage.setItem('token', data.token);
    // Redirect or update UI
    window.location.href = '/dashboard';
  }
} catch (error) {
  console.error('Google auth error:', error);
}

};

const handleGoogleError = () => { console.log('Google Login Failed'); };

return ( ); };

export default GoogleOAuthButton; ```

Session-Based Authentication

Express Session Configuration

```javascript const express = require('express'); const session = require('express-session'); const MongoStore = require('connect-mongo'); const bcrypt = require('bcrypt');

const app = express();

// Session configuration
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  store: MongoStore.create({
    mongoUrl: process.env.MONGODB_URI,
    collectionName: 'sessions'
  }),
  cookie: {
    secure: process.env.NODE_ENV === 'production',
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000 // 24 hours
  }
}));

// Login route
app.post('/api/login', async (req, res) => {
  try {
    const { email, password } = req.body;

    // Find user
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    // Verify password
    const isValid = await bcrypt.compare(password, user.password);
    if (!isValid) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    // Create session
    req.session.userId = user.id;
    req.session.email = user.email;

    res.json({
      message: 'Login successful',
      user: { id: user.id, email: user.email }
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Logout route
app.post('/api/logout', (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      return res.status(500).json({ error: 'Could not log out' });
    }
    res.clearCookie('connect.sid');
    res.json({ message: 'Logout successful' });
  });
});

// Auth middleware
const requireAuth = (req, res, next) => {
  if (!req.session.userId) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  next();
};

// Protected route
app.get('/api/profile', requireAuth, async (req, res) => {
  try {
    const user = await User.findById(req.session.userId);
    res.json({ user });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
```

Database Integration Examples

Database Patterns

MongoDB with Mongoose

Schema Definition

```javascript const mongoose = require('mongoose'); const bcrypt = require('bcrypt');

// User Schema
const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true,
    trim: true
  },
  password: {
    type: String,
    required: true,
    minlength: 8
  },
  profile: {
    firstName: String,
    lastName: String,
    avatar: String,
    bio: String
  },
  roles: [{
    type: String,
    enum: ['user', 'admin', 'moderator'],
    default: 'user'
  }],
  settings: {
    notifications: {
      email: { type: Boolean, default: true },
      push: { type: Boolean, default: false }
    },
    privacy: {
      profileVisible: { type: Boolean, default: true },
      showEmail: { type: Boolean, default: false }
    }
  },
  lastLogin: Date,
  isActive: { type: Boolean, default: true }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Virtual for full name
userSchema.virtual('fullName').get(function() {
  return `${this.profile.firstName} ${this.profile.lastName}`;
});

// Pre-save middleware for password hashing
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();

  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error);
  }
});

// Instance method for password comparison
userSchema.methods.comparePassword = async function(candidatePassword) {
  return bcrypt.compare(candidatePassword, this.password);
};

// Static method for finding active users
userSchema.statics.findActive = function() {
  return this.find({ isActive: true });
};

const User = mongoose.model('User', userSchema);

// Post Schema with references
const postSchema = new mongoose.Schema({
  title: { type: String, required: true },
  content: { type: String, required: true },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  tags: [String],
  categories: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Category'
  }],
  likes: [{
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    createdAt: { type: Date, default: Date.now }
  }],
  comments: [{
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    content: String,
    createdAt: { type: Date, default: Date.now }
  }],
  publishedAt: Date,
  status: {
    type: String,
    enum: ['draft', 'published', 'archived'],
    default: 'draft'
  }
}, {
  timestamps: true
});

// Index for better query performance
postSchema.index({ author: 1, status: 1 });
postSchema.index({ publishedAt: -1 });
postSchema.index({ tags: 1 });

const Post = mongoose.model('Post', postSchema);

module.exports = { User, Post };
```
### CRUD Operations

<div class="lazy-content" data-lazy-content="true">

```javascript const { User, Post } = require('./models');

// Create user
const createUser = async (userData) => {
  try {
    const user = new User(userData);
    await user.save();
    return user;
  } catch (error) {
    throw new Error(`Error creating user: ${error.message}`);
  }
};

// Find user with posts
const getUserWithPosts = async (userId) => {
  try {
    const user = await User.findById(userId)
      .populate({
        path: 'posts',
        match: { status: 'published' },
        options: { sort: { publishedAt: -1 } }
      });
    return user;
  } catch (error) {
    throw new Error(`Error fetching user: ${error.message}`);
  }
};

// Create post with transaction
const createPost = async (postData) => {
  const session = await mongoose.startSession();

  try {
    session.startTransaction();

    const post = new Post(postData);
    await post.save({ session });

    // Update user's post count
    await User.findByIdAndUpdate(
      postData.author,
      { $inc: { postCount: 1 } },
      { session }
    );

    await session.commitTransaction();
    return post;
  } catch (error) {
    await session.abortTransaction();
    throw new Error(`Error creating post: ${error.message}`);
  } finally {
    session.endSession();
  }
};

// Advanced aggregation query
const getPostStats = async () => {
  try {
    const stats = await Post.aggregate([
      {
        $match: { status: 'published' }
      },
      {
        $group: {
          _id: '$author',
          postCount: { $sum: 1 },
          totalLikes: { $sum: { $size: '$likes' } },
          avgLikes: { $avg: { $size: '$likes' } },
          latestPost: { $max: '$publishedAt' }
        }
      },
      {
        $lookup: {
          from: 'users',
          localField: '_id',
          foreignField: '_id',
          as: 'author'
        }
      },
      {
        $unwind: '$author'
      },
      {
        $project: {
          'author.email': 1,
          'author.profile.firstName': 1,
          'author.profile.lastName': 1,
          postCount: 1,
          totalLikes: 1,
          avgLikes: { $round: ['$avgLikes', 2] },
          latestPost: 1
        }
      },
      {
        $sort: { totalLikes: -1 }
      }
    ]);

    return stats;
  } catch (error) {
    throw new Error(`Error getting post stats: ${error.message}`);
  }
};
```

PostgreSQL with Prisma

Schema Definition

```prisma // schema.prisma generator client { provider = "prisma-client-js" }

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  password  String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  // Profile information
  profile   Profile?

  // Relations
  posts     Post[]
  comments  Comment[]
  likes     Like[]

  // Enums
  role      Role     @default(USER)
  status    UserStatus @default(ACTIVE)

  @@map("users")
}

model Profile {
  id        String @id @default(cuid())
  firstName String?
  lastName  String?
  bio       String?
  avatar    String?
  website   String?

  user      User   @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId    String @unique

  @@map("profiles")
}

model Post {
  id          String   @id @default(cuid())
  title       String
  content     String
  slug        String   @unique
  publishedAt DateTime?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  // Relations
  author      User      @relation(fields: [authorId], references: [id])
  authorId    String
  categories  Category[]
  comments    Comment[]
  likes       Like[]
  tags        Tag[]

  // Enums
  status      PostStatus @default(DRAFT)

  @@map("posts")
}

model Category {
  id    String @id @default(cuid())
  name  String @unique
  slug  String @unique
  posts Post[]

  @@map("categories")
}

model Tag {
  id    String @id @default(cuid())
  name  String @unique
  posts Post[]

  @@map("tags")
}

model Comment {
  id        String   @id @default(cuid())
  content   String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  author    User     @relation(fields: [authorId], references: [id])
  authorId  String
  post      Post     @relation(fields: [postId], references: [id])
  postId    String

  @@map("comments")
}

model Like {
  id     String @id @default(cuid())
  user   User   @relation(fields: [userId], references: [id])
  userId String
  post   Post   @relation(fields: [postId], references: [id])
  postId String

  @@unique([userId, postId])
  @@map("likes")
}

enum Role {
  USER
  ADMIN
  MODERATOR
}

enum UserStatus {
  ACTIVE
  INACTIVE
  SUSPENDED
}

enum PostStatus {
  DRAFT
  PUBLISHED
  ARCHIVED
}
```
### Database Operations

<div class="lazy-content" data-lazy-content="true">

```javascript const { PrismaClient } = require('prisma/client'); const prisma = new PrismaClient();

// Create user with profile
const createUserWithProfile = async (userData) => {
  try {
    const user = await prisma.user.create({
      data: {
        email: userData.email,
        password: userData.password,
        profile: {
          create: {
            firstName: userData.firstName,
            lastName: userData.lastName,
            bio: userData.bio
          }
        }
      },
      include: {
        profile: true
      }
    });

    return user;
  } catch (error) {
    throw new Error(`Error creating user: ${error.message}`);
  }
};

// Get posts with relations
const getPostsWithDetails = async (page = 1, limit = 10) => {
  try {
    const posts = await prisma.post.findMany({
      skip: (page - 1) * limit,
      take: limit,
      where: {
        status: 'PUBLISHED'
      },
      include: {
        author: {
          include: {
            profile: true
          }
        },
        categories: true,
        tags: true,
        comments: {
          include: {
            author: {
              include: {
                profile: true
              }
            }
          }
        },
        _count: {
          select: {
            likes: true,
            comments: true
          }
        }
      },
      orderBy: {
        publishedAt: 'desc'
      }
    });

    return posts;
  } catch (error) {
    throw new Error(`Error fetching posts: ${error.message}`);
  }
};

// Complex transaction example
const createPostWithTags = async (postData) => {
  try {
    const result = await prisma.$transaction(async (tx) => {
      // Create or connect tags
      const tagConnections = [];
      for (const tagName of postData.tags) {
        const tag = await tx.tag.upsert({
          where: { name: tagName },
          update: {},
          create: { name: tagName }
        });
        tagConnections.push({ id: tag.id });
      }

      // Create post
      const post = await tx.post.create({
        data: {
          title: postData.title,
          content: postData.content,
          slug: postData.slug,
          authorId: postData.authorId,
          status: postData.status,
          tags: {
            connect: tagConnections
          }
        },
        include: {
          author: {
            include: {
              profile: true
            }
          },
          tags: true
        }
      });

      return post;
    });

    return result;
  } catch (error) {
    throw new Error(`Error creating post: ${error.message}`);
  }
};

// Raw SQL query example
const getPostStatistics = async () => {
  try {
    const stats = await prisma.$queryRaw`
      SELECT
        u.id,
        u.email,
        p.first_name,
        p.last_name,
        COUNT(po.id) as post_count,
        AVG(like_counts.like_count) as avg_likes,
        MAX(po.published_at) as latest_post
      FROM users u
      LEFT JOIN profiles p ON u.id = p.user_id
      LEFT JOIN posts po ON u.id = po.author_id AND po.status = 'PUBLISHED'
      LEFT JOIN (
        SELECT post_id, COUNT(*) as like_count
        FROM likes
        GROUP BY post_id
      ) like_counts ON po.id = like_counts.post_id
      GROUP BY u.id, u.email, p.first_name, p.last_name
      HAVING COUNT(po.id) > 0
      ORDER BY avg_likes DESC NULLS LAST;
    `;

    return stats;
  } catch (error) {
    throw new Error(`Error getting statistics: ${error.message}`);
  }
};
```

SQLite with Better-SQLite3

Database Setup

```javascript const Database = require('better-sqlite3'); const path = require('path');

// Initialize database
const db = new Database(path.join(__dirname, 'app.db'));

// Enable foreign keys
db.pragma('foreign_keys = ON');

// Create tables
const createTables = () => {
  // Users table
  db.exec(`
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      email TEXT UNIQUE NOT NULL,
      password TEXT NOT NULL,
      first_name TEXT,
      last_name TEXT,
      avatar TEXT,
      role TEXT DEFAULT 'user',
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  `);

  // Posts table
  db.exec(`
    CREATE TABLE IF NOT EXISTS posts (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title TEXT NOT NULL,
      content TEXT NOT NULL,
      slug TEXT UNIQUE NOT NULL,
      author_id INTEGER NOT NULL,
      status TEXT DEFAULT 'draft',
      published_at DATETIME,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (author_id) REFERENCES users (id) ON DELETE CASCADE
    )
  `);

  // Tags table
  db.exec(`
    CREATE TABLE IF NOT EXISTS tags (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT UNIQUE NOT NULL,
      slug TEXT UNIQUE NOT NULL
    )
  `);

  // Post tags junction table
  db.exec(`
    CREATE TABLE IF NOT EXISTS post_tags (
      post_id INTEGER,
      tag_id INTEGER,
      PRIMARY KEY (post_id, tag_id),
      FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE CASCADE,
      FOREIGN KEY (tag_id) REFERENCES tags (id) ON DELETE CASCADE
    )
  `);

  // Comments table
  db.exec(`
    CREATE TABLE IF NOT EXISTS comments (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      content TEXT NOT NULL,
      author_id INTEGER NOT NULL,
      post_id INTEGER NOT NULL,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (author_id) REFERENCES users (id) ON DELETE CASCADE,
      FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE CASCADE
    )
  `);

  // Create indexes
  db.exec(`
    CREATE INDEX IF NOT EXISTS idx_posts_author ON posts (author_id);
    CREATE INDEX IF NOT EXISTS idx_posts_status ON posts (status);
    CREATE INDEX IF NOT EXISTS idx_posts_published ON posts (published_at);
    CREATE INDEX IF NOT EXISTS idx_comments_post ON comments (post_id);
  `);
};

createTables();

// Prepared statements for better performance
const statements = {
  // User operations
  createUser: db.prepare(`
    INSERT INTO users (email, password, first_name, last_name)
    VALUES (?, ?, ?, ?)
  `),

  getUserById: db.prepare(`
    SELECT * FROM users WHERE id = ?
  `),

  getUserByEmail: db.prepare(`
    SELECT * FROM users WHERE email = ?
  `),

  // Post operations
  createPost: db.prepare(`
    INSERT INTO posts (title, content, slug, author_id, status)
    VALUES (?, ?, ?, ?, ?)
  `),

  getPostById: db.prepare(`
    SELECT
      p.*,
      u.email as author_email,
      u.first_name as author_first_name,
      u.last_name as author_last_name
    FROM posts p
    JOIN users u ON p.author_id = u.id
    WHERE p.id = ?
  `),

  getPostsByAuthor: db.prepare(`
    SELECT * FROM posts
    WHERE author_id = ? AND status = 'published'
    ORDER BY published_at DESC
    LIMIT ? OFFSET ?
  `),

  // Tag operations
  createTag: db.prepare(`
    INSERT OR IGNORE INTO tags (name, slug) VALUES (?, ?)
  `),

  getTagByName: db.prepare(`
    SELECT * FROM tags WHERE name = ?
  `),

  addPostTag: db.prepare(`
    INSERT OR IGNORE INTO post_tags (post_id, tag_id) VALUES (?, ?)
  `),

  getPostTags: db.prepare(`
    SELECT t.* FROM tags t
    JOIN post_tags pt ON t.id = pt.tag_id
    WHERE pt.post_id = ?
  `),

  // Comment operations
  createComment: db.prepare(`
    INSERT INTO comments (content, author_id, post_id)
    VALUES (?, ?, ?)
  `),

  getPostComments: db.prepare(`
    SELECT
      c.*,
      u.email as author_email,
      u.first_name as author_first_name,
      u.last_name as author_last_name
    FROM comments c
    JOIN users u ON c.author_id = u.id
    WHERE c.post_id = ?
    ORDER BY c.created_at ASC
  `),

  // Statistics
  getPostStats: db.prepare(`
    SELECT
      u.id,
      u.email,
      u.first_name,
      u.last_name,
      COUNT(p.id) as post_count,
      MAX(p.published_at) as latest_post
    FROM users u
    LEFT JOIN posts p ON u.id = p.author_id AND p.status = 'published'
    GROUP BY u.id
    HAVING post_count > 0
    ORDER BY post_count DESC
  `)
};

// Database operations with transactions
const createPostWithTags = (postData, tagNames) => {
  const transaction = db.transaction((postData, tagNames) => {
    // Create post
    const postResult = statements.createPost.run(
      postData.title,
      postData.content,
      postData.slug,
      postData.authorId,
      postData.status
    );

    const postId = postResult.lastInsertRowid;

    // Create tags and link to post
    for (const tagName of tagNames) {
      const slug = tagName.toLowerCase().replace(/\s+/g, '-');

      // Create tag if it doesn't exist
      statements.createTag.run(tagName, slug);

      // Get tag ID
      const tag = statements.getTagByName.get(tagName);

      // Link post to tag
      statements.addPostTag.run(postId, tag.id);
    }

    return postId;
  });

  return transaction(postData, tagNames);
};

module.exports = { db, statements, createPostWithTags };
```

Testing Examples

Testing Strategies

Jest Unit Testing

Basic Test Setup

```javascript // tests/user.test.js const { User } = require('../models/User'); const bcrypt = require('bcrypt');

// Mock bcrypt
jest.mock('bcrypt');

describe('User Model', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe('User Creation', () => {
    it('should create a user with valid data', async () => {
      const userData = {
        email: 'test@example.com',
        password: 'password123',
        firstName: 'John',
        lastName: 'Doe'
      };

      bcrypt.hash.mockResolvedValue('hashedPassword');

      const user = new User(userData);
      const savedUser = await user.save();

      expect(savedUser.email).toBe(userData.email);
      expect(savedUser.firstName).toBe(userData.firstName);
      expect(bcrypt.hash).toHaveBeenCalledWith('password123', 10);
    });

    it('should throw error for invalid email', async () => {
      const userData = {
        email: 'invalid-email',
        password: 'password123'
      };

      const user = new User(userData);

      await expect(user.save()).rejects.toThrow();
    });

    it('should hash password before saving', async () => {
      const userData = {
        email: 'test@example.com',
        password: 'plainPassword'
      };

      bcrypt.hash.mockResolvedValue('hashedPassword');

      const user = new User(userData);
      await user.save();

      expect(bcrypt.hash).toHaveBeenCalledWith('plainPassword', 10);
      expect(user.password).toBe('hashedPassword');
    });
  });

  describe('User Methods', () => {
    it('should compare password correctly', async () => {
      const user = new User({
        email: 'test@example.com',
        password: 'hashedPassword'
      });

      bcrypt.compare.mockResolvedValue(true);

      const result = await user.comparePassword('plainPassword');

      expect(result).toBe(true);
      expect(bcrypt.compare).toHaveBeenCalledWith('plainPassword', 'hashedPassword');
    });

    it('should return false for wrong password', async () => {
      const user = new User({
        email: 'test@example.com',
        password: 'hashedPassword'
      });

      bcrypt.compare.mockResolvedValue(false);

      const result = await user.comparePassword('wrongPassword');

      expect(result).toBe(false);
    });
  });
});
```
### Service Layer Testing

<div class="lazy-content" data-lazy-content="true">

```javascript // tests/authService.test.js const AuthService = require('../services/AuthService'); const { User } = require('../models/User'); const jwt = require('jsonwebtoken');

jest.mock('../models/User');
jest.mock('jsonwebtoken');

describe('AuthService', () => {
  let authService;

  beforeEach(() => {
    authService = new AuthService();
    jest.clearAllMocks();
  });

  describe('login', () => {
    it('should login user with valid credentials', async () => {
      const mockUser = {
        id: 1,
        email: 'test@example.com',
        comparePassword: jest.fn().mockResolvedValue(true)
      };

      User.findOne.mockResolvedValue(mockUser);
      jwt.sign.mockReturnValue('token123');

      const result = await authService.login('test@example.com', 'password');

      expect(result).toEqual({
        success: true,
        token: 'token123',
        user: { id: 1, email: 'test@example.com' }
      });

      expect(User.findOne).toHaveBeenCalledWith({ email: 'test@example.com' });
      expect(mockUser.comparePassword).toHaveBeenCalledWith('password');
    });

    it('should fail with invalid email', async () => {
      User.findOne.mockResolvedValue(null);

      const result = await authService.login('wrong@example.com', 'password');

      expect(result).toEqual({
        success: false,
        error: 'Invalid credentials'
      });
    });

    it('should fail with invalid password', async () => {
      const mockUser = {
        comparePassword: jest.fn().mockResolvedValue(false)
      };

      User.findOne.mockResolvedValue(mockUser);

      const result = await authService.login('test@example.com', 'wrongpassword');

      expect(result).toEqual({
        success: false,
        error: 'Invalid credentials'
      });
    });
  });

  describe('register', () => {
    it('should register new user successfully', async () => {
      const userData = {
        email: 'new@example.com',
        password: 'password123'
      };

      const mockSavedUser = { id: 1, ...userData };

      User.findOne.mockResolvedValue(null); // User doesn't exist
      User.prototype.save = jest.fn().mockResolvedValue(mockSavedUser);
      jwt.sign.mockReturnValue('token123');

      const result = await authService.register(userData);

      expect(result).toEqual({
        success: true,
        token: 'token123',
        user: mockSavedUser
      });
    });

    it('should fail if user already exists', async () => {
      User.findOne.mockResolvedValue({ email: 'existing@example.com' });

      const result = await authService.register({
        email: 'existing@example.com',
        password: 'password'
      });

      expect(result).toEqual({
        success: false,
        error: 'User already exists'
      });
    });
  });
});
```

API Integration Testing

Express API Testing with Supertest

```javascript // tests/api/auth.test.js const request = require('supertest'); const app = require('../../app'); const { User } = require('../../models/User'); const { setupTestDB, cleanupTestDB } = require('../helpers/database');

describe('Auth API', () => {
  beforeAll(async () => {
    await setupTestDB();
  });

  afterAll(async () => {
    await cleanupTestDB();
  });

  beforeEach(async () => {
    await User.deleteMany({});
  });

  describe('POST /api/auth/register', () => {
    it('should register a new user', async () => {
      const userData = {
        email: 'test@example.com',
        password: 'password123',
        firstName: 'John',
        lastName: 'Doe'
      };

      const response = await request(app)
        .post('/api/auth/register')
        .send(userData)
        .expect(201);

      expect(response.body).toHaveProperty('token');
      expect(response.body.user.email).toBe(userData.email);
      expect(response.body.user).not.toHaveProperty('password');

      // Verify user was created in database
      const user = await User.findOne({ email: userData.email });
      expect(user).toBeTruthy();
      expect(user.firstName).toBe(userData.firstName);
    });

    it('should return 400 for invalid email', async () => {
      const userData = {
        email: 'invalid-email',
        password: 'password123'
      };

      const response = await request(app)
        .post('/api/auth/register')
        .send(userData)
        .expect(400);

      expect(response.body).toHaveProperty('error');
    });

    it('should return 409 for existing email', async () => {
      // Create user first
      const user = new User({
        email: 'existing@example.com',
        password: 'password123'
      });
      await user.save();

      const response = await request(app)
        .post('/api/auth/register')
        .send({
          email: 'existing@example.com',
          password: 'newpassword'
        })
        .expect(409);

      expect(response.body.error).toBe('User already exists');
    });
  });

  describe('POST /api/auth/login', () => {
    let user;

    beforeEach(async () => {
      user = new User({
        email: 'test@example.com',
        password: 'password123'
      });
      await user.save();
    });

    it('should login with valid credentials', async () => {
      const response = await request(app)
        .post('/api/auth/login')
        .send({
          email: 'test@example.com',
          password: 'password123'
        })
        .expect(200);

      expect(response.body).toHaveProperty('token');
      expect(response.body.user.email).toBe('test@example.com');
    });

    it('should return 401 for invalid password', async () => {
      const response = await request(app)
        .post('/api/auth/login')
        .send({
          email: 'test@example.com',
          password: 'wrongpassword'
        })
        .expect(401);

      expect(response.body.error).toBe('Invalid credentials');
    });
  });

  describe('GET /api/auth/profile', () => {
    let user, token;

    beforeEach(async () => {
      user = new User({
        email: 'test@example.com',
        password: 'password123'
      });
      await user.save();

      // Get auth token
      const loginResponse = await request(app)
        .post('/api/auth/login')
        .send({
          email: 'test@example.com',
          password: 'password123'
        });

      token = loginResponse.body.token;
    });

    it('should get user profile with valid token', async () => {
      const response = await request(app)
        .get('/api/auth/profile')
        .set('Authorization', `Bearer ${token}`)
        .expect(200);

      expect(response.body.user.email).toBe('test@example.com');
    });

    it('should return 401 without token', async () => {
      await request(app)
        .get('/api/auth/profile')
        .expect(401);
    });

    it('should return 403 with invalid token', async () => {
      await request(app)
        .get('/api/auth/profile')
        .set('Authorization', 'Bearer invalid-token')
        .expect(403);
    });
  });
});
```
### Database Integration Testing

<div class="lazy-content" data-lazy-content="true">

```javascript // tests/integration/database.test.js const mongoose = require('mongoose'); const { User, Post } = require('../../models');

describe('Database Integration', () => {
  beforeAll(async () => {
    await mongoose.connect(process.env.TEST_DATABASE_URL);
  });

  afterAll(async () => {
    await mongoose.connection.close();
  });

  beforeEach(async () => {
    await User.deleteMany({});
    await Post.deleteMany({});
  });

  describe('User-Post Relationship', () => {
    it('should create user with posts', async () => {
      const user = new User({
        email: 'author@example.com',
        password: 'password123'
      });
      await user.save();

      const post1 = new Post({
        title: 'First Post',
        content: 'Content of first post',
        author: user._id,
        status: 'published'
      });

      const post2 = new Post({
        title: 'Second Post',
        content: 'Content of second post',
        author: user._id,
        status: 'draft'
      });

      await Promise.all([post1.save(), post2.save()]);

      // Test population
      const userWithPosts = await User.findById(user._id).populate('posts');
      expect(userWithPosts.posts).toHaveLength(2);
    });

    it('should cascade delete posts when user is deleted', async () => {
      const user = new User({
        email: 'author@example.com',
        password: 'password123'
      });
      await user.save();

      const post = new Post({
        title: 'Test Post',
        content: 'Test content',
        author: user._id
      });
      await post.save();

      // Delete user
      await User.findByIdAndDelete(user._id);

      // Check if posts are deleted (depends on your schema configuration)
      const remainingPosts = await Post.find({ author: user._id });
      expect(remainingPosts).toHaveLength(0);
    });
  });

  describe('Transactions', () => {
    it('should rollback on error', async () => {
      const session = await mongoose.startSession();

      try {
        await session.withTransaction(async () => {
          const user = new User({
            email: 'test@example.com',
            password: 'password123'
          });
          await user.save({ session });

          // This should cause an error due to duplicate email
          const duplicateUser = new User({
            email: 'test@example.com',
            password: 'password456'
          });
          await duplicateUser.save({ session });
        });
      } catch (error) {
        // Expected error
      } finally {
        await session.endSession();
      }

      // Verify no users were created
      const userCount = await User.countDocuments({ email: 'test@example.com' });
      expect(userCount).toBe(0);
    });
  });
});
```

End-to-End Testing with Playwright

Test Setup

javascript // playwright.config.js module.exports = { testDir: './e2e', timeout: 30000, expect: { timeout: 5000 }, fullyParallel: true, forbidOnly: !!process.env.CI, retries: process.env.CI ? 2 : 0, workers: process.env.CI ? 1 : undefined, reporter: 'html', use: { baseURL: 'http://localhost:3000', trace: 'on-first-retry', screenshot: 'only-on-failure' }, projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, { name: 'webkit', use: { ...devices['Desktop Safari'] } }, { name: 'Mobile Chrome', use: { ...devices['Pixel 5'] } } ], webServer: { command: 'npm run start', port: 3000 } };

Authentication Flow Testing

```javascript // e2e/auth.spec.js const { test, expect } = require('playwright/test');

test.describe('Authentication Flow', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/');
  });

  test('should register new user', async ({ page }) => {
    await page.click('text=Sign Up');

    await page.fill('[data-testid="email"]', 'newuser@example.com');
    await page.fill('[data-testid="password"]', 'password123');
    await page.fill('[data-testid="confirmPassword"]', 'password123');
    await page.fill('[data-testid="firstName"]', 'John');
    await page.fill('[data-testid="lastName"]', 'Doe');

    await page.click('[data-testid="submitButton"]');

    // Should redirect to dashboard
    await expect(page).toHaveURL('/dashboard');
    await expect(page.locator('[data-testid="welcomeMessage"]')).toContainText('Welcome, John');
  });

  test('should login existing user', async ({ page }) => {
    await page.click('text=Sign In');

    await page.fill('[data-testid="email"]', 'test@example.com');
    await page.fill('[data-testid="password"]', 'password123');

    await page.click('[data-testid="loginButton"]');

    await expect(page).toHaveURL('/dashboard');
    await expect(page.locator('[data-testid="userMenu"]')).toBeVisible();
  });

  test('should show error for invalid credentials', async ({ page }) => {
    await page.click('text=Sign In');

    await page.fill('[data-testid="email"]', 'test@example.com');
    await page.fill('[data-testid="password"]', 'wrongpassword');

    await page.click('[data-testid="loginButton"]');

    await expect(page.locator('[data-testid="errorMessage"]')).toContainText('Invalid credentials');
    await expect(page).toHaveURL('/login');
  });

  test('should logout user', async ({ page }) => {
    // Login first
    await page.goto('/login');
    await page.fill('[data-testid="email"]', 'test@example.com');
    await page.fill('[data-testid="password"]', 'password123');
    await page.click('[data-testid="loginButton"]');

    // Wait for dashboard
    await expect(page).toHaveURL('/dashboard');

    // Logout
    await page.click('[data-testid="userMenu"]');
    await page.click('text=Logout');

    await expect(page).toHaveURL('/');
    await expect(page.locator('text=Sign In')).toBeVisible();
  });
});

test.describe('Protected Routes', () => {
  test('should redirect to login for protected routes', async ({ page }) => {
    await page.goto('/dashboard');

    await expect(page).toHaveURL('/login');
    await expect(page.locator('[data-testid="loginForm"]')).toBeVisible();
  });

  test('should access protected routes when authenticated', async ({ page, context }) => {
    // Set authentication cookie/token
    await context.addCookies([{
      name: 'authToken',
      value: 'valid-jwt-token',
      domain: 'localhost',
      path: '/'
    }]);

    await page.goto('/dashboard');

    await expect(page).toHaveURL('/dashboard');
    await expect(page.locator('[data-testid="dashboard"]')).toBeVisible();
  });
});
```
### Complex User Interactions

<div class="lazy-content" data-lazy-content="true">

```javascript // e2e/blog.spec.js const { test, expect } = require('playwright/test');

test.describe('Blog Management', () => {
  test.beforeEach(async ({ page, context }) => {
    // Login as authenticated user
    await context.addCookies([{
      name: 'authToken',
      value: 'valid-jwt-token',
      domain: 'localhost',
      path: '/'
    }]);

    await page.goto('/dashboard');
  });

  test('should create new blog post', async ({ page }) => {
    await page.click('[data-testid="newPostButton"]');

    await page.fill('[data-testid="postTitle"]', 'My New Blog Post');

    // Rich text editor interaction
    const editor = page.locator('[data-testid="contentEditor"]');
    await editor.click();
    await editor.fill('This is the content of my blog post. It has **bold text** and *italic text*.');

    // Add tags
    await page.click('[data-testid="addTagButton"]');
    await page.fill('[data-testid="tagInput"]', 'javascript');
    await page.press('[data-testid="tagInput"]', 'Enter');

    await page.click('[data-testid="addTagButton"]');
    await page.fill('[data-testid="tagInput"]', 'tutorial');
    await page.press('[data-testid="tagInput"]', 'Enter');

    // Select category
    await page.selectOption('[data-testid="categorySelect"]', 'Technology');

    // Publish post
    await page.click('[data-testid="publishButton"]');

    // Should redirect to post view
    await expect(page).toHaveURL(/\/posts\/\d+/);
    await expect(page.locator('h1')).toContainText('My New Blog Post');
    await expect(page.locator('[data-testid="postContent"]')).toContainText('This is the content');

    // Check tags are displayed
    await expect(page.locator('[data-testid="tag"]')).toHaveCount(2);
  });

  test('should edit existing post', async ({ page }) => {
    // Navigate to existing post
    await page.goto('/posts/1');

    await page.click('[data-testid="editButton"]');

    // Modify title
    await page.fill('[data-testid="postTitle"]', 'Updated Blog Post Title');

    // Update content
    const editor = page.locator('[data-testid="contentEditor"]');
    await editor.selectAll();
    await editor.fill('Updated content for the blog post.');

    await page.click('[data-testid="saveButton"]');

    // Verify changes
    await expect(page.locator('h1')).toContainText('Updated Blog Post Title');
    await expect(page.locator('[data-testid="postContent"]')).toContainText('Updated content');
  });

  test('should delete post with confirmation', async ({ page }) => {
    await page.goto('/posts/1');

    await page.click('[data-testid="deleteButton"]');

    // Confirmation dialog
    await expect(page.locator('[data-testid="confirmDialog"]')).toBeVisible();
    await expect(page.locator('[data-testid="confirmMessage"]')).toContainText('Are you sure you want to delete this post?');

    await page.click('[data-testid="confirmDelete"]');

    // Should redirect to posts list
    await expect(page).toHaveURL('/dashboard/posts');

    // Post should not exist
    await expect(page.locator('text=Updated Blog Post Title')).not.toBeVisible();
  });
});
```

Summary

Content Tabs Implementation Complete

This comprehensive implementation provides:

✅ Basic tab functionality with Material Design styling
✅ Advanced configuration options for customization
✅ Comprehensive usage examples across multiple scenarios
✅ Responsive design with mobile optimization
✅ Accessibility features with keyboard navigation
✅ Integration patterns with other components
✅ Performance optimizations and best practices

The content tabs feature is now fully configured and documented with extensive examples demonstrating real-world usage patterns.