import type { Route } from "../+types/root";
import { useState, useEffect, type FormEventHandler } from "react";
import RootLayout from "~/layout/RootLayout";
import { getTagColor } from "../utils/tags";
import type { Post } from "../types/post";
import Icon, { ICONS } from "../components/Icon";
import { API } from "../api/api";
import { useNavigate } from "react-router";
import type { PaginatedResponse } from "~/types/PaginatedResponse";
import Loading from "~/components/Loading";
interface PostCardProps {
post: Post;
onClick: (id: number) => void;
}
export function meta({}: Route.MetaArgs) {
return [
{ title: "ImgBoard - Posts" },
];
}
export default function Posts() {
const PostCard = ({ post, onClick }: PostCardProps) => (
onClick(post.id)}>
{post.title}
{post.tags.slice(0, 3).map(tag => (
{tag.name}
))}
{post.tags.length > 3 && ...}
);
const SearchBar = ({ currentQuery, onSearch }: { currentQuery: string, onSearch: (query: string) => void }) => {
const [query, setQuery] = useState(currentQuery);
const handleSearch: FormEventHandler = (e) => {
e.preventDefault();
onSearch(query);
};
return (
);
};
const GridView = ({ posts, onPostSelect }: { posts: Post[]; onPostSelect: (id: number) => void }) => (
);
const Pagination = ({
postsPerPage,
totalPosts,
paginate,
currentPage,
}: {
postsPerPage: number;
totalPosts: number;
paginate: (pageNumber: number) => void;
currentPage: number;
}) => {
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) { pageNumbers.push(i); }
if(pageNumbers.length <= 1) return null;
return (
);
};
const [paginatedData, setPaginatedData] = useState | null>(null);
const [currentPage, setCurrentPage] = useState(1);
const [searchQuery, setSearchQuery] = useState('');
const navigate = useNavigate();
useEffect(() => {
setCurrentPage(1);
}, [searchQuery])
useEffect(() => {
const fetchData = async () => {
const data = await API.fetchPosts(currentPage, searchQuery);
setPaginatedData(data);
}
fetchData();
}, [currentPage, searchQuery]);
const handleSearch = (query: string) => { setSearchQuery(query); setCurrentPage(1); };
const handlePostSelect = (id: number) => { navigate(`/posts/${id}`) };
const currentPosts = paginatedData?.items ?? [];
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
if (!paginatedData) {
return
;
}
return (
{paginatedData.items.length > 0 ?
<>
>
:
No Posts Found
Try adjusting your search to find what you're looking for.
}
);
}