Skip to content

Full Toolkit for Next-Level Domain Analysis

Display search suggestions from BigQuery 👀

Felix Wotschofsky2420967a74a1
diff --git a/app/api/search-suggestions/route.ts b/app/api/search-suggestions/route.ts
new file mode 100644
index 0000000..3f6e8e6
--- /dev/null
+++ b/app/api/search-suggestions/route.ts
@@ -0,0 +1,46 @@
+import { NextResponse } from 'next/server';
+
+import bigquery from '@/lib/bigquery';
+
+export const runtime = 'edge';
+export const preferredRegion = 'home';
+
+export const GET = async (request: Request) => {
+ const { searchParams } = new URL(request.url);
+ const query = searchParams.get('q');
+
+ if (!query) {
+ return new Response('Missing query', {
+ status: 400,
+ });
+ }
+
+ if (query.includes('%')) {
+ return new Response('Invalid query', {
+ status: 400,
+ });
+ }
+
+ if (!bigquery) {
+ return NextResponse.json([]);
+ }
+
+ const tableName = `\`${bigquery.projectId}.${process.env.BIGQUERY_DATASET}.lookups\``;
+ const results = await bigquery.query({
+ query: `
+ SELECT baseDomain
+ FROM ${tableName}
+ WHERE baseDomain LIKE @query
+ GROUP BY baseDomain
+ ORDER BY COUNT(*) ASC
+ LIMIT 5
+ `,
+ params: {
+ query: `${query}%`,
+ },
+ });
+
+ const suggestions = results.map((row: any) => row.baseDomain) as string[];
+
+ return NextResponse.json(suggestions);
+};
diff --git a/components/general/SearchForm.tsx b/components/general/SearchForm.tsx
index de1f1e4..848f454 100644
--- a/components/general/SearchForm.tsx
+++ b/components/general/SearchForm.tsx
@@ -1,17 +1,52 @@
'use client';
+import { useDebounce } from '@uidotdev/usehooks';
import { Loader2 } from 'lucide-react';
import { usePlausible } from 'next-plausible';
import { usePathname, useRouter } from 'next/navigation';
import { toASCII } from 'punycode';
-import { ChangeEvent, FormEvent, useEffect, useRef, useState } from 'react';
+import {
+ ChangeEvent,
+ FormEvent,
+ KeyboardEventHandler,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
+import useSWR from 'swr';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { cn, isAppleDevice, isValidDomain } from '@/lib/utils';
+const normalizeDomain = (input: string) => {
+ let tDomain;
+ try {
+ tDomain = new URL(input.trim().toLowerCase()).hostname;
+ } catch (err) {
+ tDomain = input.trim().toLowerCase();
+ }
+
+ let normalizedDomain = tDomain.endsWith('.') ? tDomain.slice(0, -1) : tDomain;
+ return toASCII(normalizedDomain);
+};
+
+const useSuggestions = (domain: string) => {
+ const debouncedDomain = useDebounce(domain, 200);
+
+ const { data: suggestions } = useSWR<string[]>(
+ domain
+ ? `/api/search-suggestions?q=${encodeURIComponent(debouncedDomain)}`
+ : null,
+ { keepPreviousData: true }
+ );
+
+ return { suggestions };
+};
+
enum FormStates {
Initial,
Submitting,
@@ -30,9 +65,10 @@ const SearchForm = (props: SearchFormProps) => {
const router = useRouter();
const pathname = usePathname();
- const [domain, setDomain] = useState('');
+ const [domain, setDomain] = useState(props.initialValue ?? '');
const [state, setState] = useState<FormStates>(FormStates.Initial);
const [error, setError] = useState(false);
+ const [suggestionsVisible, setSuggestionsVisible] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
useHotkeys(
@@ -45,56 +81,120 @@ const SearchForm = (props: SearchFormProps) => {
[inputRef.current]
);
+ const redirectUser = useCallback(
+ (domain: string) => {
+ setState(FormStates.Submitting);
+
+ const target = `/lookup/${domain}`;
+
+ if (pathname === target) {
+ router.refresh();
+ setTimeout(() => {
+ setState(FormStates.Initial);
+ }, 150);
+ return;
+ }
+
+ router.push(target);
+ },
+ [setState, router, pathname]
+ );
+
+ const handleSubmit = useCallback(
+ (event: FormEvent) => {
+ event.preventDefault();
+
+ const normalizedDomain = normalizeDomain(domain);
+ if (!isValidDomain(normalizedDomain)) {
+ setError(true);
+ return;
+ }
+
+ setError(false);
+ redirectUser(normalizedDomain);
+
+ plausible('Search Form: Submit', {
+ props: { domain: normalizedDomain },
+ });
+ },
+ [setError, domain, redirectUser, plausible]
+ );
+
+ const { suggestions } = useSuggestions(domain);
+ const [selectedSuggestion, setSelectedSuggestion] = useState<number | null>(
+ null
+ );
useEffect(() => {
- if (props.initialValue) {
- setDomain(props.initialValue);
- }
- }, [props.initialValue]);
-
- const handleSubmit = (event: FormEvent) => {
- event.preventDefault();
- setError(false);
- setState(FormStates.Submitting);
-
- let tDomain;
- try {
- tDomain = new URL(domain.trim().toLowerCase()).hostname;
- } catch (err) {
- tDomain = domain.trim().toLowerCase();
- }
-
- let normalizedDomain = tDomain.endsWith('.')
- ? tDomain.slice(0, -1)
- : tDomain;
- normalizedDomain = toASCII(normalizedDomain);
-
- if (!isValidDomain(normalizedDomain)) {
- setError(true);
- setState(FormStates.Initial);
- return;
- }
-
- const target = `/lookup/${normalizedDomain}`;
-
- if (pathname === target) {
- router.refresh();
- setTimeout(() => {
- setState(FormStates.Initial);
- }, 150);
- return;
- }
-
- router.push(target);
-
- plausible('Search Form: Submit', {
- props: { domain: normalizedDomain },
- });
- };
+ setSelectedSuggestion(null);
+ }, [suggestions]);
+
+ const handleSelectSuggestion = useCallback(
+ (value: string) => {
+ setError(false);
+
+ setDomain(value);
+ setSuggestionsVisible(false);
+ redirectUser(value);
+
+ plausible('Search Form: Click Suggestion', {
+ props: { domain: value },
+ });
+ },
+ [setDomain, redirectUser, plausible]
+ );
+
+ const handleKeyDown = useCallback<KeyboardEventHandler<HTMLFormElement>>(
+ (event) => {
+ console.log(event.key);
+
+ if (
+ !(suggestionsVisible && domain && suggestions && suggestions.length > 0)
+ ) {
+ return;
+ }
+
+ switch (event.key) {
+ case 'ArrowDown':
+ event.preventDefault();
+ setSelectedSuggestion((prev) => {
+ if (prev === null) return 0;
+ if (prev === suggestions?.length - 1) return 0;
+ return prev + 1;
+ });
+ break;
+ case 'ArrowUp':
+ event.preventDefault();
+ setSelectedSuggestion((prev) => {
+ if (prev === null) return suggestions?.length - 1;
+ if (prev === 0) return suggestions?.length - 1;
+ return prev - 1;
+ });
+ break;
+ case 'Enter':
+ if (selectedSuggestion !== null) {
+ event.preventDefault();
+ handleSelectSuggestion(suggestions[selectedSuggestion]);
+ }
+ break;
+ }
+ },
+ [
+ suggestionsVisible,
+ domain,
+ suggestions,
+ selectedSuggestion,
+ handleSelectSuggestion,
+ ]
+ );
return (
<>
- <form className="flex gap-3" onSubmit={handleSubmit}>
- <div className="relative flex-[3]">
+ <form
+ className="flex gap-3"
+ onSubmit={handleSubmit}
+ onKeyDown={handleKeyDown}
+ >
+ <div className="group relative flex-[3]">
<Input
ref={inputRef}
className="w-full"
@@ -106,6 +206,12 @@ const SearchForm = (props: SearchFormProps) => {
onInput={(event: ChangeEvent<HTMLInputElement>) =>
setDomain(event.target.value)
}
+ onFocus={() => setSuggestionsVisible(true)}
+ onBlur={() => {
+ setTimeout(() => {
+ setSuggestionsVisible(false);
+ }, 100);
+ }}
disabled={state !== FormStates.Initial}
autoFocus={props.autofocus}
/>
@@ -119,6 +225,26 @@ const SearchForm = (props: SearchFormProps) => {
'ctrl+k'
)}
</kbd>
+
+ {suggestionsVisible &&
+ domain &&
+ suggestions &&
+ suggestions.length > 0 && (
+ <ul className="absolute left-0 top-full w-full rounded-xl border bg-card p-1 text-card-foreground shadow">
+ {suggestions.map((value, index) => (
+ <li
+ key={value}
+ className={cn(
+ 'cursor-pointer rounded-lg px-2 py-1 hover:bg-muted/50',
+ { 'bg-muted/50': selectedSuggestion === index }
+ )}
+ onClick={() => handleSelectSuggestion(value)}
+ >
+ {value}
+ </li>
+ ))}
+ </ul>
+ )}
</div>
<Button
className="flex-[1]"
diff --git a/lib/bigquery.ts b/lib/bigquery.ts
index 9fd9a44..c28a2fc 100644
--- a/lib/bigquery.ts
+++ b/lib/bigquery.ts
@@ -50,6 +50,74 @@ export const insertRows = async ({
}
};
+export const query = async ({
+ query,
+ params,
+}: {
+ query: string;
+ params?: Record<string, string>;
+}): Promise<any[]> => {
+ const accessToken = await getAccessToken({
+ credentials: credentials,
+ scope: 'https://www.googleapis.com/auth/bigquery',
+ });
+
+ const queryParameters = params
+ ? Object.keys(params).map((key) => ({
+ name: key,
+ parameterType: {
+ type: typeof params[key] === 'number' ? 'INT64' : 'STRING',
+ },
+ parameterValue: { value: params[key] },
+ }))
+ : [];
+
+ const response = await fetch(
+ `https://bigquery.googleapis.com/bigquery/v2/projects/${
+ credentials!.project_id
+ }/queries`,
+ {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ kind: 'bigquery#queryRequest',
+ useLegacySql: false,
+ location: process.env.BIGQUERY_LOCATION,
+ query,
+ parameterMode: 'NAMED',
+ queryParameters,
+ }),
+ }
+ );
+
+ if (!response.ok) {
+ const errorBody = await response.text();
+ throw new Error(
+ `Failed to execute query in BigQuery: ${response.status} ${errorBody}`
+ );
+ }
+
+ const { schema, rows } = await response.json();
+
+ if (!rows) {
+ return [];
+ }
+
+ return rows.map((row: any) =>
+ Object.fromEntries(
+ row.f.map((field: any, index: number) => [
+ schema.fields[index].name,
+ field.v,
+ ])
+ )
+ );
+};
+
export default credentials && {
+ projectId: credentials.project_id,
insertRows,
+ query,
};