Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add feature to search with Ctrl + k #1205

Merged
merged 8 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
/.pnp
.pnp.js
.yarn/install-state.gz
bun.lockb

# docker volume
/postgres-data/
Expand Down
10 changes: 6 additions & 4 deletions src/app/(main)/(pages)/home/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { MyCourses } from '@/components/MyCourses';
import { Redirect } from '@/components/Redirect';
import SearchBar from '@/components/search/SearchBar';
import { SearchBar } from '@/components/search/SearchBar';
import { getServerSession } from 'next-auth';

export default async function MyCoursesPage() {
Expand All @@ -23,11 +23,13 @@ export default async function MyCoursesPage() {

return (
<main className="flex flex-col gap-4 pb-16 pt-8">
<div className="flex flex-col justify-between gap-4 lg:flex-row">
<h1 className="text-wrap text-3xl font-extrabold capitalize tracking-tighter md:text-4xl">
<div className="flex flex-col justify-between gap-4 md:flex-row">
<h1 className="text-wrap text-center text-3xl font-extrabold capitalize tracking-tighter md:text-start md:text-4xl">
{greeting} {session.user.name}
</h1>
<SearchBar />
<div>
<SearchBar />
</div>
</div>

<div className="flex h-full flex-col gap-4 rounded-2xl py-4">
Expand Down
2 changes: 1 addition & 1 deletion src/components/NewPostDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const NewPostDialog = () => {
const { theme } = useTheme();
const formRef = useRef<ElementRef<'form'>>(null);
const searchParam = useSearchParams();
const paramsObject = searchParamsToObject(searchParam);
const paramsObject = searchParamsToObject(searchParam as any); // build fix (eslint)
const path = usePathname();
const router = useRouter();
const [value, setValue] = useState<string>('**Hello world!!!**');
Expand Down
2 changes: 1 addition & 1 deletion src/components/Pagination.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ interface IPagination {
const Pagination: React.FC<IPagination> = ({ dataLength = 1 }) => {
const searchParams = useSearchParams();
const path = usePathname();
const paramsObj = searchParamsToObject(searchParams);
const paramsObj = searchParamsToObject(searchParams as any); // build fix (eslint)
const paginationQ = paginationData(paramsObj);
return (
<div className="flex items-center justify-center space-x-4">
Expand Down
2 changes: 1 addition & 1 deletion src/components/comment/Comments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ const Comments = async ({
<span>
{searchParams.type === CommentType.INTRO
? CommentType.INTRO
: 'All comments' || 'All comments'}
: 'All comments'}
</span>
<ChevronDownIcon className="h-4 w-4" />
</Button>
Expand Down
2 changes: 1 addition & 1 deletion src/components/search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const Search = () => {
const searchParams = useSearchParams();
const [search, setSearch] = useState('');
const path = usePathname();
const paramsObj = searchParamsToObject(searchParams);
const paramsObj = searchParamsToObject(searchParams as any); // build fix (eslint)

const handleSearch = () => {
router.push(getUpdatedUrl(path, paramsObj, { search }));
Expand Down
26 changes: 0 additions & 26 deletions src/components/search/MobileScreenSearch.tsx

This file was deleted.

162 changes: 88 additions & 74 deletions src/components/search/SearchBar.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,26 @@
'use client';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Input } from '@/components/ui/input';
import { SearchIcon, X } from 'lucide-react';
import React, { useCallback, useEffect, useState } from 'react';
import { TSearchedVideos } from '@/app/api/search/route';
import { useRouter } from 'next/navigation';
import useClickOutside from '@/hooks/useClickOutside';
import VideoSearchCard from './VideoSearchCard';
import VideoSearchInfo from './VideoSearchInfo';
import { toast } from 'sonner';
import VideoSearchLoading from './VideoSearchLoading';
import {
Command,
CommandDialog,
CommandInput,
CommandList,
} from '../ui/command';

const SearchBar = ({ onCardClick }: { onCardClick?: () => void }) => {
export function SearchBar() {
const [searchTerm, setSearchTerm] = useState('');
const [searchedVideos, setSearchedVideos] = useState<
TSearchedVideos[] | null
>(null);
const [isInputFocused, setIsInputFocused] = useState<boolean>(false);
const [searchedVideos, setSearchedVideos] = useState<TSearchedVideos[]>([]);
const [loading, setLoading] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(-1);
const router = useRouter();

const ref = useRef<HTMLDivElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);

useClickOutside(ref, () => {
setIsInputFocused(false);
});

const fetchData = useCallback(async (searchTerm: string) => {
setLoading(true);
try {
Expand All @@ -48,31 +43,54 @@ const SearchBar = ({ onCardClick }: { onCardClick?: () => void }) => {

return () => clearTimeout(timeoutId);
}
setSearchedVideos(null);
setSearchedVideos([]);
}, [searchTerm, fetchData]);

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSearchTerm(event.target.value);
};

const clearSearchTerm = () => {
setSearchTerm('');
};

const handleCardClick = (videoUrl: string) => {
if (onCardClick !== undefined) {
onCardClick();
}
clearSearchTerm();
router.push(videoUrl);
};
useEffect(() => {
const handleKeyPress = (event: KeyboardEvent) => {
switch (event.code) {
case 'KeyK':
if (event.ctrlKey) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are just checking with ctrl key but as the name suggests it should also support ⌘K on mac

devsargam marked this conversation as resolved.
Show resolved Hide resolved
event.preventDefault();
setDialogOpen((prev) => !prev);
}
break;
case 'ArrowDown':
event.preventDefault();
setSelectedIndex(
(prevIndex) => (prevIndex + 1) % searchedVideos.length,
);
break;
case 'ArrowUp':
event.preventDefault();
setSelectedIndex(
(prevIndex) =>
(prevIndex - 1 + searchedVideos.length) % searchedVideos.length,
);
break;
case 'Enter':
if (selectedIndex !== -1) {
event.preventDefault();
const {
id: videoId,
parentId,
parent,
} = searchedVideos[selectedIndex];

const handleClearInput = () => {
clearSearchTerm();
if (searchInputRef.current) {
searchInputRef.current.focus();
}
};
if (parentId && parent?.courses.length) {
const courseId = parent.courses[0].courseId;
const videoUrl = `/courses/${courseId}/${parentId}/${videoId}`;
router.push(videoUrl);
}
}
break;
default:
break;
}
};
window.addEventListener('keydown', handleKeyPress);
return () => window.removeEventListener('keydown', handleKeyPress);
}, [searchedVideos, selectedIndex]);

const renderSearchResults = () => {
if (searchTerm.length < 3) {
Expand All @@ -84,45 +102,41 @@ const SearchBar = ({ onCardClick }: { onCardClick?: () => void }) => {
} else if (!searchedVideos || searchedVideos.length === 0) {
return <VideoSearchInfo text="No videos found" />;
}
return searchedVideos.map((video) => (
<VideoSearchCard
key={video.id}
video={video}
onCardClick={handleCardClick}
/>
return searchedVideos.map((video, index) => (
<div
className={` ${index === selectedIndex && 'bg-blue-600/10 text-blue-600'}`}
>
<VideoSearchCard key={video.id} video={video} />
</div>
));
};

return (
<div
className="relative flex h-10 w-full items-center lg:w-[32vw]"
ref={ref}
>
{/* Search Input Bar */}
<SearchIcon className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-primary/80" />
<Input
placeholder="Search for videos..."
className="focus:ring-none rounded-lg border-none bg-primary/5 px-10 text-base focus:outline-none"
value={searchTerm}
onChange={handleInputChange}
onFocus={() => setIsInputFocused(true)}
ref={searchInputRef}
/>
{searchTerm.length > 0 && (
<X
className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 transform cursor-pointer"
onClick={handleClearInput}
/>
)}

{/* Search Results */}
{isInputFocused && searchTerm.length > 0 && (
<div className="absolute top-12 z-30 max-h-[40vh] w-full overflow-y-auto rounded-lg border-2 bg-background p-2 shadow-lg">
{renderSearchResults()}
<>
<Command onClick={() => setDialogOpen(true)}>
<div className="flex items-center justify-between border-2">
<CommandInput
placeholder="Search video..."
value={searchTerm}
onValueChange={(search) => setSearchTerm(search)}
/>
<kbd className="m-1 rounded-sm bg-white/15 p-1.5 text-xs leading-3">
Ctrl K
</kbd>
</div>
)}
</div>
<CommandList></CommandList>
</Command>
<CommandDialog
open={dialogOpen}
onOpenChange={() => setDialogOpen((prev) => !prev)}
>
<CommandInput
placeholder="Search video..."
value={searchTerm}
onValueChange={(search) => setSearchTerm(search)}
/>
<CommandList>{renderSearchResults()}</CommandList>
</CommandDialog>
</>
);
};

export default SearchBar;
}
18 changes: 6 additions & 12 deletions src/components/search/VideoSearchCard.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,23 @@
import { TSearchedVideos } from '@/app/api/search/route';
import { Play } from 'lucide-react';
import Link from 'next/link';
import React from 'react';

const VideoSearchCard = ({
video,
onCardClick,
}: {
video: TSearchedVideos;
onCardClick: (videoUrl: string) => void;
}) => {
const VideoSearchCard = ({ video }: { video: TSearchedVideos }) => {
const { id: videoId, parentId, parent } = video;

if (parentId && parent) {
if (parentId && parent?.courses.length) {
const courseId = parent.courses[0].courseId;
const videoUrl = `/courses/${courseId}/${parentId}/${videoId}`;
return (
<div
<Link
href={videoUrl}
className="flex cursor-pointer items-center gap-3 rounded-md px-3 py-2 hover:bg-blue-600/10 hover:text-blue-600"
onClick={() => onCardClick(videoUrl)}
>
<Play className="size-4" />
<span className="w-4/5 truncate font-medium capitalize">
{video.title}
</span>
</div>
</Link>
);
}
};
Expand Down
Loading