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 basic search functionality #34

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

import { Routes, Route, BrowserRouter } from "react-router-dom";
Copy link
Collaborator

Choose a reason for hiding this comment

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

react-router-dom is not used anywhere in the project, it was just added in package.json. So I think, it will be better to use the latest version.

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'm not sure where you're seeing it being added to the package.json. react-router-dom was part of the initial commit.
If you wish to have the dependencies updated, I recommend making a new PR for it.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Can you update it in your PR ?

Copy link
Collaborator

@saminjay saminjay Dec 31, 2024

Choose a reason for hiding this comment

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

It was added in the initial commit, but its not being used anywhere. Its just there.
Since you are using it in this PR, you can just make it like its being added for the first time and update it to the latest version.

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>
</main>
<Footer />
<BrowserRouter>
<Header />
<Banner />
<main className="main">
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/search" element={<SearchPage />} />
</Routes>
</main>
<Footer />
</BrowserRouter>
</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;
49 changes: 47 additions & 2 deletions src/components/SearchInput.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,63 @@
import { SearchIcon } from "./Icons";
import { useState, useCallback } from "react";
import { useSearchParams, useNavigate, useLocation } from "react-router-dom";

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

const navigateToSearch = useCallback(
(query: string, isCompletedSearch = false) => {
const trimmedQuery = query.trim().toLowerCase();

if (!trimmedQuery) {
// Remove search params and navigate to home if query is empty
setSearchParams({});
navigate("/", { replace: true });
Copy link
Collaborator

Choose a reason for hiding this comment

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

This one shouldn't replace

return;
}

// Set the search params with the query
// Use replace: true for keypresses (when isCompletedSearch is false)
setSearchParams({ q: trimmedQuery }, { replace: !isCompletedSearch });

// Only navigate if we're not already on the search page
if (location.pathname !== "/search") {
navigate("/search", {
replace: isCompletedSearch || location.pathname === "/search",
Copy link
Collaborator

Choose a reason for hiding this comment

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

This one should always be false

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'll look at it next year, I've been going crazy for the past four hours trying to get this all to behave.

});
}
},
[navigate, location.pathname, setSearchParams]
);

return (
<div className="search-field">
<form
onSubmit={(e) => {
e.preventDefault();
navigateToSearch(searchValue, true);
}}
className="search-field"
>
<label htmlFor="search">
<SearchIcon />
</label>
<input
type="search"
id="search"
value={searchValue}
onChange={(e) => {
const newValue = e.target.value;
setSearchValue(newValue);
navigateToSearch(newValue, false);
}}
onBlur={() => navigateToSearch(searchValue, true)}
placeholder="Search here..."
autoComplete="off"
/>
</div>
</form>
);
};

Expand Down
25 changes: 14 additions & 11 deletions src/components/SnippetList.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
import { useState } from "react";
import { useState, useMemo } from "react";
import { SnippetType } from "../types";
import { useAppContext } from "../contexts/AppContext";
import { useSnippets } from "../hooks/useSnippets";

import SnippetModal from "./SnippetModal";
import { LeftAngleArrowIcon } from "./Icons";

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

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

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

const handleOpenModal = (activeSnippet: SnippetType) => {
setIsModalOpen(true);
Expand All @@ -31,7 +34,7 @@ const SnippetList = () => {
return (
<>
<ul role="list" className="snippets">
{fetchedSnippets.map((snippet, idx) => (
{filteredSnippets.map((snippet, idx) => (
<li key={idx}>
<button
className="snippet | flow"
Expand All @@ -41,8 +44,8 @@ const SnippetList = () => {
<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>
))}
Expand Down
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
25 changes: 19 additions & 6 deletions src/hooks/useSnippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,28 @@ type CategoryData = {
snippets: SnippetType[];
};

const getSnippetsFromData = (
data: CategoryData[] | null,
category: string
): SnippetType[] => {
if (!data?.length) {
return [];
}

if (category === "All snippets") {
return data.flatMap((item) => item.snippets);
}

const categoryData = data.find((item) => item.categoryName === category);
return categoryData?.snippets ?? [];
};

export const useSnippets = () => {
const { language, category } = useAppContext();
const { data, loading, error } = useFetch<CategoryData[]>(
`/data/${slugify(language.lang)}.json`
);
const endpoint = `/data/${slugify(language.lang)}.json`;
const { data, loading, error } = useFetch<CategoryData[]>(endpoint);

const fetchedSnippets = data
? data.find((item) => item.categoryName === category)?.snippets
: [];
const fetchedSnippets = getSnippetsFromData(data, category);

return { fetchedSnippets, loading, error };
};
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 SnippetList from "../components/SnippetList";
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>
<SnippetList query={query} />
</section>
</>
);
};

export default SearchPage;
15 changes: 15 additions & 0 deletions src/styles/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,21 @@ abbr {

.snippet__title {
color: var(--text-primary);
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
line-clamp: 1;
overflow: hidden;
text-overflow: "…";
}

.snippet__description {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
line-clamp: 1;
overflow: hidden;
text-overflow: "…";
}

/*------------------------------------*\
Expand Down