diff --git a/.github/workflows/lighthouse-report.yml b/.github/workflows/lighthouse-report.yml index e848b34..3856486 100644 --- a/.github/workflows/lighthouse-report.yml +++ b/.github/workflows/lighthouse-report.yml @@ -42,13 +42,9 @@ jobs: http://localhost:3000/tutorial/ http://localhost:3000/tutorial/category/html/ http://localhost:3000/tutorial/css/introduction/what-is-css - http://localhost:3000/tutorial/javascript/introduction-to-javascript/what-is-js http://localhost:3000/tutorial/git/introduction - http://localhost:3000/tutorial/category/getting-started-with-github - http://localhost:3000/tutorial/github/introduction-to-github http://localhost:3000/tutorial/react/react-intro http://localhost:3000/tutorial/cybersecurity - http://localhost:3000/tutorial/tags configPath: ./.github/workflows/lighthouserc.json uploadArtifacts: true temporaryPublicStorage: true diff --git a/docs/internet/browser-devtools.mdx b/docs/internet/browser-devtools.mdx index e345ed2..6952fbd 100644 --- a/docs/internet/browser-devtools.mdx +++ b/docs/internet/browser-devtools.mdx @@ -1 +1,217 @@ - \ No newline at end of file +--- +title: "Browser Developer Tools" +description: "Learn how to use Browser Developer Tools (DevTools) to inspect, debug, and optimize websites for performance, accessibility, and security." +tags: [browser, devtools, debugging, chrome, frontend, performance] +sidebar_label: Browser DevTools +--- + +Modern web browsers come with a powerful suite of built-in tools known as **Developer Tools (DevTools)**. These tools help developers **inspect**, **debug**, **analyze**, and **optimize** web applications directly within the browser. + +:::info +Think of DevTools as your web development Swiss Army knife — it provides everything you need to understand how a webpage works under the hood and fix issues on the fly. +::: + +## What Are Browser DevTools? + +**Browser DevTools** are a set of debugging tools integrated into browsers like **Chrome**, **Firefox**, **Edge**, and **Safari**. They allow you to view and interact with the **HTML**, **CSS**, **JavaScript**, **network requests**, and **performance metrics** of any webpage. + +You can open DevTools by pressing: + +* **Windows/Linux:** `Ctrl + Shift + I` or `F12` +* **macOS:** `Cmd + Option + I` + +## Core Panels in DevTools + +Let’s explore the most important panels and their uses: + +| Panel | Purpose | Example Use | +| ------ | -------- | ----------- | +| **Elements** | Inspect and modify HTML & CSS live | Change a button color or test responsive layout | +| **Console** | Run JavaScript commands & view logs/errors | `console.log()` debugging | +| **Network** | Monitor API calls, page load time, and caching | Analyze slow API responses | +| **Sources** | View and debug JavaScript files with breakpoints | Pause code at runtime | +| **Performance** | Analyze runtime performance and memory usage | Optimize page rendering | +| **Application** | View storage, cookies, and service workers | Inspect LocalStorage data | +| **Security** | Check HTTPS and certificate information | Identify mixed-content issues | +| **Lighthouse** | Generate audits for performance, SEO, and accessibility | Get site improvement recommendations | + +## Elements Panel + +The **Elements panel** allows you to explore and edit your website’s structure and styles in real-time. + +```mermaid +graph TD + A[HTML Document] --> B[DOM Tree] + B --> C[Styles - CSS] + C --> D[Rendered Page] +``` + +**Example:** + +Change the text of a heading directly from the DOM inspector — it won’t affect your source code, but helps test design changes instantly. + + + +## Console Panel + +The **Console** is your **interactive JavaScript terminal**. You can log data, test snippets, or view error messages. + +```js title="Console" +console.log("Hello, CodeHarborHub!"); +``` + +**Output:** + +``` +Hello, CodeHarborHub! +``` + +Common uses: + +* Debugging JavaScript code +* Monitoring warnings or errors +* Inspecting objects and variables + +:::tip + +You can also use the Console to execute JavaScript on the fly, making it a powerful tool for testing and debugging. + +You can also use shortcuts like: +* `$0` → selects the last inspected element from the Elements panel +* `clear()` → clears the console output +::: + + +## Network Panel + +The **Network panel** shows every HTTP request made by the browser — scripts, images, CSS, APIs, and more. + + + + * Request and response headers + * File sizes and load times + * Waterfall visualization of loading sequence + * Status codes (e.g., 200, 404, 500) + + + Helps identify slow resources, failed requests, or caching problems — key for improving **performance** and **user experience**. + + + +## Sources Panel + +Use the **Sources panel** to: +* View and debug JavaScript files +* Set **breakpoints** +* Step through your code +* Watch variable values as your script runs + +```jsx live +function DebugExample() { + const [count, setCount] = React.useState(0); + return ( +
+

Debug Counter Example

+

Count: {count}

+ +
+ ); +} +``` + +Try adding a **breakpoint** on the `setCount` line in DevTools to pause execution and inspect the current state. + +## Application Panel + +The **Application panel** helps manage client-side storage and data. + +You can inspect: +* **Cookies** +* **LocalStorage** / **SessionStorage** +* **IndexedDB** +* **Service Workers** +* **Cache Storage** +* **Manifest files** + +This is extremely helpful for debugging **PWAs (Progressive Web Apps)** or authentication tokens. + +## Performance Panel + +The **Performance** tab allows you to **record runtime activity** — useful for diagnosing rendering issues and JavaScript bottlenecks. + +Key metrics include: +* Frame rendering time +* Layout and paint events +* JavaScript execution time +* Memory usage + +```mermaid +graph LR +A[User Action] --> B[Script Execution] +B --> C[Layout Reflow] +C --> D[Paint] +D --> E[Composite Layers] +``` + +A well-optimized page maintains **60 frames per second (FPS)** for smooth performance. + +:::info + +Think of the Performance panel as a high-speed camera that captures every millisecond of your webpage’s activity, allowing you to pinpoint exactly where delays occur. + +::: + + +## Lighthouse Audits + +The **Lighthouse** tool (under the “Audits” or “Lighthouse” panel) evaluates your web app for: +* Performance +* Accessibility +* SEO +* Progressive Web App (PWA) features + +It provides actionable reports with scores and recommendations. + +## Example: Inspecting a Button + +```html + +``` + +In the **Elements panel**, you can: +* Modify the color dynamically +* Add hover states +* Copy computed CSS styles + +Then test the interaction directly without editing the source code. + +## Math Behind Load Time (KaTeX Example) + +If a page loads 3 MB of data in 6 seconds: + +$$ +Load\ Speed = \frac{3\ \text{MB}}{6\ \text{s}} = 0.5\ \text{MB/s} +$$ + +Optimizing image size, caching, and lazy loading can drastically reduce this time. + +## Best Practices for Using DevTools + +* Use **Console logs** for quick debugging, but remove them before production. +* Check **Network requests** for unnecessary files or slow APIs. +* Run **Lighthouse** regularly for performance improvements. +* Monitor **Memory leaks** using the Performance tab. +* Use **Responsive Design Mode** to test across devices. + +## Key Takeaways + +* DevTools empower you to **inspect, debug, and optimize** web applications. +* Mastering key panels (Elements, Console, Network) saves hours of debugging. +* Tools like **Lighthouse** and **Performance** enhance web speed and accessibility. +* DevTools are your **real-time lab** for frontend development. + +:::tip Try It Yourself + +Open DevTools on any website and experiment with the panels discussed. Change styles, debug scripts, and analyze network requests to see how they affect the page in real-time! + +::: \ No newline at end of file diff --git a/docs/internet/nslookup.mdx b/docs/internet/nslookup.mdx index e345ed2..0aa9386 100644 --- a/docs/internet/nslookup.mdx +++ b/docs/internet/nslookup.mdx @@ -1 +1,183 @@ - \ No newline at end of file +--- +title: "Understanding nslookup" +description: "Learn how the nslookup command helps you query DNS records, verify domain configurations, and troubleshoot Internet connectivity issues." +tags: [dns, networking, nslookup, domain, cli, troubleshooting] +sidebar_label: nslookup +--- + +The **`nslookup`** (Name Server Lookup) command is one of the most essential tools for network diagnostics. It allows you to **query DNS servers** to find the IP address of a domain or verify other DNS records like MX, TXT, or CNAME. + +:::info +Think of `nslookup` as a phone book for the Internet — it helps you find the phone number (IP address) associated with a person’s name (domain). +::: + +## What Is nslookup? + +`nslookup` stands for **Name Server Lookup**. It’s a command-line tool available on Windows, macOS, and Linux that helps you: + +* Check if a **domain name** resolves correctly to an IP address. +* View **DNS records** for troubleshooting. +* Identify **name server (NS)** or **mail server (MX)** configurations. +* Diagnose **DNS-related issues** such as incorrect resolution or timeouts. + +## Basic Syntax + +```bash +nslookup [options] [domain] [dns-server] +``` + +| Parameter | Description | +| ---------- | ------------ | +| `domain` | The domain name you want to query (e.g., `codeharborhub.github.io`) | +| `dns-server` | (Optional) The specific DNS server you want to use | +| `options` | Flags or arguments to modify the behavior | + +Example: + +```bash +nslookup codeharborhub.github.io +``` + +Output: + +```bash +Server: dns.google +Address: 8.8.8.8 + +Non-authoritative answer: +Name: codeharborhub.github.io +Address: 185.199.108.153 +``` + +## How nslookup Works + +When you run `nslookup`, it sends a **query** to a **DNS resolver**. The resolver checks its cache or contacts **authoritative name servers** to find the answer. + +```mermaid +sequenceDiagram + participant User as You + participant Resolver as DNS Resolver + participant Root as Root Server + participant TLD as .io Server + participant Auth as GitHub Authoritative Server + + User->>Resolver: nslookup codeharborhub.github.io + Resolver->>Root: Request for .io + Root-->>Resolver: TLD Server (.io) + Resolver->>TLD: Request for github.io + TLD-->>Resolver: Authoritative Name Server info + Resolver->>Auth: Query for codeharborhub.github.io + Auth-->>Resolver: IP Address (185.199.108.153) + Resolver-->>User: Returns the resolved IP +``` + +## Common Use Cases + +| Purpose | Command | Description | +| -------- | -------- | ------------ | +| Basic IP lookup | `nslookup google.com` | Returns the IP address for the domain | +| Use a specific DNS server | `nslookup codeharborhub.github.io 8.8.8.8` | Queries Google DNS (8.8.8.8) | +| Check MX records | `nslookup -type=mx gmail.com` | Lists mail servers for Gmail | +| View Name Servers | `nslookup -type=ns github.com` | Shows authoritative DNS servers | +| View TXT records | `nslookup -type=txt openai.com` | Displays domain verification or SPF records | +| Reverse lookup | `nslookup 8.8.8.8` | Finds the domain name associated with an IP | + +## Interactive Example + +```jsx live +function NslookupDemo() { + const [domain, setDomain] = React.useState("codeharborhub.github.io"); + const [response, setResponse] = React.useState(""); + + const handleLookup = () => { + setResponse(`Non-authoritative answer: +Name: ${domain} +Address: 185.199.108.153`); + }; + + return ( +
+

Simulate nslookup Command

+ setDomain(e.target.value)} + style={{ padding: "8px", width: "60%", borderRadius: "8px" }} + /> +
+ +
{response}
+
+ ); +} +``` + +In this simulation, you can enter any domain name and click "Run Lookup" to see a mock response similar to what `nslookup` would return. + +## Types of DNS Records You Can Query + +| Record Type | Description | Example | +| ------------ | ------------ | -------- | +| `A` | Maps a domain name to an IPv4 address | `185.199.108.153` | +| `AAAA` | Maps a domain to an IPv6 address | `2606:50c0:8001::153` | +| `MX` | Identifies mail servers for the domain | `aspmx.l.google.com` | +| `NS` | Lists authoritative name servers | `ns1.github.io` | +| `CNAME` | Provides alias names | `www → codeharborhub.github.io` | +| `TXT` | Stores verification or SPF info | `"v=spf1 include:_spf.google.com"` | + +## Common Issues and Errors + +| Error | Meaning | +| ------ | -------- | +| `*** Can't find server name` | DNS resolver not configured properly | +| `Non-existent domain` | The queried domain does not exist | +| `Request timed out` | DNS server not responding | +| `NXDOMAIN` | The domain name can’t be resolved | + +## Example: Query Timing + +If a DNS query takes 50 ms to respond and you perform 4 lookups: + +$$ +Average\ Query\ Time = \frac{50 + 48 + 52 + 50}{4} = 50\text{ ms} +$$ + +That means your DNS response time averages around **50 milliseconds**, which is quite fast. + +:::note +Keep in mind that DNS caching can affect response times. Subsequent queries for the same domain may return faster results due to cached data. +::: + +## Quick Commands Reference + +```bash +# Basic domain lookup +nslookup codeharborhub.github.io + +# Query using Cloudflare DNS +nslookup codeharborhub.github.io 1.1.1.1 + +# Check mail records +nslookup -type=mx example.com + +# Find authoritative name servers +nslookup -type=ns example.com +``` + +## Key Takeaways + +* **`nslookup`** queries DNS servers to fetch IPs and record details. +* It’s useful for **troubleshooting**, **validation**, and **network diagnostics**. +* Works across platforms (Windows, macOS, Linux). +* Helps identify **DNS misconfigurations, delays, or missing records**. +* Understanding DNS records (A, MX, NS, CNAME, TXT) is crucial for effective use of `nslookup`. \ No newline at end of file diff --git a/docs/internet/ping-and-traceroute.mdx b/docs/internet/ping-and-traceroute.mdx index e345ed2..f6de188 100644 --- a/docs/internet/ping-and-traceroute.mdx +++ b/docs/internet/ping-and-traceroute.mdx @@ -1 +1,153 @@ - \ No newline at end of file +--- +title: "Ping and Traceroute" +description: "Learn how Ping and Traceroute help diagnose network connectivity issues, measure latency, and trace the path your data takes across the Internet." +tags: [networking, internet, ping, traceroute, latency, diagnostics] +sidebar_label: Ping and Traceroute +--- + +When your Internet feels slow or a website won’t load, tools like **Ping** and **Traceroute** help you understand what’s happening behind the scenes. They are essential network utilities used by developers, system admins, and engineers to **diagnose connectivity problems** and **analyze network performance**. + +## What Are Ping and Traceroute? + +Both tools check **how data travels** between your device (client) and another server (host), but they do it in different ways. + +| Tool | Purpose | Protocol Used | +| ---- | -------- | -------------- | +| **Ping** | Tests connectivity and measures response time (latency). | ICMP (Internet Control Message Protocol) | +| **Traceroute** | Maps the route data takes through routers (hops) to reach the destination. | ICMP or UDP | + +:::info +Think of Ping as sending a quick “Are you there?” message to a server, while Traceroute is like asking for directions and noting every stop along the way. +::: + +## Ping: Testing Connectivity and Latency + +**Ping** sends a small packet (an “echo request”) to a target server and waits for an “echo reply.” It measures how long it takes for the message to travel to the target and back known as the **Round Trip Time (RTT)**. + +```bash +ping codeharborhub.github.io +``` + +Typical output: +```bash +Pinging codeharborhub.github.io [185.199.108.153] with 32 bytes of data: +Reply from 185.199.108.153: bytes=32 time=45ms TTL=57 +Reply from 185.199.108.153: bytes=32 time=47ms TTL=57 +Reply from 185.199.108.153: bytes=32 time=44ms TTL=57 + +Ping statistics: +Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), +Approximate round trip times in milliseconds: +Minimum = 44ms, Maximum = 47ms, Average = 45ms +``` + +### What Ping Tells You + +* **If the destination is reachable** +* **Latency (RTT)** — time taken for data to travel back and forth +* **Packet loss** — if packets don’t make it to the destination or back + +If all packets are lost, the host may be offline, blocked by a firewall, or unreachable. + +:::info +Lower ping times (e.g., 20ms) indicate a faster connection, while higher times (e.g., 200ms) suggest latency issues. +::: + +## Traceroute: Mapping the Path of Data + +**Traceroute** shows the **route** your packets take from your device to the destination server listing every **hop** (router) along the way. + +```bash +traceroute codeharborhub.github.io +``` + +Example output: +```bash +Tracing route to codeharborhub.github.io [185.199.108.153] +over a maximum of 30 hops: + + 1 <1 ms <1 ms <1 ms 192.168.0.1 + 2 8 ms 9 ms 8 ms 100.64.0.1 + 3 25 ms 24 ms 26 ms 203.0.113.5 + 4 42 ms 43 ms 41 ms 185.199.108.153 + +Trace complete. +``` + +Each “hop” represents a router or network device forwarding your data toward its destination. + +:::info +Think of Traceroute as a travel itinerary showing every stop your data makes on its journey across the Internet. +::: + +## How Traceroute Works + +Traceroute sends packets with **increasing TTL (Time To Live)** values. Each router that handles the packet **decreases the TTL by 1**. When TTL reaches 0, the router sends back an ICMP “Time Exceeded” message. + +```mermaid +sequenceDiagram + participant A as Your Device + participant B as Router 1 + participant C as Router 2 + participant D as Destination Server + + A->>B: TTL=1 (Expires) + B-->>A: ICMP Time Exceeded + A->>C: TTL=2 (Expires) + C-->>A: ICMP Time Exceeded + A->>D: TTL=3 (Delivered) + D-->>A: ICMP Echo Reply +``` + +This process allows Traceroute to **map every hop** between you and the final destination. + + +## Common Use Cases + +| Scenario | Tool | What You Learn | +| -------- | ---- | --------------- | +| Website not loading | Ping | Is the server reachable? | +| Slow website response | Ping | Check latency or packet loss | +| Identifying network bottlenecks | Traceroute | Where delays occur between hops | +| ISP troubleshooting | Traceroute | Which router or region has high latency | + +## Common Issues and Interpretations + +* `Request timed out` → A router or firewall blocked ICMP responses. +* `Destination host unreachable` → The server or network is down. +* High latency at certain hops → Possible congestion or slow routing. +* Stable ping but slow web load → Could be DNS or application-level delay. + +## Example Calculation: Average Ping Time + +If you receive ping times of 40ms, 42ms, 44ms, and 46ms: + +$$ +Average\ Latency = \frac{40 + 42 + 44 + 46}{4} = 43\ \text{ms} +$$ + +This means your system’s network latency to that server is about **43 milliseconds**. + +## Key Takeaways + +* **Ping** measures reachability and response time. +* **Traceroute** maps the route your packets take. +* Both tools use **ICMP** to analyze connectivity and network health. +* Useful for diagnosing **latency, packet loss, or routing issues**. + +## Try It Yourself + +On Windows: +```bash +ping google.com +tracert google.com +``` + +On macOS/Linux: + +```bash +ping -c 4 google.com +traceroute google.com +``` + +In this way, you can start diagnosing your own network issues and better understand how data travels across the Internet! \ No newline at end of file diff --git a/docs/internet/quiz.mdx b/docs/internet/quiz.mdx index e345ed2..6fab27e 100644 --- a/docs/internet/quiz.mdx +++ b/docs/internet/quiz.mdx @@ -1 +1,128 @@ - \ No newline at end of file +--- +title: Internet Quiz +description: Test your knowledge of how the Internet works with this interactive quiz. +keywords: ["internet", "quiz", "networking", "web", "dns", "http", "tcp-ip"] +--- + +import { Quiz } from "@site/src/components/Quiz"; + +**Think you understand how the Internet works?** + +Take this quiz to test your skills on DNS, IP, HTTP, TCP/IP, and more! + + + +--- + + +:::tip +You can revisit topics like **DNS, HTTP, TCP/IP, Firewalls, and CDNs** before retrying the quiz to improve your score. +::: \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 5c0076c..3911f94 100644 --- a/package-lock.json +++ b/package-lock.json @@ -45,6 +45,7 @@ "fontawesome": "^5.6.3", "framer-motion": "^11.11.8", "joi": "^17.12.1", + "lucide-react": "^0.548.0", "passport": "^0.7.0", "passport-github": "^1.1.0", "prism-react-renderer": "^2.3.1", @@ -65,7 +66,8 @@ "rehype-katex": "^7.0.0", "remark-math": "^6.0.0", "styled-components": "^6.1.8", - "swiper": "^12.0.2", + "swiper": "^11.1.4", + "tailwind-merge": "^3.3.1", "three": "^0.169.0", "vanilla-tilt": "^1.8.1" }, @@ -16411,6 +16413,14 @@ "yallist": "^3.0.2" } }, + "node_modules/lucide-react": { + "version": "0.548.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.548.0.tgz", + "integrity": "sha512-63b16z63jM9yc1MwxajHeuu0FRZFsDtljtDjYm26Kd86UQ5HQzu9ksEtoUUw4RBuewodw/tGFmvipePvRsKeDA==", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/magic-string": { "version": "0.25.9", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz", @@ -25492,9 +25502,9 @@ } }, "node_modules/swiper": { - "version": "12.0.2", - "resolved": "https://registry.npmjs.org/swiper/-/swiper-12.0.2.tgz", - "integrity": "sha512-y8F6fDGXmTVVgwqJj6I00l4FdGuhpFJn0U/9Ucn1MwWOw3NdLV8aH88pZOjyhBgU/6PyBlUx+JuAQ5KMWz906Q==", + "version": "11.2.10", + "resolved": "https://registry.npmjs.org/swiper/-/swiper-11.2.10.tgz", + "integrity": "sha512-RMeVUUjTQH+6N3ckimK93oxz6Sn5la4aDlgPzB+rBrG/smPdCTicXyhxa+woIpopz+jewEloiEE3lKo1h9w2YQ==", "funding": [ { "type": "patreon", @@ -25505,7 +25515,6 @@ "url": "http://opencollective.com/swiper" } ], - "license": "MIT", "engines": { "node": ">= 4.7.0" } @@ -25522,6 +25531,15 @@ "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, + "node_modules/tailwind-merge": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.3.1.tgz", + "integrity": "sha512-gBXpgUm/3rp1lMZZrM/w7D8GKqshif0zAymAhbCyIt8KMe+0v9DQ7cdYLR4FHH/cKpdTXb+A/tKKU3eolfsI+g==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, "node_modules/tailwindcss": { "version": "3.4.17", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz", diff --git a/package.json b/package.json index a82aafb..45d3465 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ "fontawesome": "^5.6.3", "framer-motion": "^11.11.8", "joi": "^17.12.1", + "lucide-react": "^0.548.0", "passport": "^0.7.0", "passport-github": "^1.1.0", "prism-react-renderer": "^2.3.1", @@ -72,7 +73,8 @@ "rehype-katex": "^7.0.0", "remark-math": "^6.0.0", "styled-components": "^6.1.8", - "swiper": "^12.0.2", + "swiper": "^11.1.4", + "tailwind-merge": "^3.3.1", "three": "^0.169.0", "vanilla-tilt": "^1.8.1" }, diff --git a/src/components/Quiz.tsx b/src/components/Quiz.tsx new file mode 100644 index 0000000..7f472c4 --- /dev/null +++ b/src/components/Quiz.tsx @@ -0,0 +1,177 @@ +import React, { useState } from "react"; +import { motion, AnimatePresence } from "framer-motion"; +import { Button } from "./ui/button"; +import { Card, CardContent } from "./ui/card"; +import { CheckCircle, XCircle, RefreshCw, ArrowRight } from "lucide-react"; + +interface Question { + question: string; + options: string[]; + answer: number; + explanation: string; +} + +interface QuizProps { + questions: Question[]; +} + +export const Quiz: React.FC = ({ questions }) => { + const [current, setCurrent] = useState(0); + const [selected, setSelected] = useState(null); + const [score, setScore] = useState(0); + const [showResults, setShowResults] = useState(false); + + const currentQuestion = questions[current]; + + const handleAnswer = (index: number) => { + if (selected !== null) return; + setSelected(index); + if (index === currentQuestion.answer) { + setScore((prev) => prev + 1); + } + }; + + const nextQuestion = () => { + if (current + 1 < questions.length) { + setCurrent((prev) => prev + 1); + setSelected(null); + } else { + setShowResults(true); + } + }; + + const resetQuiz = () => { + setCurrent(0); + setSelected(null); + setScore(0); + setShowResults(false); + }; + + return ( +
+ + + {!showResults ? ( + + +
+

+ Question {current + 1} of {questions.length} +

+ + Score: {score} + +
+ +

+ {currentQuestion.question} +

+ +
+ {currentQuestion.options.map((option, index) => { + const isCorrect = index === currentQuestion.answer; + const isSelected = index === selected; + + const baseClass = + "w-full text-left px-4 py-3 rounded-xl border transition-all duration-300 focus:ring-2 focus:ring-offset-2 focus:outline-none "; + let stateClass = ""; + + if (selected === null) { + stateClass = + "border-gray-300 dark:border-gray-700 hover:border-blue-500 hover:bg-blue-500/10"; + } else if (isSelected && isCorrect) { + stateClass = "border-green-500 bg-green-500/10 text-green-600 dark:text-green-400"; + } else if (isSelected && !isCorrect) { + stateClass = "border-red-500 bg-red-500/10 text-red-600 dark:text-red-400"; + } else { + stateClass = "opacity-60 border-gray-200 dark:border-gray-700"; + } + + return ( + handleAnswer(index)} + disabled={selected !== null} + whileHover={selected === null ? { scale: 1.02 } : {}} + whileTap={{ scale: 0.98 }} + className={baseClass + stateClass} + > + {option} + + ); + })} +
+ + {selected !== null && ( + + {selected === currentQuestion.answer ? ( +

+ Correct! +

+ ) : ( +

+ Incorrect. +

+ )} + +

+ 💡 {currentQuestion.explanation} +

+ + +
+ )} +
+
+ ) : ( + +

+ 🎉 Quiz Completed! +

+

+ You scored{" "} + + {score} + {" "} + out of {questions.length}. +

+ + +
+ )} +
+
+
+ ); +}; diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx new file mode 100644 index 0000000..94f65a6 --- /dev/null +++ b/src/components/ui/button.tsx @@ -0,0 +1,40 @@ +import * as React from "react"; +import { cn } from "../../lib/utils"; + +export interface ButtonProps + extends React.ButtonHTMLAttributes { + variant?: "default" | "outline" | "ghost"; + size?: "sm" | "md" | "lg"; +} + +export const Button = React.forwardRef( + ({ className, variant = "default", size = "md", ...props }, ref) => { + const base = + "inline-flex items-center justify-center font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2"; + + const variants = { + default: + "bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500 dark:bg-blue-500 dark:hover:bg-blue-600 dark:focus:ring-blue-400", + outline: + "border border-gray-300 text-gray-800 hover:bg-gray-100 focus:ring-gray-400 dark:border-gray-700 dark:text-gray-200 dark:hover:bg-gray-800", + ghost: + "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800", + }; + + const sizes = { + sm: "px-3 py-1 text-sm", + md: "px-4 py-2 text-base", + lg: "px-6 py-3 text-lg", + }; + + return ( +