Skip to content

Prevent menu list from auto-expanding on Tab key navigation #918

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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
114 changes: 73 additions & 41 deletions src/components/Nav/MainNavLinks.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import styles from "./styles.module.scss";
import { Logo } from "../Logo";
import { Icon } from "../Icon";
import { useEffect, useRef } from "preact/hooks";

type MainNavLinksProps = {
links: {
label: string;
url: string;
}[];
links: { label: string; url: string }[];
editorButtonLabel: string;
donateButtonLabel: string;
mobileMenuLabel: string;
Expand All @@ -26,7 +24,33 @@ export const MainNavLinks = ({
isOpen,
hasJumpTo,
}: MainNavLinksProps) => {
if (!links || links?.length <= 0) return null;
const menuRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);


useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Tab") {
requestAnimationFrame(() => {
const active = document.activeElement;
const isFocusOutside =
menuRef.current &&
buttonRef.current &&
!menuRef.current.contains(active as Node) &&
!buttonRef.current.contains(active as Node);

if (isOpen && isFocusOutside) {
handleToggle();
}
});
}
};

document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [isOpen, handleToggle]);

if (!links || links.length === 0) return null;

const renderLogo = () => (
<div class={styles.logo}>
Expand All @@ -43,20 +67,18 @@ export const MainNavLinks = ({
</a>

<button
ref={buttonRef}
class={styles.toggle}
onClick={handleToggle}
aria-expanded={isOpen}
aria-controls="main-menu-content"
aria-label={mobileMenuLabel || "Toggle navigation menu"}
>
<div class={styles.mobileMenuLabel}>
{isOpen ? (
<Icon kind="close" />
) : (
<>
<span>{mobileMenuLabel}</span>
<Icon kind="hamburger" />
</>
)}
{isOpen ? <Icon kind="close" /> : <>
<span>{mobileMenuLabel}</span>
<Icon kind="hamburger" />
</>}
</div>
<span class={styles.desktopMenuLabel}>
<Icon kind={isOpen ? "chevron-up" : "chevron-down"} />
Expand All @@ -67,36 +89,46 @@ export const MainNavLinks = ({

return (
<div
class={`${styles.mainlinks} ${isOpen && "open"} ${
!hasJumpTo && "noJumpTo"
}`}
ref={menuRef}
id="main-menu"
class={`${styles.mainlinks} ${isOpen ? "open" : "closed"} ${!hasJumpTo && "noJumpTo"}`}
>
{renderLogo()}
<ul>
{links.map((link) => (
<li key={link.label}>
<a href={link.url}>{link.label}</a>


<div id="main-menu-content" aria-hidden={!isOpen}>
<ul
style={{ display: isOpen ? "block" : "none" }}
>
{links.map((link) => (
<li key={link.label}>
<a href={link.url} tabIndex={isOpen ? 0 : -1}>{link.label}</a>
</li>
))}
</ul>

<ul
class="flex flex-col gap-[15px]"
style={{ display: isOpen ? "flex" : "none" }}
>
<li>
<a className={styles.buttonlink} href="https://editor.p5js.org" tabIndex={isOpen ? 0 : -1}>
<div class="mr-xxs">
<Icon kind="code-brackets" />
</div>
{editorButtonLabel}
</a>
</li>
))}
</ul>
<ul class="flex flex-col gap-[15px]">
<li>
<a className={styles.buttonlink} href="https://editor.p5js.org">
<div class="mr-xxs">
<Icon kind="code-brackets" />
</div>
{editorButtonLabel}
</a>
</li>
<li>
<a className={styles.buttonlink} href="/donate/">
<div class="mr-xxs">
<Icon kind="heart" />
</div>
{donateButtonLabel}
</a>
</li>
</ul>
<li>
<a className={styles.buttonlink} href="/donate/" tabIndex={isOpen ? 0 : -1}>
<div class="mr-xxs">
<Icon kind="heart" />
</div>
{donateButtonLabel}
</a>
</li>
</ul>
</div>
</div>
);
};
};
168 changes: 83 additions & 85 deletions src/components/SearchResults/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo, useRef, useState } from "preact/hooks";
import { useMemo, useRef, useState, useEffect } from "preact/hooks";
import { Icon } from "../Icon";

type SearchResult = {
Expand All @@ -23,46 +23,96 @@ const SearchResults = ({
uiTranslations,
}: SearchResultProps) => {
const inputRef = useRef<HTMLInputElement>(null);
const clearButtonRef = useRef<HTMLButtonElement>(null);
const submitButtonRef = useRef<HTMLButtonElement>(null);
const [currentFilter, setCurrentFilter] = useState("");
const [isInputEdited, setInputEdited] = useState(false);

useEffect(() => {
if (searchTerm && clearButtonRef.current) {
clearButtonRef.current.focus();
} else if (!searchTerm && inputRef.current) {
inputRef.current.focus();
}
}, [searchTerm]);

const allUniqueCategoriesForResults = useMemo(() => {
const categories = results.map((result) => result.category);
return [...new Set(categories)];
}, [results]);

const uniqueCategories = useMemo(() => {
if (currentFilter) {
return [currentFilter];
}
return allUniqueCategoriesForResults;
return currentFilter ? [currentFilter] : allUniqueCategoriesForResults;
}, [currentFilter, allUniqueCategoriesForResults]);

const uiTranslationKey = (category: string) => {
return (
category
// words in a category slugs are separated by dashes
.split("-")
.map((word) => {
// Capitalize the first letter of the word
return word.charAt(0).toUpperCase() + word.slice(1);
})
.join(" ")
);
};
const uiTranslationKey = (category: string) =>
category
.split("-")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");

const toggleFilter = (category: string) => {
if (currentFilter === category) {
setCurrentFilter("");
} else {
setCurrentFilter(category);
}
setCurrentFilter((prev) => (prev === category ? "" : category));
};

const clearInput = () => {
if (inputRef.current) inputRef.current.value = "";
setInputEdited(false);
onSearchChange("");
};

const submitInput = () => {
if (inputRef.current) onSearchChange(inputRef.current.value);
};

const renderBigSearchForm = () => (
<search
role="search"
class="bg-body-color relative flex h-[64px] w-full items-center rounded-[50px] border border-sidebar-type-color"
>
<input
id="search-term"
type="search"
ref={inputRef}
value={searchTerm}
placeholder={uiTranslations["Search"]}
onKeyDown={(e) => {
setInputEdited(true);
if (e.key === "Enter") {
e.preventDefault();
submitInput();
}
}}
class="h-fit w-full appearance-none bg-transparent px-md text-4xl placeholder-sidebar-type-color focus:outline-0"
aria-label="Search through site content"
required
/>
{isInputEdited ? (
<button
ref={submitButtonRef}
type="submit"
class="absolute right-0 top-[2px] px-[22px] py-[13px]"
onClick={submitInput}
aria-label="Submit search"
>
<Icon kind="arrow-lg" />
</button>
) : (
<button
ref={clearButtonRef}
type="reset"
class="absolute right-0 top-0 px-[22px] py-[13px]"
onClick={clearInput}
aria-label="Clear search input"
>
<Icon kind="close-lg" />
</button>
)}
</search>
);

const renderFilterByOptions = () => {
if (results.length === 0) {
return null;
}
if (results.length === 0) return null;

return (
<div className="flex w-fit py-lg">
Expand All @@ -71,7 +121,11 @@ const SearchResults = ({
{allUniqueCategoriesForResults.map((category) => (
<li
key={category}
className={`${currentFilter === category ? "bg-sidebar-type-color text-bg-color" : "bg-bg-color text-sidebar-type-color"} h-[25px] rounded-[20px] border border-sidebar-type-color px-xs py-[0.1rem] hover:bg-sidebar-type-color hover:text-bg-color md:h-[30px]`}
className={`${
currentFilter === category
? "bg-sidebar-type-color text-bg-color"
: "bg-bg-color text-sidebar-type-color"
} h-[25px] rounded-[20px] border border-sidebar-type-color px-xs py-[0.1rem] hover:bg-sidebar-type-color hover:text-bg-color md:h-[30px]`}
>
<button
value={category}
Expand All @@ -94,63 +148,6 @@ const SearchResults = ({
);
};

const clearInput = () => {
if (inputRef.current) {
inputRef.current.value = "";
}
};
const submitInput = () => {
if (inputRef.current) {
onSearchChange(inputRef.current.value);
}
};

const renderBigSearchForm = () => {
return (
<search
role="search"
class="bg-body-color relative flex h-[64px] w-full items-center rounded-[50px] border border-sidebar-type-color"
>
<input
id="search-term"
type="search"
ref={inputRef}
value={searchTerm}
placeholder={uiTranslations["Search"]}
onKeyDown={(e) => {
setInputEdited(true);
if (e.key === "Enter") {
e.preventDefault();
submitInput();
}
}}
class="h-fit w-full appearance-none bg-transparent px-md text-4xl placeholder-sidebar-type-color focus:outline-0"
aria-label="Search through site content"
required
/>
{isInputEdited ? (
<button
type="submit"
class="absolute right-0 top-[2px] px-[22px] py-[13px]"
onClick={submitInput}
aria-label="Submit search"
>
<Icon kind="arrow-lg" />
</button>
) : (
<button
type="reset"
class="absolute right-0 top-0 px-[22px] py-[13px]"
onClick={clearInput}
aria-label="Clear search input"
>
<Icon kind="close-lg" />
</button>
)}
</search>
);
};

const renderResults = () => {
if (results.length === 0) {
return (
Expand Down Expand Up @@ -181,13 +178,14 @@ const SearchResults = ({
return (
<div className="py-2xl md:py-3xl">
<div class="sticky top-0 bg-bg-color">
<p className="mt-0 pb-xs pt-md">{results.length} results found for</p>
<p className="mt-0 pb-xs pt-md">
{results.length} results found for
</p>
{renderBigSearchForm()}
</div>
<div className="no-scrollbar w-full overflow-x-scroll">
{renderFilterByOptions()}
</div>

{renderResults()}
</div>
);
Expand Down