Complete Thriven AI Chat App Tutorial

A comprehensive guide to understanding how this modern web application works, covering HTML structure, backend services, JavaScript functionality and Google Cloud Platform integration.

Share
My Learning Progress
0%

Progress recorded when you check "Completed" on each module

Welcome to the Tutorial

Beginner

Welcome to this interactive tutorial on the Thriven AI Chat Application! In this guide, we'll break down every component of this modern web application to help you understand how it works.

Note: This tutorial is designed for beginners with basic knowledge of HTML, CSS and JavaScript. We'll explain concepts in simple terms.

The application we're studying is a feature-rich chat interface that includes:

  • User authentication system with Firebase
  • Multiple AI assistant modes (coding, career, health, etc.)
  • Real-time chat with OpenAI integration
  • Responsive design with mobile gestures
  • Code highlighting and copying features

Quick App Demo

Try this simplified version of the chat interface:

Hello! How can I help you today?

Let's start by exploring the HTML structure of the application!

Next Section

1. HTML Structure

HTML

In HTML the structure of a document works like the skeleton of a web page. It organizes everything the browser will show and it helps the page display correctly on different devices. Beginners often find HTML easier when each part of the page is broken down into simple sections and explained step by step.

Every HTML document starts with a declaration that tells the browser what type of document it is so the browser knows how to read it. After that the page is divided into two major sections which are the head and the body. The head stores information about the page and the body stores everything the user can see.

Head Section

Contains meta tags title and external resources

Sidebar

Collapsible panel that shows chat history and user profile

Main Chat Area

Displays messages between the user and the AI

Input Section

Contains the text area and buttons for sending messages

Key HTML Sections:

  1. Head Section: Contains meta tags title and links to external tools like Tailwind CSS Font Awesome and Highlight.js. These resources help style the page and add features without writing everything from scratch.
  2. Sidebar: A collapsible panel that stores navigation chat history and profile information. It helps users access features quickly on both mobile and desktop screens.
  3. Main Chat Area: Displays all chat messages in a smooth scrolling layout so users can follow conversations easily.
  4. Input Section: Contains the text box and buttons for sending messages so it is the main place where users interact with the AI.
  5. Authentication Modal: A pop up window that appears when users need to log in or create an account.

Tip: HTML uses semantic elements like <header> <main> <footer> These elements improve accessibility and boost SEO because they help browsers understand the purpose of each part of the page.

Each part of the structure works together to create a clear responsive and user friendly layout so the design looks good on phones tablets and larger screens. A strong HTML foundation also makes it easier to add JavaScript and styling later.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <title>THRIVEN AI - Enhanced</title>

  <!-- External resources -->
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body class="bg-gray-900 text-white min-h-screen">
  <div class="flex h-screen">

    <!-- Sidebar -->
    <aside id="sidebarDrawer" class="fixed inset-y-0 left-0 z-40 w-72 bg-gray-800 border-r border-gray-700 transform -translate-x-full md:translate-x-0 md:static md:inset-auto transition-transform">
      <!-- Sidebar content -->
    </aside>

    <!-- Main content -->
    <div class="flex-1 flex flex-col md:pl-0 min-w-0">

      <header class="flex items-center justify-between bg-gray-800 border-b border-gray-700 px-4 py-3">
        <!-- Header content -->
      </header>

      <main id="chat-messages" class="flex-1 overflow-y-auto p-4 md:p-6 space-y-6 scroll-smooth">
        <!-- Chat messages appear here -->
      </main>

      <footer class="border-t border-gray-700 p-4">
        <!-- Input area -->
      </footer>

    </div>
  </div>

  <!-- Authentication Modal -->
  <div id="authModal" class="fixed inset-0 z-50 hidden flex items-center justify-center auth-modal bg-black/60">
    <!-- Modal content -->
  </div>

  <script type="module">
    // JavaScript code goes here
  </script>
</body>
</html>

Before You Start the Quiz

• Once you start a quiz section, you must finish all 5 questions within 5 minutes.

• Your score and the total time you spend will be saved securely on our server for global ranking.

• You can track your quiz history anytime by clicking the user icon in the navbar.

• Perform well to stand a chance of winning rewards such as merchandise and special gifts featured in each quiz section.

⚠ Once you submit your quiz results, you cannot replay that section.

2. CSS Styling

CSS

What is CSS?

CSS (Cascading Style Sheets) is the language that controls how your website looks. If HTML is the structure or skeleton, then CSS is the design — the colors, layout, spacing, animations, shadows, shapes, responsiveness and more.

In this project, CSS is responsible for the modern, clean, dark-theme layout. We use a mix of:

  • Tailwind CSS utility classes
  • Custom CSS for scrollbars and animations
  • Responsive styling for mobile → desktop

Why CSS is Important

CSS improves:

  • Readability and flow of content
  • User interface (UI) and user experience (UX)
  • Mobile responsiveness
  • Brand identity and professionalism

Key CSS Features Used in This App

  • Custom Scrollbars – Styled to match the dark theme
  • Animations – Elements fade in smoothly
  • Responsive Layout – Adapts to mobile and desktop
  • Dark Mode UI – Clean consistent color scheme
  • Code Styling – Prettified blocks for readability

Before CSS

Plain message box

After CSS

Styled message box

This project uses a mobile-first approach. That means we write styles for small screens first and scale upward. It ensures the UI works perfectly on phones.

Tip: Tailwind and Bootstrap are examples of pre-built CSS libraries. They provide ready-made classes for spacing, colors, layout, and animation—saving hours of work and helping beginners build professional-looking UIs very quickly.

Bonus: CSS Basics for Beginners (Interactive)

Try adjusting the values below and watch the box change instantly. This helps you understand how CSS works in real time.

1. Colors

Change the text color or background color using any CSS color (name, hex, rgb, etc.)

This is a preview box.

2. Margin

Margin controls the space outside the box.

Box with adjustable margin

3. Padding

Padding adds space inside the box.

Box with adjustable padding

4. Borders

Adjust the border width and radius.

Box with adjustable border & radius

5. CSS Selectors (Visualization)

Type a color and see how different selectors affect boxes.

.class selector
#id selector

div p selector

6. Flexbox Alignment

Choose how items should align.

1
2
3

7. CSS Grid

Control the number of columns.

A
B
C
D
style.css
/* Custom Scrollbar */
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: #111827; }
::-webkit-scrollbar-thumb { background: #374151; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #4b5563; }

/* Animations */
.transition-all { transition: all .2s ease; }
@keyframes fadeIn { 
  from { opacity:0; transform: translateY(8px); } 
  to { opacity:1; transform: translateY(0);} 
}
.message-fade-in { animation: fadeIn .22s ease-out forwards; }

/* Sidebar Logic */
#sidebarDrawer { min-width: 250px; max-width: 400px; }
#resizer { width: 5px; cursor: ew-resize; position: absolute; top:0; right:0; bottom:0; z-index:50; }

/* Markdown Styles */
.prose pre { margin: 0.5rem 0; padding: 0; border-radius: 0.5rem; overflow: hidden; position: relative; }
.prose code { font-family: 'Courier New', Courier, monospace; font-size: 0.9em; }

/* Code Block Header */
.code-header {  
  display: flex; justify-content: space-between; align-items: center;  
  background: #2d2d2d; padding: 4px 10px; font-size: 0.75rem; color: #aaa;  
}

Before You Start the Quiz

• Once you start a quiz section, you must finish all 5 questions within 5 minutes.

• Your score and the total time you spend will be saved securely on our server for global ranking.

• You can track your quiz history anytime by clicking the user icon in the navbar.

• Perform well to stand a chance of winning rewards such as merchandise and special gifts featured in each quiz section.

⚠ Once you submit your quiz results, you cannot replay that section.

3. JavaScript Imports

JavaScript

In this section, we look at how our web application loads different JavaScript libraries using CDNs (Content Delivery Networks). A CDN is simply a fast online server where popular libraries are hosted, so instead of downloading files manually, you just link to them using a URL. This keeps your project lightweight, simple and easy to update.

Think of each imported library as a “tool” that adds superpowers to your project. Instead of building everything from scratch, we rely on these trusted tools to handle complicated tasks such as code highlighting, alerts, authentication and markdown rendering. Beginners often find imports confusing, but just remember: imports allow your project to reuse ready-made features created by experts.

Most libraries in this project are loaded using a simple <script> or <link> tag. But Firebase works differently because it uses modern JavaScript modules. That’s why it is wrapped inside: <script type="module"> — this allows you to import only the Firebase features your app needs, making your code cleaner and faster.

Below is a quick overview of the major libraries used and what purpose they serve in the project:

Firebase

Powers user authentication, storing messages, saving accounts and managing data.

Highlight.js

Automatically styles and colors code blocks sent inside the chat.

Marked

Converts Markdown symbols (like **bold**, *italic*, # headings) into readable HTML.

SweetAlert2

Replaces boring browser alerts with elegant, animated popup messages.

Key Libraries:

  • Firebase: Handles login, registration, data storage and user sessions.
  • Highlight.js: Highlights and formats code snippets beautifully.
  • Marked: Converts markdown text to rich HTML messages.
  • SweetAlert2: Provides modern popup alerts that improve user experience.
  • Tailwind CSS: A fast, utility-first CSS framework for styling layouts.

As a beginner, don’t worry if the import structure looks complex. You’ll quickly get used to recognizing each library and understanding why it’s needed. The key is: imports let your app use powerful features without you writing everything from scratch.

Note: Using CDN-hosted libraries means we don't need to download or store the files ourselves — saving space and keeping deployment simple.

JavaScript Imports
<!-- Tailwind CSS for styling -->
<script src="https://cdn.tailwindcss.com"></script>

<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<!-- Marked for markdown parsing -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

<!-- Highlight.js for code syntax highlighting -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>

<!-- SweetAlert2 for beautiful alerts -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- Firebase for backend services -->
<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js";
  import { 
      getAuth, 
      createUserWithEmailAndPassword, 
      signInWithEmailAndPassword, 
      signOut, 
      onAuthStateChanged,
      updateProfile,
      deleteUser,
      sendPasswordResetEmail
  } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js";
  import { 
      getFirestore, 
      doc, 
      setDoc, 
      getDoc, 
      deleteDoc 
  } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js";
</script>

Before You Start the Quiz

• Once you start a quiz section, you must finish all 5 questions within 5 minutes.

• Your score and the total time you spend will be saved securely on our server for global ranking.

• You can track your quiz history anytime by clicking the user icon in the navbar.

• Perform well to stand a chance of winning rewards such as merchandise and special gifts featured in each quiz section.

⚠ Once you submit your quiz results, you cannot replay that section.

4. Firebase Setup

Backend

Firebase is a tool that gives your website a powerful backend without setting up your own server. It helps you handle login, save data and protect your app. You only connect it once then you use it anywhere in your code.

How Firebase Works in a Simple Web Project

A normal web project has only three files

  • index.html – the page the user sees
  • style.css – the design of the page
  • app.js – the logic you write for your app

Firebase connects to your project through your JavaScript file. Once you add the Firebase SDK you can log in users save data and read data in real time.

Steps to Create a Simple Web Project with Firebase

1

Create a Firebase Project

Open Firebase Console select Add project and follow the setup

2

Create Your Web Folder

Make a folder on your computer and add three files index.html style.css and app.js

3

Enable Authentication

Turn on Email and Password login inside the Authentication section

4

Create Firestore Database

Set Firestore to production mode then create your first collection

5

Get Firebase Config

Go to Project Settings scroll down to Web App then copy the config object

6

Paste Config Into app.js

Add the Firebase scripts in index.html then paste your config in app.js

Firebase Services Used in This App

  • Firebase Authentication: Handles login signup and keeping users logged in
  • Cloud Firestore: Stores your app data messages profiles and more
  • Firebase Security Rules: Protects your database so users can only access their own data

Important: Firebase API keys are safe to show during development but for real production apps use environment variables or a backend to protect sensitive data.

Firebase Configuration
// Firebase configuration object
const firebaseConfig = {
  apiKey: "your-api-key",
  authDomain: "your-project.firebaseapp.com",
  projectId: "your-project-id",
  storageBucket: "your-project.appspot.com",
  messagingSenderId: "123456789",
  appId: "your-app-id"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);

// Monitor authentication state
onAuthStateChanged(auth, async (user) => {
  if (user) {
    // User is signed in
    console.log("User is signed in:", user.email);
    // Update UI to show user is logged in
  } else {
    // User is signed out
    console.log("User is signed out");
    // Update UI to show login options
  }
});

Before You Start the Quiz

• Once you start a quiz section, you must finish all 5 questions within 5 minutes.

• Your score and the total time you spend will be saved securely on our server for global ranking.

• You can track your quiz history anytime by clicking the user icon in the navbar.

• Perform well to stand a chance of winning rewards such as merchandise and special gifts featured in each quiz section.

⚠ Once you submit your quiz results, you cannot replay that section.

5. Authentication System

Security

The authentication system is what allows people to create accounts and sign in to your app. It is built with Firebase Authentication and it uses a simple email and password setup. When a user signs up Firebase creates their account and stores their profile in Firestore. When they sign in Firebase keeps them logged in even if the page refreshes. This makes the app feel smooth and secure.

How Authentication Works:

1

User Registration

The user enters email password and name to create an account

2

Account Creation

Firebase creates the account and Firestore stores the profile info

3

User Login

The user signs in with email and password and Firebase verifies them

4

Session Management

Firebase keeps the user logged in after page reloads so they do not lose progress

5

User Logout

The user can sign out and Firebase ends the session

Authentication Features:

  • User Registration: Create a new account with email verification
  • User Login: Sign in with email and password
  • Password Reset: Send a reset link when the user forgets their password
  • Profile Management: Update name or other user details
  • Account Deletion: Remove the user and their data forever

Tip: The system uses Firebase's onAuthStateChanged function to check if the user is logged in and update the UI instantly.

Authentication Code
// User registration
async function registerUser(email, password, name) {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    const user = userCredential.user;
    
    // Update user profile
    await updateProfile(user, { displayName: name });
    
    // Store user data in Firestore
    await setDoc(doc(db, "aiUsers", user.uid), {
      name: name,
      email: email,
      createdAt: new Date().toISOString()
    });
    
    return { success: true, user: user };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

// User login
async function loginUser(email, password) {
  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    return { success: true, user: userCredential.user };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

// Password reset
async function resetPassword(email) {
  try {
    await sendPasswordResetEmail(auth, email);
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

// Monitor auth state
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in
    updateUIForSignedInUser(user);
  } else {
    // User is signed out
    updateUIForSignedOutUser();
  }
});

Before You Start the Quiz

• Once you start a quiz section, you must finish all 5 questions within 5 minutes.

• Your score and the total time you spend will be saved securely on our server for global ranking.

• You can track your quiz history anytime by clicking the user icon in the navbar.

• Perform well to stand a chance of winning rewards such as merchandise and special gifts featured in each quiz section.

⚠ Once you submit your quiz results, you cannot replay that section.

6. Chat Interface

UI/UX

The Chat Interface is the central hub of your application. It’s where users interact with the AI, view their history, and switch between specialized modes. A well-designed interface is crucial for a smooth and intuitive user experience (UX).

Core Components:

  • Sidebar Navigation: Manages chat history, user profile, and session controls. It uses Local Storage to persist conversations.
  • Message Area: The main display for chat bubbles. It utilizes a Scroll-to-Bottom utility to keep the latest message in view and uses the marked.js library to parse and render Markdown into clean HTML.
  • Input Bar (Footer): Contains the Prompt Textarea, which auto-resizes for a better typing experience, and the Send Button to initiate API calls.
  • Feature Mode Selector: Allows users to switch between specialized AI modes (e.g., General, Coding, Career) by changing the System Prompt sent to the AI model.

The Chat Interaction Flow:

1

User Submits Prompt

The user types a message and clicks 'Send' or presses 'Enter'. The app disables the input.

2

Message Added to UI & State

The user's message is immediately rendered, added to the conversations state object, and a loading indicator appears for the AI response.

3

API Call with Context

The entire conversation history (plus the selected System Prompt) is sent to the OpenAI API to maintain context.

4

Render and Save Response

The final AI text is returned, the loading indicator is removed, the response is rendered (with Markdown/Code highlighting), and the updated conversation is saved to Local Storage.

Enhancing UI/UX:

  • Code Highlighting: The use of highlight.js is critical to correctly style code blocks returned by the AI, improving readability for technical responses.
  • Sidebar Gestures: Implementing touch-based logic (like the mobile swipe gestures in the JavaScript) makes the sidebar accessible on mobile devices, greatly improving the mobile UX.
  • Session Persistence: By using localStorage to save the conversations object, the application remembers the user's history even after the browser is closed.

Tip: The core logic of the chat is centered around the handleGenerate function, which orchestrates the UI update, state management, and the asynchronous API request.

Chat Interface - Key JavaScript Logic
// The core logic orchestrating the chat flow

async function handleGenerate() {
const prompt = promptInput.value.trim();
if (!prompt) return;
// 1. UI Reset and State Init
if (!currentConversationId) { /* ... init logic ... */ }
// 2. Add User Message
const userMsg = { role: 'user', content: prompt, timestamp: new Date().toISOString() };
conversations[currentConversationId].messages.push(userMsg);
renderMessage(userMsg);
// ... Loading message ...
// 3. Prepare API Payload with Context
const systemContent = SYSTEM_PROMPTS[currentMode];
const systemMsg = { role: 'system', content: systemContent };
// The API call uses the system message + full history
const apiMessages = [systemMsg, ...conversations[currentConversationId].messages.map(m => ({role: m.role, content: m.content}))];
// 4. API Call (await callOpenAI(apiMessages);)
const responseText = await callOpenAI(apiMessages);
// 5. Render and Save
const aiMsg = { role: 'assistant', content: responseText, timestamp: new Date().toISOString() };
conversations[currentConversationId].messages.push(aiMsg);
saveConversations(); // Saves to localStorage
renderMessage(aiMsg);
}
// Function to render a single message (User or AI)
function renderMessage(msg) {
// ... logic for creating the chat bubble HTML ...
// Uses marked.parse(msg.content) for markdown rendering
// Uses hljs.highlightElement for code highlighting
}
// System Prompts for different modes
const SYSTEM_PROMPTS = {
general: "You are Thriven AI, a helpful, friendly, and intelligent assistant.",
coding: "You are an expert Senior Software Engineer...",
career: "You are a professional Career Coach...",
// ... and others
};
// Saving function
function saveConversations() {
localStorage.setItem('thriven-ai-conversations', JSON.stringify(conversations));
renderChatHistory(); // Updates sidebar titles
}

Before You Start the Quiz

• Once you start a quiz section, you must finish all 5 questions within 5 minutes.

• Your score and the total time you spend will be saved securely on our server for global ranking.

• You can track your quiz history anytime by clicking the user icon in the navbar.

• Perform well to stand a chance of winning rewards such as merchandise and special gifts featured in each quiz section.

⚠ Once you submit your quiz results, you cannot replay that section.

7. Message Handling

Logic

The Message Handling section defines the core logic for communicating with the AI. This is where the application transforms raw user input into an API request, manages the asynchronous response, and beautifully renders the result back to the user interface.

The handleGenerate Function: The Orchestrator

The handleGenerate function is the control center. It performs three critical actions in sequence:

  1. UI/State Update: Captures the user's prompt, adds it to the current conversation state (conversations object), renders it instantly, and displays a loading indicator.
  2. Context Assembly: Creates the full API payload by combining the user's entire conversation history with the selected System Prompt (from SYSTEM_PROMPTS). This step is vital for the AI to maintain conversational context.
  3. API Execution: Calls the callOpenAI function asynchronously and waits for the response.
  4. Final Render & Save: Removes the loading indicator, adds the AI's final response to the state, renders it in the chat, and saves the updated conversation to Local Storage.

Rendering and Formatting Messages

The renderMessage function ensures AI responses are readable and visually appealing. This involves two major external libraries:

  • Markdown Parsing (marked.js): The AI's response is raw text containing Markdown syntax (e.g., *bullet points*, **bold text**, ```javascript code blocks```). marked.js converts this into correct HTML tags.
  • Syntax Highlighting (highlight.js): Code snippets converted into <pre><code> blocks are passed to highlight.js (via processCodeBlocks), which adds beautiful syntax highlighting.

Helper Utilities

  • copyCode(btn): Copies raw text from a highlighted code block using navigator.clipboard.writeText, giving instant user feedback.
  • scrollToBottom(): Ensures the user always sees the latest message by automatically scrolling to the bottom of the chat after each message.
Message Handling - Key JavaScript Logic


// The main function that drives the interaction
async function handleGenerate() {
const prompt = promptInput.value.trim();
if (!prompt) return;
// 1. UI/State Update (Add user message)
if (!currentConversationId) { /* initialize new conversation */ }
const userMsg = { role: 'user', content: prompt };
conversations[currentConversationId].messages.push(userMsg);
renderMessage(userMsg);
// ... show loading indicator ...
// 2. Context Assembly
const systemContent = SYSTEM_PROMPTS[currentMode];
const apiMessages = [
{ role: 'system', content: systemContent },
...conversations[currentConversationId].messages.map(m => ({role: m.role, content: m.content}))
];
try {
// 3. API Execution
const responseText = await callOpenAI(apiMessages);
// 4. Final Render & Save
// ... remove loading indicator ...
const aiMsg = { role: 'assistant', content: responseText };
conversations[currentConversationId].messages.push(aiMsg);
saveConversations();
renderMessage(aiMsg);

} catch (err) {
// ... display error message ...
}
}
// Renders the message content using markdown parsing and highlighting
function renderMessage(msg) {
// ... (omitted bubble HTML creation)
const rawHtml = marked.parse(msg.content);
// ... (insert rawHtml into bubble)
processCodeBlocks(div); // Calls highlight.js
}
// Applies syntax highlighting to code blocks
function processCodeBlocks(messageDiv) {
const blocks = messageDiv.querySelectorAll('pre code');
blocks.forEach((block) => {
hljs.highlightElement(block);
// ... (adds copy button header)
});
}

Before You Start the Quiz

• Once you start a quiz section, you must finish all 5 questions within 5 minutes.

• Your score and the total time you spend will be saved securely on our server for global ranking.

• You can track your quiz history anytime by clicking the user icon in the navbar.

• Perform well to stand a chance of winning rewards such as merchandise and special gifts featured in each quiz section.

⚠ Once you submit your quiz results, you cannot replay that section.

8. OpenAI Integration

API

The OpenAI Integration section is the bridge between your app and the intelligent AI model. It handles the critical task of sending user requests to OpenAI's servers and retrieving the generated responses. This communication uses an API (Application Programming Interface), which is like a waiter taking your order to the kitchen (OpenAI) and bringing back your meal (the AI response).

Communicating with the API

The entire conversation happens inside the asynchronous callOpenAI function. Here’s what it does:

  1. Endpoint: It uses the correct web address (URL) for the OpenAI Chat Completions service (https://api.openai.com/v1/chat/completions).
  2. Authentication: It includes your secret API Key in the request's header. This key acts as your secure password, proving to OpenAI that you are authorized to use their service.
  3. Payload (The Request Body): It sends a JSON object containing three essential pieces of information: the model you want to use (like gpt-4o-mini), the temperature (how creative the response should be), and the messages array (the full conversation context).
  4. The Response: Once the request is sent, the function pauses (await) until OpenAI sends back a JSON response containing the AI's answer.

Managing Context and Persona

To have a meaningful conversation, the AI needs to remember what was said before and who it's supposed to be. This is achieved using the Messages Array in the API payload, which contains objects with two keys: role and content.

  • System Role: The very first message is always the System Prompt (e.g., "You are an expert Senior Software Engineer..."). This sets the persona and rules for the AI.
  • User/Assistant Roles: All subsequent messages are the back-and-forth between the user (role: 'user') and the AI (role: 'assistant'). By sending this complete history, you give the AI the necessary context to continue the chat naturally.

API Key Security

For a production application, you should never expose your OPENAI_KEY directly in the client-side JavaScript file, as it can be easily stolen. A secure setup requires using a server (like a Firebase Cloud Function or a simple Node.js endpoint) to handle the API calls privately. However, for this educational example, the key is temporarily placed as a variable.

Tip: The temperature parameter controls the randomness of the AI. A lower value (e.g., 0.2) makes the response more predictable and factual, while a higher value (e.g., 1.0) makes it more creative but potentially less accurate.

OpenAI Integration - Key JavaScript Logic

// --- CONFIGURATION ---
const OPENAI_KEY = "YOUR_SECRET_KEY_HERE"; // !!! Never expose this in a real app!

// --- API Handler ---
async function callOpenAI(messagesPayload) {
  if (!OPENAI_KEY) throw new Error("API Key not configured.");
  const res = await fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer " + OPENAI_KEY
    },
    body: JSON.stringify({
      // Model choice: fast and capable
      model: "gpt-4o-mini",
      // The full history including the System Prompt
      messages: messagesPayload,
      // Controls creativity (0.7 is a good balance)
      temperature: 0.7
    })
  });
  const data = await res.json();
  if (data.error) throw new Error(data.error.message);
  // Return the actual text response
  return data.choices[0].message.content;
}
      

Before You Start the Quiz

• Once you start a quiz section, you must finish all 5 questions within 5 minutes.

• Your score and the total time you spend will be saved securely on our server for global ranking.

• You can track your quiz history anytime by clicking the user icon in the navbar.

• Perform well to stand a chance of winning rewards such as merchandise and special gifts featured in each quiz section.

⚠ Once you submit your quiz results, you cannot replay that section.

9. Mobile Features

Mobile

A great application must work perfectly on any screen size, especially on phones. This chapter covers the features that make the chat interface responsive, and easy to use on a small screen. We use Tailwind CSS for adaptive layouts, and JavaScript for touch-friendly interactions.

Responsiveness and Layout

The layout adapts using CSS breakpoints (like md: for medium devices). On desktop screens, the sidebar is always visible. On mobile screens, the layout changes dramatically:

  • Sidebar Hiding: The chat history sidebar is hidden off-screen (-translate-x-full) by default to maximize space for the chat area,
  • Dynamic Buttons: The New Chat button, and the menu icons change visibility based on screen size, ensuring only essential controls are shown,
  • Viewport Meta Tag: The HTML includes the <meta name="viewport" content="width=device-width, initial-scale=1.0"> tag, which is essential to tell the mobile browser to scale the page correctly, preventing tiny, unreadable text,

Touch and Swipe Gestures

Typing, and navigating should be as fluid on mobile as on a desktop. We implement specific JavaScript logic to enable intuitive touch controls, primarily focused on the Sidebar Drawer:

  • Opening the Sidebar: Users can open the sidebar by pressing the Menu icon, or by using a Swipe Right gesture from the left edge of the screen,
  • Closing the Sidebar: Users can close the sidebar by pressing the Close icon, tapping the dark Overlay that appears, or using a Swipe Left gesture directly on the drawer,
  • Touch Events: The logic uses standard Touch Events (touchstart, touchmove, touchend) to track finger movement, and calculate how far the user has dragged the drawer,

These gestures make navigating between the current chat, and the history feel native and fast on any modern smartphone,

Tip: The passive: true option added to touch event listeners is a performance optimization. It tells the browser that the script won't call preventDefault(), which allows the browser to perform scrolling actions without waiting for the script, making the app feel much smoother,

Mobile Features - Swipe Gesture Logic

function initSwipeForDrawer() {
  let touchStartX = 0;
  let isDraggingDrawer = false;

  // 1. Start Swipe on Sidebar
  sidebarDrawer.addEventListener('touchstart', e => {
    if (e.touches.length !== 1) return;
    touchStartX = e.touches[0].clientX;
    isDraggingDrawer = !sidebarDrawer.classList.contains('-translate-x-full');
  }, { passive: true });

  // 2. Move Finger - Visual Dragging
  sidebarDrawer.addEventListener('touchmove', e => {
    if (!isDraggingDrawer) return;
    let deltaX = e.touches[0].clientX - touchStartX;
    if (deltaX < 0) {
      sidebarDrawer.style.transform = `translateX(${deltaX}px)`;
    }
  }, { passive: true });

  // 3. Lift Finger - Decide Close or Snap Back
  sidebarDrawer.addEventListener('touchend', e => {
    if (!isDraggingDrawer) return;
    let touchEndX = e.changedTouches[0].clientX;
    let deltaX = touchEndX - touchStartX;

    if (deltaX < -60) {
      closeSidebar(); // Function to close the menu
    } else {
      sidebarDrawer.style.transform = '';
    }

    touchStartX = 0;
    isDraggingDrawer = false;
  });
}
      

Before You Start the Quiz

• Once you start a quiz section, you must finish all 5 questions within 5 minutes.

• Your score and the total time you spend will be saved securely on our server for global ranking.

• You can track your quiz history anytime by clicking the user icon in the navbar.

• Perform well to stand a chance of winning rewards such as merchandise and special gifts featured in each quiz section.

⚠ Once you submit your quiz results, you cannot replay that section.

10. Final Notes & Project Ideas

Summary

Congratulations on completing this tutorial! You've learned how a modern web application is structured and how different technologies work together.

Key Takeaways:

  • Modern web apps combine HTML, CSS and JavaScript
  • External services like Firebase can handle complex backend tasks
  • APIs (like OpenAI) can add powerful functionality to your apps
  • Responsive design ensures your app works on all devices
  • Good UX includes features like loading indicators and error handling

Project Enhancement Ideas:

  • Add support for multiple AI models (GPT-4, Claude, etc.)
  • Implement file uploads for document analysis
  • Add voice input/output capabilities
  • Create a plugin system for custom functionality
  • Add collaborative features for team usage
  • Implement advanced analytics for chat usage

Learning Path: To continue your web development journey, consider learning about:

  • React, Vue or other JavaScript frameworks
  • Node.js for server-side development
  • Database design and management
  • Web security best practices
  • Progressive Web Apps (PWAs)

Remember, the best way to learn is by building projects. Try modifying this application or creating your own from scratch!

Tutorial Complete!
Previous