REFACTOR: Enhance Categories Page;

REFACTOR: Update ListRow component;
REFACTOR: Improve component structure and navigation; FEAT: Scroll fetching hook;
REFACTOR: Add more testing_data to database to demonstrate updated ListRow component;
This commit is contained in:
Chris-1010
2025-02-16 23:01:09 +00:00
parent 9f59810833
commit d79f617b4f
13 changed files with 240 additions and 162 deletions

View File

@@ -52,7 +52,7 @@ function App() {
path="/category/:category_name"
element={<CategoryPage />}
></Route>
<Route path="/category" element={<CategoriesPage />}></Route>
<Route path="/categories" element={<CategoriesPage />}></Route>
<Route path="/results" element={<ResultsPage />}></Route>
<Route path="/404" element={<NotFoundPage />} />
<Route path="*" element={<Navigate to="/404" replace />} />

View File

@@ -53,6 +53,7 @@ export const Return: React.FC = () => {
// Main CheckoutForm component
interface CheckoutFormProps {
streamerID: number;
onClose: () => void;
}

View File

@@ -32,21 +32,19 @@ export const ToggleButton: React.FC<ToggleButtonProps> = ({
children = "Toggle",
extraClasses = "",
onClick,
toggled = false
toggled = false,
}) => {
toggled
? (extraClasses += " cursor-default bg-purple-600")
: (extraClasses +=
" cursor-pointer hover:text-purple-600 hover:bg-black/80 hover:border-purple-500 hover:border-b-4 hover:border-l-4");
return (
<div>
<button
className={`${extraClasses} p-2 text-[1.5rem] text-white bg-black/30 rounded-[1rem] border border-gray-300 transition-all`}
onClick={onClick}
>
{children}
</button>
</div>
<button
className={`${extraClasses} p-2 text-[1.5rem] text-white bg-black/30 rounded-[1rem] border border-gray-300 transition-all`}
onClick={onClick}
>
{children}
</button>
);
};

View File

@@ -0,0 +1,54 @@
import React from "react";
export interface ListItemProps {
type: "stream" | "category";
id: number;
title: string;
streamer?: string;
streamCategory?: string;
viewers: number;
thumbnail?: string;
onItemClick?: () => void;
}
const ListItem: React.FC<ListItemProps> = ({
type,
title,
streamer,
streamCategory,
viewers,
thumbnail,
onItemClick,
}) => {
return (
<div className="p-4">
<div
className="min-w-[25vw] overflow-hidden flex-shrink-0 flex flex-col bg-purple-900 rounded-lg
cursor-pointer hover:bg-pink-700 hover:scale-105 transition-all"
onClick={onItemClick}
>
<div className="relative w-full pt-[56.25%] overflow-hidden rounded-t-lg">
{thumbnail ? (
<img
src={thumbnail}
alt={title}
className="absolute top-0 left-0 w-full h-full object-cover"
/>
) : (
<div className="absolute top-0 left-0 w-full h-full bg-gray-600" />
)}
</div>
<div className="p-3">
<h3 className="font-semibold text-lg text-center">{title}</h3>
{type === "stream" && <p className="font-bold">{streamer}</p>}
{type === "stream" && (
<p className="text-sm text-gray-300">{streamCategory}</p>
)}
<p className="text-sm text-gray-300">{viewers} viewers</p>
</div>
</div>
</div>
);
};
export default ListItem;

View File

@@ -1,46 +1,44 @@
import React, { useRef } from "react";
import { ArrowLeft as ArrowLeftIcon, ArrowRight as ArrowRightIcon } from "lucide-react";
import "../../assets/styles/listRow.css"
interface ListItemProps {
type: "stream" | "category";
id: number;
title: string;
streamer?: string;
streamCategory?: string;
viewers: number;
thumbnail?: string;
onItemClick?: () => void;
}
import {
ArrowLeft as ArrowLeftIcon,
ArrowRight as ArrowRightIcon,
} from "lucide-react";
import "../../assets/styles/listRow.css";
import ListItem, { ListItemProps } from "./ListItem";
interface ListRowProps {
type: "stream" | "category";
title: string;
description: string;
type: "stream" | "category" | "user";
title?: string;
description?: string;
items: ListItemProps[];
extraClasses?: string;
wrap: boolean;
onClick: (itemName: string) => void;
extraClasses?: string;
children?: React.ReactNode;
}
// Row of entries
const ListRow: React.FC<ListRowProps> = ({
title,
description,
title = "",
description = "",
items,
wrap,
onClick,
extraClasses = "",
children,
}) => {
const slider = useRef<HTMLDivElement>(null);
const scrollAmount = window.innerWidth * 0.3;
const slideRight = () => {
if (slider.current) {
slider.current.scrollBy({ left: +200, behavior: "smooth" });
if (!wrap && slider.current) {
slider.current.scrollBy({ left: +scrollAmount, behavior: "smooth" });
}
};
const slideLeft = () => {
if (slider.current) {
slider.current.scrollBy({ left: -200, behavior: "smooth" });
if (!wrap && slider.current) {
slider.current.scrollBy({ left: -scrollAmount, behavior: "smooth" });
}
};
@@ -54,13 +52,26 @@ const ListRow: React.FC<ListRowProps> = ({
</div>
<div className="relative overflow-hidden flex items-center z-0">
<ArrowLeftIcon onClick={slideLeft} size={20} className="absolute mr-1 cursor-pointer z-[999]" />
{!wrap && items.length > 3 && (
<>
<ArrowLeftIcon
onClick={slideLeft}
size={30}
className="absolute left-0 cursor-pointer z-[999]"
/>
<ArrowRightIcon
onClick={slideRight}
size={30}
className="absolute right-0 cursor-pointer z-[999]"
/>
</>
)}
<div
ref={slider}
className="flex overflow-x-scroll whitespace-nowrap scroll-smooth scrollbar-hide gap-5 pr-20"
style={{ scrollbarWidth: 'none', paddingLeft: "30px", paddingTop: "10px", paddingBottom: "10px", paddingRight: "50px" }}
className={`flex ${
wrap ? "flex-wrap" : "overflow-x-scroll whitespace-nowrap"
} items-center justify-between scroll-smooth scrollbar-hide gap-5 py-[10px] px=[30px] mx-[30px]`}
>
{items.map((item) => (
@@ -83,53 +94,11 @@ const ListRow: React.FC<ListRowProps> = ({
/>
))}
</div>
<ArrowRightIcon onClick={slideRight} size={20} className="absolute right-[10px] cursor-pointer" />
</div>
{children}
</div>
);
};
// Individual list entry component
export const ListItem: React.FC<ListItemProps> = ({
type,
title,
streamer,
streamCategory,
viewers,
thumbnail,
onItemClick,
}) => {
return (
<div className="relative pr-[3]">
<div
className="min-w-[430px] overflow-visible flex-shrink-0 flex flex-col bg-purple-900 rounded-lg
cursor-pointer hover:bg-pink-700 hover:scale-105 transition-all"
onClick={onItemClick}
>
<div className="relative w-full pt-[56.25%] overflow-hidden rounded-t-lg">
{thumbnail ? (
<img
src={thumbnail}
alt={title}
className="absolute top-0 left-0 w-full h-full object-cover"
/>
) : (
<div className="absolute top-0 left-0 w-full h-full bg-gray-600" />
)}
</div>
<div className="p-3">
<h3 className="font-semibold text-lg text-center">{title}</h3>
{type === "stream" && <p className="font-bold">{streamer}</p>}
{type === "stream" && (
<p className="text-sm text-gray-300">{streamCategory}</p>
)}
<p className="text-sm text-gray-300">{viewers} viewers</p>
</div>
</div>
</div>
);
};
export default ListRow;
export default ListRow;

View File

@@ -12,7 +12,7 @@ const themeIcons = {
const themes = ["light", "dark", "blue", "green", "orange"];
const Theme: React.FC = () => {
const ThemeSetting: React.FC = () => {
const { theme, setTheme } = useTheme();
const handleNextTheme = () => {
@@ -33,7 +33,7 @@ const Theme: React.FC = () => {
);
};
export default Theme;
export default ThemeSetting;
{/*
${isMode ?

View File

@@ -0,0 +1,21 @@
import { useEffect } from "react";
export function fetchContentOnScroll(callback: () => void, hasMoreData: boolean) {
useEffect(() => {
const handleScroll = () => {
if (!hasMoreData) return; // Don't trigger scroll if no more data
const scrollPosition = window.innerHeight + document.documentElement.scrollTop;
const scrollHeight = document.documentElement.scrollHeight;
if (scrollPosition >= scrollHeight * 0.9) {
callback(); // Trigger data fetching when 90% scroll is reached
}
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll); // Cleanup on unmount
};
}, [callback, hasMoreData]);
}

View File

@@ -0,0 +1,71 @@
import React, { useEffect } from "react";
import Navbar from "../components/Navigation/Navbar";
import { useNavigate } from "react-router-dom";
import ListRow from "../components/Layout/ListRow";
import { useCategories } from "../context/ContentContext";
const AllCategoriesPage: React.FC = () => {
const { categories, setCategories } = useCategories();
const navigate = useNavigate();
useEffect(() => {
const fetchCategories = async () => {
try {
const response = await fetch("/api/categories/popular/8/0");
if (!response.ok) {
throw new Error("Failed to fetch categories");
}
const data = await response.json();
// Transform the data to match CategoryItem interface
const processedCategories = data.map((category: any) => ({
type: "category" as const,
id: category.category_id,
title: category.category_name,
viewers: category.num_viewers,
thumbnail: `/images/thumbnails/categories/${category.category_name
.toLowerCase()
.replace(/ /g, "_")}.webp`,
}));
setCategories(processedCategories);
} catch (error) {
console.error("Error fetching categories:", error);
}
};
fetchCategories();
}, [setCategories]);
if (!categories.length) {
return (
<div className="h-screen w-screen flex items-center justify-center text-white">
Loading...
</div>
);
}
const handleCategoryClick = (categoryName: string) => {
console.log(categoryName);
navigate(`/category/${categoryName}`);
};
return (
<div
className="min-h-screen bg-gradient-radial from-[#ff00f1] via-[#0400ff] to-[#ff0000]"
style={{ backgroundImage: "url(/images/background-pattern.svg)" }}
>
<Navbar />
<ListRow
type="category"
title="All Categories"
items={categories}
onClick={handleCategoryClick}
extraClasses="text-center"
wrap={true}
/>
</div>
);
};
export default AllCategoriesPage;

View File

@@ -1,53 +0,0 @@
import React, { useState, useEffect } from "react";
import Navbar from "../components/Layout/Navbar";
import { useNavigate } from "react-router-dom";
const CategoriesPage: React.FC = () => {
const [noCategories, setNoCategories] = useState<number>(0);
const [moreCategories, setMoreCategories] = useState<number>(12);
const [isLoading, setIsLoading] = useState(true);
const navigate = useNavigate();
useEffect(() => {
const fetchCategories = async () => {
try {
const response = await fetch(`api/categories/popular/${moreCategories}`)
if (!response.ok) {
throw new Error("Failed to fetch categories");
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching categories:", error);
} finally {
setIsLoading(false);
}
};
fetchCategories();
}, [noCategories]);
if (isLoading) {
return (
<div className="h-screen w-screen flex items-center justify-center text-white">
Loading...
</div>
);
}
const handleCategoryClick = (category_name: string) => {
navigate(`/category${category_name}`);
};
return (
<div
className="min-h-screen bg-gradient-radial from-[#ff00f1] via-[#0400ff] to-[#ff0000]"
style={{ backgroundImage: "url(/images/background-pattern.svg)" }}
>
<Navbar />
<h1>Categories Page</h1>
</div>
);
};
export default CategoriesPage;

View File

@@ -1,6 +1,6 @@
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import Navbar from "../components/Layout/Navbar";
import Navbar from "../components/Navigation/Navbar";
import ListRow from "../components/Layout/ListRow";
import { useNavigate } from "react-router-dom";
@@ -78,6 +78,7 @@ const CategoryPage: React.FC = () => {
title={`${category_name} Streams`}
description={`Live streams in the ${category_name} category`}
items={streams}
wrap={true}
onClick={handleStreamClick}
extraClasses="bg-purple-950/60"
/>

View File

@@ -1,8 +1,9 @@
import React from "react";
import Navbar from "../components/Layout/Navbar";
import Navbar from "../components/Navigation/Navbar";
import ListRow from "../components/Layout/ListRow";
import { useNavigate } from "react-router-dom";
import { useStreams, useCategories } from "../context/ContentContext";
import Button from "../components/Input/Button";
interface HomePageProps {
variant?: "default" | "personalised";
@@ -33,7 +34,8 @@ const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
<ListRow
type="stream"
title={
"Streams - Live Now" + (variant === "personalised" ? " - Recommended" : "")
"Streams - Live Now" +
(variant === "personalised" ? " - Recommended" : "")
}
description={
variant === "personalised"
@@ -41,9 +43,14 @@ const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
: "Streamers that are currently live"
}
items={streams}
wrap={false}
onClick={handleStreamClick}
extraClasses="bg-red-950/60"
/>
>
<Button extraClasses="absolute right-10" onClick={() => navigate("/")}>
Show More . . .
</Button>
</ListRow>
{/* If Personalised_HomePage, display Categories the logged-in user follows. Else, trending categories. */}
<ListRow
@@ -59,9 +66,17 @@ const HomePage: React.FC<HomePageProps> = ({ variant = "default" }) => {
: "Categories that have been 'popping off' lately"
}
items={categories}
wrap={false}
onClick={handleCategoryClick}
extraClasses="bg-green-950/60"
/>
>
<Button
extraClasses="absolute right-10"
onClick={() => navigate("/categories")}
>
Show More . . .
</Button>
</ListRow>
</div>
);
};

Binary file not shown.

View File

@@ -1,10 +1,10 @@
-- Sample Data for users
INSERT INTO users (username, password, email, num_followers, stream_key, is_partnered, bio, is_live, current_stream_title, current_selected_category_id) VALUES
('GamerDude', 'password123', 'gamerdude@example.com', 500, '1234', 0, 'Streaming my gaming adventures!', 0, 'Epic Gaming Session', 1),
('GamerDude', 'password123', 'gamerdude@example.com', 500, '1234', 0, 'Streaming my gaming adventures!', 1, 'Game On!', 1),
('MusicLover', 'music4life', 'musiclover@example.com', 1200, '2345', 0, 'I share my favorite tunes.', 1, 'Live Music Jam', 2),
('ArtFan', 'artistic123', 'artfan@example.com', 300, '3456', 0, 'Exploring the world of art.', 1, 'Sketching Live', 3),
('EduGuru', 'learn123', 'eduguru@example.com', 800, '4567', 0, 'Teaching everything I know.', 1, 'Math Made Easy', 4),
('SportsStar', 'sports123', 'sportsstar@example.com', 2000, '5678', 0, 'Join me for live sports updates!', 0, 'Sports Highlights', 5);
('SportsStar', 'sports123', 'sportsstar@example.com', 2000, '5678', 0, 'Join me for live sports updates!', 1, 'Sports Highlights', 5);
INSERT INTO users (username, password, email, num_followers, stream_key, is_partnered, bio) VALUES
('GamerDude2', 'password123', 'gamerdude3@gmail.com', 3200, '7890', 0, 'Streaming my gaming adventures!'),
@@ -53,10 +53,12 @@ INSERT INTO categories (category_name) VALUES
('Sports');
-- Sample Data for streams
INSERT INTO streams (user_id, title, start_time, num_viewers, category_id) VALUES
INSERT INTO streams (user_id, title, start_time, num_viewers, category_id) VALUES
(1, 'Game on!', '2025-02-16 17:00:00', 5, 1),
(2, 'Live Music Jam', '2025-01-25 20:00:00', 350, 2),
(3, 'Sketching Live', '2025-01-24 15:00:00', 80, 3),
(4, 'Math Made Easy', '2025-01-23 10:00:00', 400, 4);
(4, 'Math Made Easy', '2025-01-23 10:00:00', 400, 4),
(5, 'Sports Highlights', '2025-02-15 23:00:00', 210, 5);
-- Sample Data for vods
INSERT INTO vods (user_id, title, datetime, category_id, length, views) VALUES
@@ -93,21 +95,6 @@ INSERT INTO chat (stream_id, chatter_id, message) VALUES
(1, 2, 'Woah, cannot believe that');
SELECT users.user_id, streams.title, streams.num_viewers, users.username
FROM streams JOIN users
ON streams.user_id = users.user_id
WHERE users.user_id IN
(SELECT followed_id FROM follows WHERE user_id = 1)
AND users.is_live = 1;
SELECT categories.category_id, categories.category_name, SUM(streams.num_viewers) AS total_viewers
FROM streams
JOIN categories ON streams.category_id = categories.category_id
GROUP BY categories.category_name
ORDER BY SUM(streams.num_viewers) DESC
LIMIT 10;
INSERT INTO follows (user_id, followed_id, since) VALUES
(7, 1, '2024-08-30'),
(7, 2, '2024-08-30'),
@@ -135,4 +122,18 @@ SELECT * FROM stream_tags;
-- To see all tables in the database
SELECT name FROM sqlite_master WHERE type='table';
UPDATE users SET is_live = 0 WHERE user_id = 1;
-- UPDATE users SET is_live = 0 WHERE user_id = 1;
SELECT users.user_id, streams.title, streams.num_viewers, users.username
FROM streams JOIN users
ON streams.user_id = users.user_id
WHERE users.user_id IN
(SELECT followed_id FROM follows WHERE user_id = 1)
AND users.is_live = 1;
SELECT categories.category_id, categories.category_name, SUM(streams.num_viewers) AS total_viewers
FROM streams
JOIN categories ON streams.category_id = categories.category_id
GROUP BY categories.category_name
ORDER BY SUM(streams.num_viewers) DESC
LIMIT 10;