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 a search component #38

Closed
wants to merge 2 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
5 changes: 5 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"tasks": {
"launch": "yarn start"
}
}
3 changes: 2 additions & 1 deletion src/components/header.astro
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Icon } from "astro-icon/components";
import { NavigationLinks, Logo } from "../config";
import Theme from "../components/theme.astro";
import Img from "../components/img.astro";
import Search from "../components/search.astro";
---

<div class="relative h-16 w-full">
Expand Down Expand Up @@ -72,7 +73,7 @@ import Img from "../components/img.astro";
class="absolute inset-y-0 right-0 flex items-center pr-2 sm:static sm:inset-auto sm:ml-6 sm:pr-0"
>
<Theme />

<Search />
<!-- Right nav -->
</div>
</div>
Expand Down
2 changes: 2 additions & 0 deletions src/components/leftsidebar.astro
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
import { SIDEBAR } from "../config";
import Search from "../components/search.astro";

type Props = {
currentPage: string;
Expand All @@ -12,6 +13,7 @@ const currentPageMatch = currentPage.slice(1);
<div
class="hidden lg:sticky lg:top-16 lg:-ml-6 lg:block lg:h-[calc(100vh-4rem)] lg:flex-none lg:overflow-y-auto lg:py-16 lg:pl-6 bg-purple-50 dark:bg-gray-800"
>
<Search />
<nav
aria-labelledby="grid-left"
class="text-base lg:text-sm w-64 pr-8 xl:w-72 xl:pr-16"
Expand Down
2 changes: 2 additions & 0 deletions src/components/rightsidebar.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
---
import TableOfContents from "./tableofcontents.astro";
import MoreMenu from "./moremenu.astro";
import Search from "../components/search.astro";
import type { MarkdownHeading } from "astro";

type Props = {
Expand All @@ -16,6 +17,7 @@ const { headings, githubEditUrl } = Astro.props as Props;
>
<nav aria-labelledby="on-this-page-title" class="w-56">
<div>
<Search />
<TableOfContents headings={headings} />
<MoreMenu editHref={githubEditUrl} />
</div>
Expand Down
60 changes: 60 additions & 0 deletions src/components/search.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
---
import { useState, useEffect } from 'react';
import lunr from 'lunr';

const Search = () => {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const [index, setIndex] = useState(null);

useEffect(() => {
const fetchData = async () => {
const response = await fetch('/search-index.json');
const data = await response.json();
const idx = lunr(function () {
this.ref('id');
this.field('title');
this.field('content');

data.forEach((doc) => {
this.add(doc);
});
});
setIndex(idx);
};

fetchData();
}, []);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure error handling around fetching search data.
If the JSON file fails to load, it might break the search. Add try/catch or handle a non-200 response from the fetch for better resiliency.

 useEffect(() => {
   const fetchData = async () => {
     try {
       const response = await fetch('/search-index.json');
+      if (!response.ok) {
+        console.error("Failed to fetch search index:", response.statusText);
+        return;
+      }
       const data = await response.json();
       // ...
     } catch (error) {
+      console.error("Error fetching search index:", error);
     }
   };
   fetchData();
 }, []);

Committable suggestion skipped: line range outside the PR's diff.


const handleSearch = (event) => {
const query = event.target.value;
setQuery(query);

if (index) {
const results = index.search(query).map(({ ref }) => {
return data.find((doc) => doc.id === ref);
});
setResults(results);
}
};

return (
<div>
<input
type="text"
value={query}
onChange={handleSearch}
placeholder="Search..."
/>
<ul>
{results.map((result) => (
<li key={result.id}>
<a href={result.url}>{result.title}</a>
</li>
))}
</ul>
</div>
);
};

export default Search;
Loading