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

FEAT: On pressing '/' switches user focus to searchbar #708

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 26 additions & 1 deletion packages/preview/src/components/@core/sidebar/index.tsx
@@ -1,7 +1,7 @@
import { ALL_ICONS } from "@utils/icon";
import { Context } from "@utils/search-context";
import { useRouter } from "next/router";
import React, { useState } from "react";
import React, { useEffect, useRef, useState } from "react";

import ActiveLink from "../active-link";
import Heading from "../heading";
Expand All @@ -13,6 +13,7 @@ export default function Sidebar() {
const router = useRouter();
const [isOpen, setIsOpen] = useState(false);
const [inputQuery, setInputQuery] = useState(null);
const searchRef = useRef<HTMLInputElement>(null);

const { query, setQuery, setResults } = React.useContext(Context);

Expand Down Expand Up @@ -40,6 +41,29 @@ export default function Sidebar() {
}
};

useEffect(() => {
const searchNode = searchRef.current;

const onKeyPress = (e: KeyboardEvent) => {
const activeElement = document.activeElement;

// To avoid switching focus when the user is typing in input fields
const isInputElement =
activeElement instanceof HTMLInputElement ||
activeElement instanceof HTMLTextAreaElement;

if (!isInputElement && e.key === "/") {
searchNode?.focus();
}
};

document.addEventListener("keyup", onKeyPress);

return () => {
document.removeEventListener("keyup", onKeyPress);
};
}, []);

return (
<div className="sidebar pt3">
<Heading isOpen={isOpen} setIsOpen={setIsOpen} />
Expand All @@ -53,6 +77,7 @@ export default function Sidebar() {
onFocus={goToSearch}
onBlur={onBlur}
onChange={onSearch}
ref={searchRef}
value={inputQuery !== null ? inputQuery : query}
autoComplete="off"
autoCorrect="off"
Expand Down