From f80ff16edd7a9203fee805bb837f9e2df37fdb3f Mon Sep 17 00:00:00 2001 From: Vighnesh Raut Date: Wed, 15 Jan 2025 21:40:19 +0530 Subject: [PATCH] feat: focus search input on page load (#815) 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) --- frontend/islands/GlobalSearch.tsx | 11 ++++++++++- frontend/utils/os.ts | 7 +++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/frontend/islands/GlobalSearch.tsx b/frontend/islands/GlobalSearch.tsx index cc913edeb..cfbeed219 100644 --- a/frontend/islands/GlobalSearch.tsx +++ b/frontend/islands/GlobalSearch.tsx @@ -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"; @@ -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) { @@ -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; diff --git a/frontend/utils/os.ts b/frontend/utils/os.ts index eb8a1dd1e..792378a84 100644 --- a/frontend/utils/os.ts +++ b/frontend/utils/os.ts @@ -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, + ); +}