Skip to content

Add basic search functionality #34

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

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
21 changes: 7 additions & 14 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
import { useAppContext } from "./contexts/AppContext";

import { Routes, Route } from "react-router-dom";
import Header from "./layouts/Header";
import Banner from "./layouts/Banner";
import Sidebar from "./layouts/Sidebar";
import Footer from "./layouts/Footer";

import SnippetList from "./components/SnippetList";
import HomePage from "./pages/HomePage.tsx";
import SearchPage from "./pages/SearchPage.tsx";

const App = () => {
const { category } = useAppContext();

return (
<div className="container flow">
<Header />
<Banner />
<main className="main">
<Sidebar />
<section className="flow">
<h2 className="section-title">
{category ? category : "Select a category"}
</h2>
<SnippetList />
</section>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/search" element={<SearchPage />} />
</Routes>
</main>
<Footer />
</div>
Expand Down
22 changes: 22 additions & 0 deletions src/components/SearchFilters.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useCategories } from "../hooks/useCategories";
import { useAppContext } from "../contexts/AppContext";

const SearchFilters = () => {
const { category, setCategory } = useAppContext();
const { fetchedCategories } = useCategories();

return (
<div className="search-filters">
<select value={category} onChange={(e) => setCategory(e.target.value)}>
<option value="">All Categories</option>
{fetchedCategories.map((cat, idx) => (
<option key={idx} value={cat}>
{cat}
</option>
))}
</select>
</div>
);
};

export default SearchFilters;
39 changes: 39 additions & 0 deletions src/components/SearchInput.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,31 @@
import { SearchIcon } from "./Icons";
import { useState, useCallback } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";

const SearchInput = () => {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const [searchValue, setSearchValue] = useState(searchParams.get("q") || "");

const debouncedSearch = useCallback(
debounce((query: string) => {
if (query) {
setSearchParams({ q: query });
navigate(`/search?q=${encodeURIComponent(query.trim().toLowerCase())}`);
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't think navigating urls every debounced request is a good thing. I know it is debounced but still sometimes people pause to think while searching, and it will clutter the history.

You can maybe search on Enter, or show results while typing but navigate the URL on Enter or onBlur

Copy link
Collaborator

Choose a reason for hiding this comment

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

It's an SPA so it doesn't "refresh" the page, but yeah it will clutter the history, what you can do is use the replace feature of navigate here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think on Enter and onBlur is a great idea! I'll look into it.

} else {
setSearchParams({});
navigate("/");
}
}, 200),
[setSearchParams, navigate]
);

const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setSearchValue(value);
debouncedSearch(value);
};

return (
<div className="search-field">
<label htmlFor="search">
Expand All @@ -9,11 +34,25 @@ const SearchInput = () => {
<input
type="search"
id="search"
value={searchValue}
onChange={handleSearch}
placeholder="Search here..."
autoComplete="off"
/>
</div>
);
};

// Debounce utility function
function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let timeout: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
}

export default SearchInput;
64 changes: 64 additions & 0 deletions src/components/SearchSnippetList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { useState, useMemo } from "react";
import { SnippetType } from "../types";
import { useAppContext } from "../contexts/AppContext";
import { useSnippets } from "../hooks/useSnippets";
import SnippetModal from "./SnippetModal";

const SearchSnippetList = ({ query }: { query: string | null }) => {
const { language, snippet, setSnippet } = useAppContext();
const { fetchedSnippets, loading } = useSnippets();
const [isModalOpen, setIsModalOpen] = useState(false);

const filteredSnippets = useMemo(() => {
if (!query) return [];
return fetchedSnippets.filter((snippet) =>
snippet.title.toLowerCase().includes(query.toLowerCase())
);
}, [fetchedSnippets, query]);

const handleOpenModal = (activeSnippet: SnippetType) => {
setIsModalOpen(true);
setSnippet(activeSnippet);
};

const handleCloseModal = () => {
setIsModalOpen(false);
setSnippet(null);
};

if (loading) return <div>Searching...</div>;
if (filteredSnippets.length === 0)
return <div>No results found for "{query}"</div>;

return (
<>
<ul role="list" className="snippets">
{filteredSnippets.map((snippet, idx) => (
<li key={idx}>
<button
className="snippet | flow"
data-flow-space="sm"
onClick={() => handleOpenModal(snippet)}
>
<div className="snippet__preview">
<img src={language.icon} alt={language.lang} />
</div>
<h3 className="snippet__title">{snippet.title}</h3>
<p className="snippet__description">{snippet.description}</p>
</button>
</li>
))}
</ul>

{isModalOpen && snippet && (
<SnippetModal
snippet={snippet}
handleCloseModal={handleCloseModal}
language={language.lang}
/>
)}
</>
);
};

export default SearchSnippetList;
3 changes: 2 additions & 1 deletion src/hooks/useCategories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ export const useCategories = () => {
);

const fetchedCategories = useMemo(() => {
return data ? data.map((item) => item.categoryName) : [];
const categories = data ? data.map((item) => item.categoryName) : [];
return ["All snippets", ...categories];
}, [data]);

return { fetchedCategories, loading, error };
Expand Down
6 changes: 4 additions & 2 deletions src/hooks/useSnippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ export const useSnippets = () => {
`/data/${slugify(language.lang)}.json`
);

const fetchedSnippets = data
? data.find((item) => item.categoryName === category)?.snippets
const fetchedSnippets: SnippetType[] = data
Copy link
Collaborator

Choose a reason for hiding this comment

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

instead of adding nested ternary operator, it would be better to populate it through a function.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I did the thing 🫡

? category === "All snippets"
? data.flatMap((item) => item.snippets)
: (data.find((item) => item.categoryName === category)?.snippets ?? [])
: [];

return { fetchedSnippets, loading, error };
Expand Down
9 changes: 6 additions & 3 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import { createRoot } from "react-dom/client";
import "./styles/main.css";
import App from "./App";
import { AppProvider } from "./contexts/AppContext";
import { BrowserRouter } from "react-router-dom";

createRoot(document.getElementById("root")!).render(
<StrictMode>
<AppProvider>
<App />
</AppProvider>
<BrowserRouter>
<AppProvider>
<App />
</AppProvider>
</BrowserRouter>
</StrictMode>
);
21 changes: 21 additions & 0 deletions src/pages/HomePage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useAppContext } from "../contexts/AppContext";
import SnippetList from "../components/SnippetList";
import Sidebar from "../layouts/Sidebar";

const HomePage = () => {
const { category } = useAppContext();

return (
<>
<Sidebar />
<section className="flow">
<h2 className="section-title">
{category ? category : "Select a category"}
</h2>
<SnippetList />
</section>
</>
);
};

export default HomePage;
20 changes: 20 additions & 0 deletions src/pages/SearchPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { useSearchParams } from "react-router-dom";
import SearchSnippetList from "../components/SearchSnippetList";
import Sidebar from "../layouts/Sidebar";

const SearchPage = () => {
const [searchParams] = useSearchParams();
const query = searchParams.get("q");

return (
<>
<Sidebar />
<section className="flow">
<h2 className="section-title">Search Results for: {query}</h2>
<SearchSnippetList query={query} />
</section>
</>
);
};

export default SearchPage;