Skip to content

feat: search bar #62

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

Merged
merged 8 commits into from
Jun 4, 2025
Merged
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
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,17 @@ To connect to the database for development, you may optionally install the [Dies
Diesel is the Rust ORM used to create and run database migrations. It requires a separate C library called `libpq` to be installed as well.

```sh
# Mac only
# Mac
brew install libpq

# Ubuntu only
# or Ubuntu/Debian
apt-get install libpq5

# Install diesel CLI
cargo install diesel_cli --no-default-features --features postgres

# Install cargo-binstall
cargo install cargo-binstall

# On macOS-arm64, you may need additional rust flags:
RUSTFLAGS='-L /opt/homebrew/opt/libpq/lib' cargo install diesel_cli --no-default-features --features postgres
```
Expand Down
37 changes: 28 additions & 9 deletions app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
import React, { ReactNode, Suspense } from "react";
import { AppBar, Toolbar, Box, useTheme } from "@mui/material";
import UserButton from "./features/toolbar/components/UserButton";
import { useIsMobile } from "./features/toolbar/hooks/useIsMobile";
import SearchBar from "./features/toolbar/components/SearchBar";

interface AppProps {
children?: ReactNode;
}

function App({ children }: AppProps) {
const isMobile = useIsMobile();
const theme = useTheme();

return (
Expand All @@ -32,32 +30,53 @@ function App({ children }: AppProps) {
sx={{
backgroundColor: "#181818",
boxShadow: "0 2px 8px rgba(0, 0, 0, 0.3)",
padding: { xs: "8px 16px", sm: "6px 24px" },
gap: { xs: 1, sm: 2 },
flexWrap: { xs: "wrap", sm: "nowrap" },
alignItems: "center",
}}
>
<Box
onClick={() => (window.location.href = "/")}
sx={{
flexGrow: 1,
display: "block",
color: theme.palette.primary.main,
fontSize: "24px",
fontFamily: "monospace",
cursor: "pointer",
fontWeight: "bold",
transition: "color 0.2s ease-in-out",
flexShrink: 0,
order: { xs: 1, sm: 1 },
"&:hover": {
color: theme.palette.primary.light,
},
}}
>
forc.pub
</Box>
{!isMobile && <SearchBar />}
<Suspense fallback={<div>Loading...</div>}>
<UserButton />
</Suspense>
<Box
sx={{
flexGrow: 1,
order: { xs: 3, sm: 2 },
flexBasis: { xs: "100%", sm: "auto" },
}}
>
<Suspense fallback={<div></div>}>
<SearchBar />
</Suspense>
</Box>
<Box
sx={{
flexShrink: 0,
order: { xs: 2, sm: 3 },
marginLeft: { xs: "auto", sm: 0 },
}}
>
<Suspense fallback={<div>Loading...</div>}>
<UserButton />
</Suspense>
</Box>
</Toolbar>
{isMobile && <SearchBar />}
</AppBar>
<Box
component="main"
Expand Down
26 changes: 23 additions & 3 deletions app/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
"use client";

import { Suspense } from "react";
import { useSearchParams } from "next/navigation";
import App from "../App";
import PackageDashboard from "../features/dashboard/components/PackageDashboard";
import SearchResultsWrapper from "../pages/SearchResults";

function HomePage() {
const searchParams = useSearchParams();
const query = searchParams.get("query")?.trim();

export default function HomePage() {
return (
<App>
<div>
<h1>{"The Sway community's package registry"}</h1>
<PackageDashboard />
{query ? (
<SearchResultsWrapper />
) : (
<>
<h1>{"The Sway community's package registry"}</h1>
<PackageDashboard />
</>
)}
</div>
</App>
);
}

export default function HomePageWrapper() {
return (
<Suspense fallback={<div>Loading...</div>}>
<HomePage />
</Suspense>
);
}
15 changes: 0 additions & 15 deletions app/src/app/search/page.tsx

This file was deleted.

160 changes: 94 additions & 66 deletions app/src/features/toolbar/components/SearchBar.tsx
Original file line number Diff line number Diff line change
@@ -1,93 +1,121 @@
"use client";

import React, { Suspense, useCallback, useEffect } from "react";
import { usePathname } from "next/navigation";
import { useIsMobile } from "../hooks/useIsMobile";
import React, { useCallback, useState, useRef, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import InputAdornment from "@mui/material/InputAdornment";
import { styled, useTheme } from "@mui/material";
import { styled, useTheme, useMediaQuery } from "@mui/material";
import Input from "@mui/material/Input";
import SearchIcon from "@mui/icons-material/Search";
import dynamic from "next/dynamic";
import "./SearchBar.css";

function SearchBarComponent() {
const isMobile = useIsMobile();
const pathname = usePathname();
const StyledInput = styled(Input)(({ theme }) => ({
"& input::placeholder": {
color: theme.palette.text.secondary,
opacity: 1,
},
"& input": {
color: theme.palette.text.primary,
},
}));

function SearchBar() {
const router = useRouter();
const searchParams = useSearchParams();
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
const [searchValue, setSearchValue] = useState(
() => searchParams.get("query") || "",
);
const debounceTimeoutRef = useRef<NodeJS.Timeout>();

const updateURL = useCallback(
(value: string) => {
const trimmed = value.trim();
const url = trimmed
? `/?query=${encodeURIComponent(trimmed)}&page=1`
: "/";
router.replace(url, { scroll: false });
},
[router],
);

const debouncedUpdateURL = useCallback(
(value: string) => {
clearTimeout(debounceTimeoutRef.current);
debounceTimeoutRef.current = setTimeout(() => updateURL(value), 400);
},
[updateURL],
);

useEffect(() => {
const handlePopState = () => {
const params = new URLSearchParams(window.location.search);
const input = document.querySelector<HTMLInputElement>(
".search-input input",
);
if (input) {
input.value = params.get("q") || "";
}
};
const query = searchParams.get("query") || "";
setSearchValue(query);
}, [searchParams]);

window.addEventListener("popstate", handlePopState);
return () => window.removeEventListener("popstate", handlePopState);
useEffect(() => {
return () => clearTimeout(debounceTimeoutRef.current);
}, []);

// Create a styled version of Input with placeholder color override
const StyledInput = styled(Input)({
"& input::placeholder": {
color: theme.palette.text.secondary,
opacity: 1,
},
"& input": {
color: theme.palette.text.primary,
},
});

const handleChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
const params = new URLSearchParams(window.location.search);
setSearchValue(newValue);
debouncedUpdateURL(newValue);
},
[debouncedUpdateURL],
);

if (newValue) {
params.set("q", newValue);
const newUrl =
pathname === "/search"
? `${pathname}?${params.toString()}`
: `/search?${params.toString()}`;
window.history.pushState({ path: newUrl }, "", newUrl);
} else if (pathname === "/search") {
window.history.pushState({ path: "/" }, "", "/");
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Escape") {
setSearchValue("");
clearTimeout(debounceTimeoutRef.current);
updateURL("");
} else if (e.key === "Enter") {
clearTimeout(debounceTimeoutRef.current);
updateURL(searchValue);
}
},
[pathname],
[searchValue, updateURL],
);

return (
<div className={isMobile ? "search-container-mobile" : "search-container"}>
<Suspense key="search-bar" fallback={<div>Loading...</div>}>
<StyledInput
className="search-input"
placeholder="Search packages..."
fullWidth
disableUnderline
defaultValue={
new URLSearchParams(window.location.search).get("q") || ""
}
onChange={handleChange}
inputProps={{
"aria-label": "search",
}}
startAdornment={
<InputAdornment position="start">
<SearchIcon className="search-icon" />
</InputAdornment>
}
/>
</Suspense>
<div
className="search-container"
style={{
margin: 0,
width: "100%",
marginBottom: isMobile ? "0.25em" : "0",
}}
>
<StyledInput
className="search-input"
placeholder="Search packages..."
fullWidth
disableUnderline
value={searchValue}
onChange={handleChange}
onKeyDown={handleKeyDown}
sx={{
height: isMobile ? "2.5rem" : "auto",
"& input": {
height: isMobile ? "2.5rem" : "auto",
padding: isMobile ? "0.5rem 0.5rem" : "auto",
},
}}
inputProps={{
"aria-label": "search",
type: "search",
autoComplete: "off",
}}
startAdornment={
<InputAdornment position="start">
<SearchIcon className="search-icon" />
</InputAdornment>
}
/>
</div>
);
}

const SearchBar = dynamic(() => Promise.resolve(SearchBarComponent), {
ssr: false,
});

export default SearchBar;
Loading
Loading