Skip to content

Commit

Permalink
feat: focus search input on page load (#815)
Browse files Browse the repository at this point in the history
When a user opens [jsr.io](https://jsr.io), the page shows a big input
element which is used to search for packages. It appears to be the
primary call to action element and I believe by default, it should be
focused on page load because most of the times, a user would visit jsr
to search for a package.

This behaviour would also align with [google.com](https://google.com)
  • Loading branch information
vighnesh153 authored Jan 15, 2025
1 parent d880926 commit f80ff16
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
11 changes: 10 additions & 1 deletion frontend/islands/GlobalSearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { OramaPackageHit, SearchKind } from "../util.ts";
import { api, path } from "../utils/api.ts";
import type { List, Package, RuntimeCompat } from "../utils/api_types.ts";
import { PackageHit } from "../components/PackageHit.tsx";
import { useMacLike } from "../utils/os.ts";
import { useIsMobileDevice, useMacLike } from "../utils/os.ts";
import type { ListDisplayItem } from "../components/List.tsx";
import { RUNTIME_COMPAT_KEYS } from "../components/RuntimeCompatIndicator.tsx";

Expand Down Expand Up @@ -55,6 +55,7 @@ export function GlobalSearch(
isFocused.value && search.value.length > 0
);
const macLike = useMacLike();
const isMobileDevice = useIsMobileDevice();

const orama = useMemo(() => {
if (IS_BROWSER && indexId) {
Expand All @@ -65,6 +66,14 @@ export function GlobalSearch(
}
}, [indexId, apiKey]);

// focus the "search for packages" input box when the site loads
useEffect(() => {
if (location.pathname === "/" && !isMobileDevice) {
(document.querySelector("#global-search-input") as HTMLInputElement)
?.focus();
}
}, []);

useEffect(() => {
const outsideClick = (e: Event) => {
if (!ref.current) return;
Expand Down
7 changes: 7 additions & 0 deletions frontend/utils/os.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,10 @@ export function useMacLike(): boolean | undefined {
if (!IS_BROWSER) return undefined;
return !!navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i);
}

export function useIsMobileDevice(): boolean | undefined {
if (!IS_BROWSER) return undefined;
return !!navigator.userAgent.match(
/Android|webOS|iPhone|iPad|iPod|BlackBerry/i,
);
}

0 comments on commit f80ff16

Please sign in to comment.