Skip to content
Open
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: 7 additions & 1 deletion frontend/components/Search/SearchBar.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import React, { useState } from "react";
import React, { useState, useRef } from "react";
import { Input, InputGroup, InputLeftElement } from "@chakra-ui/react";
import { Search2Icon } from "@chakra-ui/icons";
import { useSearchFocus } from "./useSearchFocus";

const SearchBar = ({
onChange,
placeholder = "Search by Class, Instructor, or Department",
autofocus = false,
}) => {
const [search, setSearch] = useState("");
const inputRef = useRef(null);

useSearchFocus(inputRef, autofocus);

const handleChange = (e) => {
setSearch(e.target.value);
Expand All @@ -19,6 +24,7 @@ const SearchBar = ({
<Search2Icon color={"black"} />
</InputLeftElement>
<Input
ref={inputRef}
type={"text"}
value={search}
onChange={handleChange}
Expand Down
54 changes: 54 additions & 0 deletions frontend/components/Search/useSearchFocus.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { useEffect } from "react";
import { useToast } from "@chakra-ui/react";

export const useSearchFocus = (inputRef, autofocus = false) => {
const toast = useToast();
useEffect(() => {
if (autofocus) {
inputRef.current?.focus();
}
}, [autofocus, inputRef]);

useEffect(() => {
let toastShown = false;
const handleKeyDown = (e) => {
if (e.metaKey || e.ctrlKey || e.altKey) return;

const active = document.activeElement;
const isTyping =
active &&
(active.tagName === "INPUT" ||
active.tagName === "TEXTAREA" ||
active.isContentEditable);
if (isTyping) return;

if (e.key === "/") {
e.preventDefault();
inputRef.current?.focus();
return;
}

const isAlphanumeric = e.key.length === 1 && /[a-zA-Z0-9]/.test(e.key);
if (isAlphanumeric && !toastShown) {
toastShown = true;

toast({
title: 'Press "/" to search',
status: "info",
duration: 5000,
variant: "subtle",
isClosable: true,
position: "bottom-right",
containerStyle: {
color: "#3182ce",
},
});
}
};

window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [inputRef, toast]);
};
1 change: 1 addition & 0 deletions frontend/pages/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ const Home = () => {
<SearchBar
placeholder={search || undefined}
onChange={handleChange}
autofocus
/>
</Box>
<Collapse in={showPage} animateOpacity>
Expand Down