Skip to content

Commit

Permalink
search implementation for posts
Browse files Browse the repository at this point in the history
  • Loading branch information
MuruganandamVG committed Oct 6, 2024
1 parent 2c574cd commit 6bae709
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 15 deletions.
10 changes: 4 additions & 6 deletions app/[slug]/[board]/(main)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import React from "react";
import { getServerSession } from "next-auth";

import { authOptions } from "@/lib/auth";
Expand All @@ -11,6 +12,7 @@ import { CreatePost } from "@/components/posts/create";
import { Input } from "@/components/ui/input";
import { BoardOptions } from "@/components/boards/options";
import { Board } from "@/types/board";
import Search from "./search";

import PrivateBoard from "../../private";

Expand Down Expand Up @@ -53,13 +55,9 @@ export default async function BoardLayout({
</Badge>
</div>
<div className="flex flex-col items-start space-y-2 sm:flex-row sm:items-center sm:space-x-4 sm:space-y-0">
<Input
disabled
className="w-full sm:w-auto"
placeholder="Search Posts (Coming Soon)"
/>
<Search />
<BoardView />
<BoardOptions />
{hasAccess && <BoardOptions />}
{session ? (
<CreatePost
boardId={board.id as string}
Expand Down
4 changes: 2 additions & 2 deletions app/[slug]/[board]/(main)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,13 @@ export default async function BoardPage({
searchParams,
}: {
params: { board: string; slug: string };
searchParams: { view?: string };
searchParams: { view?: string; search: string };
}) {
const board = (await findBoardBySlug(params.board)) as
| (Board & { project: Project; projectId: string; id: string })
| null;
const session = await getServerSession(authOptions);
const view = searchParams.view || "list";

const hasAccess = await checkUserAccess({
userId: session?.user.id,
projectId: board?.projectId as string,
Expand All @@ -49,6 +48,7 @@ export default async function BoardPage({
return (
<PostsList
boardId={board.id}
searchKeyword={searchParams.search}
cols={2}
currentUserId={session?.user?.id as string}
hasAccess={hasAccess}
Expand Down
41 changes: 41 additions & 0 deletions app/[slug]/[board]/(main)/search.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"use client";
import React, { useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Input } from "@/components/ui/input";
import { debounce } from "@/utils/debounce";
const Search = () => {
const [searchQuery, setSearchQuery] = React.useState<string>();
const router = useRouter();
const searchParams = useSearchParams();
const SearchQueryUpdate = debounce((searchQuery) => {
const params = new URLSearchParams(searchParams);
if (searchQuery) {
params.set("search", searchQuery);
} else {
params.delete("search");
}
router.push(`?${params}`, { scroll: false });
}, 300);

// retrieving state from url, could be useful to share the filtered posts
useEffect(() => {
setSearchQuery(searchParams.get("search") || "");
}, []);

// calling filter upon change in search keyword
useEffect(() => {
SearchQueryUpdate(searchQuery);
}, [searchQuery]);
return (
<div>
<Input
className="w-full sm:w-auto"
placeholder="Search Postss"
onChange={(e) => setSearchQuery(e.target.value as string)}
value={searchQuery}
/>
</div>
);
};

export default Search;
1 change: 1 addition & 0 deletions components/posts/create.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export const CreatePostSheet = ({
onSuccess: () => {
toast.success("Feature Request Added");
queryClient.invalidateQueries({ queryKey: ["posts", boardId] });
form.reset();
setOpen(false);
},
onError: (error) => {
Expand Down
33 changes: 26 additions & 7 deletions components/posts/list.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"use client";

import React from "react";
import React, { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { BoardPostType, PostStatus } from "@prisma/client";
import { JsonValue } from "@prisma/client/runtime/library";
import { motion } from "framer-motion";
import Fuse from "fuse.js";

import Spinner from "@/components/common/spinner";

Expand All @@ -17,6 +18,7 @@ interface PostsListProps {
currentUserId: string;
cols?: number;
hasAccess: boolean;
searchKeyword: string;
}

interface Post {
Expand Down Expand Up @@ -53,7 +55,9 @@ export function PostsList({
currentUserId,
cols = 2,
hasAccess,
searchKeyword,
}: PostsListProps) {
const [isSearching, setIsSearching] = useState(false);
const { data, isLoading } = useQuery<{ posts: Post[] }>({
queryKey: ["posts", boardId],
queryFn: async () => {
Expand All @@ -67,18 +71,33 @@ export function PostsList({
},
});

if (isLoading) {
const posts = data?.posts || [];
const [filteredPosts, setFilteredPosts] = useState(posts);
useEffect(() => {
if (searchKeyword) {
setIsSearching(true);
const fuseOptions = {
keys: ["title", "description"],
};

const fuse = new Fuse(posts, fuseOptions);
const results = fuse.search(searchKeyword);
setIsSearching(false);
setFilteredPosts(results.map((result) => result.item));
} else {
setFilteredPosts(posts);
}
}, [searchKeyword, data]);
if (isLoading || isSearching) {
return (
<div className="flex h-64 items-center justify-center">
<Spinner />
</div>
);
}

const posts = data?.posts || [];

// Sort posts by createdAt in descending order
const sortedPosts = [...posts].sort(
const sortedPosts = [...filteredPosts].sort(
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
);

Expand Down Expand Up @@ -111,10 +130,10 @@ export function PostsList({
currentUserId={currentUserId}
hasAccess={hasAccess}
layout={view}
// @ts-ignore
// @ts-expect-error: will improve ts later
post={post}
postType={post.postType}
// @ts-ignore
// @ts-expect-error: will improve ts later
user={post.user!}
/>
</Link>
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"cmdk": "1.0.0",
"date-fns": "4.0.0-beta.1",
"framer-motion": "~11.1.1",
"fuse.js": "^7.0.0",
"geist": "^1.3.1",
"intl-messageformat": "^10.5.0",
"jsonwebtoken": "^9.0.2",
Expand Down

0 comments on commit 6bae709

Please sign in to comment.