Skip to content

Open source alternative to Semrush and Ahrefs

Port keyword research to shadcn, with a Combobox country picker (EVE-313) (#755)

Carter Smith53dbca2b4b0e
diff --git a/src/client/components/LocationSelect.tsx b/src/client/components/LocationSelect.tsx
index a175c329..1baf8bc7 100644
--- a/src/client/components/LocationSelect.tsx
+++ b/src/client/components/LocationSelect.tsx
@@ -1,5 +1,12 @@
-import { useEffect, useMemo, useRef, useState } from "react";
-import { Check, Search } from "lucide-react";
+import { cn } from "cn";
+import {
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+} from "@/client/components/ui/combobox";
import { LOCATION_OPTIONS } from "@/shared/keyword-locations";
type LocationOption = (typeof LOCATION_OPTIONS)[number];
@@ -9,7 +16,7 @@ type Props = {
onChange: (locationCode: number) => void;
/** Defaults to the full country list. Pass a subset (e.g. Labs-only). */
options?: readonly LocationOption[];
- /** Width utilities for the wrapper/trigger. Defaults to full width. */
+ /** Width utilities for the field. Defaults to full width. */
className?: string;
};
@@ -22,153 +29,41 @@ function matches(option: LocationOption, query: string): boolean {
);
}
-/**
- * Searchable country picker. Allows users to filter the country list instead of
- * scrolling it. The scrollable list is preserved below the search input.
- */
+/** Searchable country picker: type to filter the country list. */
export function LocationSelect({
value,
onChange,
options = LOCATION_OPTIONS,
className = "w-full",
}: Props) {
- const [open, setOpen] = useState(false);
- const [query, setQuery] = useState("");
- const [activeIndex, setActiveIndex] = useState(0);
-
- const containerRef = useRef<HTMLDivElement>(null);
- const inputRef = useRef<HTMLInputElement>(null);
- const listRef = useRef<HTMLUListElement>(null);
-
const selected = options.find((option) => option.code === value) ?? null;
- const filtered = useMemo(
- () => options.filter((option) => matches(option, query)),
- [options, query],
- );
-
- // Reset transient state and focus the search input each time the menu opens.
- useEffect(() => {
- if (!open) return;
- setQuery("");
- setActiveIndex(0);
- inputRef.current?.focus();
- }, [open]);
-
- // Close on outside click so it behaves like the surrounding native selects.
- useEffect(() => {
- if (!open) return;
- const handlePointerDown = (event: PointerEvent) => {
- const target = event.target;
- if (target instanceof Node && !containerRef.current?.contains(target)) {
- setOpen(false);
- }
- };
- document.addEventListener("pointerdown", handlePointerDown);
- return () => document.removeEventListener("pointerdown", handlePointerDown);
- }, [open]);
-
- // Keep the highlighted option in view as the user arrows through results.
- useEffect(() => {
- if (!open) return;
- const activeItem = listRef.current?.children[activeIndex];
- activeItem?.scrollIntoView({ block: "nearest" });
- }, [activeIndex, open]);
-
- const select = (option: LocationOption) => {
- onChange(option.code);
- setOpen(false);
- };
-
- const handleKeyDown = (event: React.KeyboardEvent) => {
- switch (event.key) {
- case "ArrowDown":
- event.preventDefault();
- setActiveIndex((index) => Math.min(index + 1, filtered.length - 1));
- break;
- case "ArrowUp":
- event.preventDefault();
- setActiveIndex((index) => Math.max(index - 1, 0));
- break;
- case "Enter": {
- event.preventDefault();
- const option = filtered[activeIndex];
- if (option) select(option);
- break;
- }
- case "Escape":
- event.preventDefault();
- setOpen(false);
- break;
- }
- };
-
return (
- <div ref={containerRef} className={`relative ${className}`}>
- <button
- type="button"
- className="select select-bordered flex w-full items-center justify-between gap-2 text-left font-normal"
- aria-haspopup="listbox"
- aria-expanded={open}
- onClick={() => setOpen((prev) => !prev)}
- >
- <span className="truncate">{selected?.label ?? "Select country"}</span>
- </button>
-
- {open ? (
- <div className="fixed z-30 mt-2 w-full max-w-56 rounded-box border border-base-300 bg-base-100 p-2 shadow-lg">
- <label className="flex items-center gap-2 rounded-lg border border-base-300 px-3 py-2 focus-within:border-primary">
- <Search className="size-4 shrink-0 text-base-content/50" />
- <input
- ref={inputRef}
- type="text"
- className="grow min-w-0 bg-transparent text-sm outline-none placeholder:text-base-content/40"
- placeholder="Search countries"
- value={query}
- onChange={(event) => {
- setQuery(event.target.value);
- setActiveIndex(0);
- }}
- onKeyDown={handleKeyDown}
- />
- </label>
-
- <ul
- ref={listRef}
- role="listbox"
- className="menu mt-2 max-h-64 w-full flex-nowrap overflow-y-auto p-0"
- >
- {filtered.length === 0 ? (
- <li className="w-full break-all px-3 py-2 text-sm text-base-content/50">
- No countries match “{query.trim()}”
- </li>
- ) : (
- filtered.map((option, index) => {
- const isSelected = option.code === value;
- return (
- <li
- key={option.code}
- role="option"
- aria-selected={isSelected}
- >
- <button
- type="button"
- className={`w-full ${index === activeIndex ? "menu-focus" : ""}`}
- onClick={() => select(option)}
- onMouseEnter={() => setActiveIndex(index)}
- >
- <span className="flex-1 truncate">{option.label}</span>
- {isSelected ? (
- <Check className="size-4 shrink-0 text-primary" />
- ) : null}
- </button>
- </li>
- );
- })
- )}
- </ul>
- </div>
- ) : null}
- </div>
+ <Combobox
+ items={options}
+ value={selected}
+ itemToStringLabel={(option) => option.label}
+ autoHighlight
+ filter={matches}
+ onValueChange={(option) => {
+ if (option) onChange(option.code);
+ }}
+ >
+ <ComboboxInput
+ className={cn("h-10", className)}
+ placeholder="Select country"
+ aria-label="Country"
+ />
+ <ComboboxContent>
+ <ComboboxEmpty>No countries match.</ComboboxEmpty>
+ <ComboboxList>
+ {(option: LocationOption) => (
+ <ComboboxItem key={option.code} value={option}>
+ {option.label}
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
);
}
diff --git a/src/client/components/SerpLocationCombobox.tsx b/src/client/components/SerpLocationCombobox.tsx
index f8e08db1..233e7c5e 100644
--- a/src/client/components/SerpLocationCombobox.tsx
+++ b/src/client/components/SerpLocationCombobox.tsx
@@ -2,6 +2,12 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { Loader2, MapPin } from "lucide-react";
import { searchSerpLocations } from "@/serverFunctions/serp-locations";
import { formatLocationLabel } from "@/shared/keyword-locations";
+import { Badge } from "@/client/components/ui/badge";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@/client/components/ui/input-group";
import type { SerpLocationResult } from "@/server/lib/dataforseo/serp-locations";
type Props = {
@@ -197,15 +203,12 @@ export function SerpLocationCombobox({
setOpen(false);
}}
>
- <label className="flex items-center gap-2 input input-bordered w-full pr-3">
- {isLoading ? (
- <Loader2 className="size-4 shrink-0 text-base-content/50 animate-spin" />
- ) : (
- <MapPin className="size-4 shrink-0 text-base-content/50" />
- )}
- <input
+ <InputGroup className="h-10">
+ <InputGroupAddon>
+ {isLoading ? <Loader2 className="animate-spin" /> : <MapPin />}
+ </InputGroupAddon>
+ <InputGroupInput
type="text"
- className="grow min-w-0 bg-transparent outline-none placeholder:text-base-content/40"
placeholder={placeholder}
value={inputValue}
onChange={handleInputChange}
@@ -215,27 +218,27 @@ export function SerpLocationCombobox({
}}
autoComplete="off"
/>
- </label>
+ </InputGroup>
{open && (
<div
- className="absolute z-30 mt-1 w-full rounded-box border border-base-300 bg-base-100 shadow-lg p-1"
+ className="absolute z-30 mt-1 w-full rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10"
// Keep focus in the input, so picking a result is not a blur.
onMouseDown={(e) => e.preventDefault()}
>
{isError ? (
- <p className="px-3 py-2 text-sm text-error">
+ <p className="px-3 py-2 text-sm text-destructive">
Unable to load locations
</p>
) : results.length === 0 ? (
- <p className="px-3 py-2 text-sm text-base-content/50">
+ <p className="px-3 py-2 text-sm text-muted-foreground">
No locations found for "{debouncedQuery.text.trim()}"
</p>
) : (
<ul
ref={listRef}
role="listbox"
- className="menu max-h-56 w-full flex-nowrap overflow-y-auto p-0"
+ className="max-h-56 w-full overflow-y-auto"
>
{results.map((loc, index) => (
<li
@@ -245,16 +248,16 @@ export function SerpLocationCombobox({
>
<button
type="button"
- className={`w-full flex items-center justify-between gap-2 ${index === activeIndex ? "menu-focus" : ""}`}
+ className={`flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm ${index === activeIndex ? "bg-accent text-accent-foreground" : ""}`}
onClick={() => select(loc)}
onMouseEnter={() => setActiveIndex(index)}
>
<span className="truncate text-left">
{loc.displayLabel}
</span>
- <span className="badge badge-xs bg-base-300 border-0 text-base-content/60 shrink-0">
+ <Badge variant="secondary" size="sm">
{loc.locationType}
- </span>
+ </Badge>
</button>
</li>
))}
diff --git a/src/client/components/table/DataTable.tsx b/src/client/components/table/DataTable.tsx
index 1760a676..c94faa1c 100644
--- a/src/client/components/table/DataTable.tsx
+++ b/src/client/components/table/DataTable.tsx
@@ -10,7 +10,12 @@ import {
type Table as TanStackTable,
type TableOptions,
} from "@tanstack/react-table";
-import { useRef, type MutableRefObject, type ReactNode } from "react";
+import {
+ useRef,
+ type ComponentProps,
+ type MutableRefObject,
+ type ReactNode,
+} from "react";
import { EmptyState } from "@/client/components/EmptyState";
import { Button } from "@/client/components/ui/button";
import { Checkbox } from "@/client/components/ui/checkbox";
@@ -150,10 +155,19 @@ export function DataTable<TData>({
error,
toolbar,
footer,
+ onRowClick,
+ activeRowId,
}: DataTableFrameProps & {
table: TanStackTable<TData>;
/** Shown when there are no rows and no filters. */
- empty: { title: ReactNode; description?: ReactNode; action?: ReactNode };
+ empty: Pick<
+ ComponentProps<typeof EmptyState>,
+ "kind" | "title" | "description" | "action"
+ >;
+ /** Makes each row clickable, for example to open its details beside the table. */
+ onRowClick?: (row: Row<TData>) => void;
+ /** Highlights the row whose details are open. */
+ activeRowId?: string;
}) {
const columns = table.getVisibleLeafColumns();
const rows = table.getRowModel().rows;
@@ -229,6 +243,13 @@ export function DataTable<TData>({
<TableRow
key={row.id}
data-state={row.getIsSelected() ? "selected" : undefined}
+ data-active={row.id === activeRowId ? "" : undefined}
+ className={
+ onRowClick
+ ? "cursor-pointer data-active:bg-primary/5 data-active:shadow-[inset_2px_0_0_var(--color-primary)]"
+ : undefined
+ }
+ onClick={onRowClick ? () => onRowClick(row) : undefined}
>
{row.getVisibleCells().map((cell) => {
const meta = cell.column.columnDef.meta?.cellClassName;
diff --git a/src/client/components/table/ExportToSheetsButton.tsx b/src/client/components/table/ExportToSheetsButton.tsx
index 9f4c71f1..08ec9e8c 100644
--- a/src/client/components/table/ExportToSheetsButton.tsx
+++ b/src/client/components/table/ExportToSheetsButton.tsx
@@ -2,6 +2,7 @@ import { Sheet } from "lucide-react";
import { useState } from "react";
import type { CsvValue } from "@/client/lib/csv";
import { exportTableToSheets } from "@/client/lib/exportToSheets";
+import { Button } from "@/client/components/ui/button";
type Props = {
headers: string[];
@@ -28,15 +29,16 @@ export function ExportToSheetsButton({ headers, rows, feature }: Props) {
};
return (
- <button
- type="button"
- className="btn btn-ghost btn-xs gap-1"
+ <Button
+ variant="ghost"
+ size="sm"
onClick={handleClick}
- disabled={rows.length === 0 || busy}
+ disabled={rows.length === 0}
+ pending={busy}
title="Copy table and open a new Google Sheet"
>
- <Sheet className="size-3.5" />
+ {busy ? null : <Sheet data-icon="inline-start" />}
Export to Sheets
- </button>
+ </Button>
);
}
diff --git a/src/client/components/ui/input-group.tsx b/src/client/components/ui/input-group.tsx
index 99a1eae0..64773692 100644
--- a/src/client/components/ui/input-group.tsx
+++ b/src/client/components/ui/input-group.tsx
@@ -58,7 +58,9 @@ function InputGroupAddon({
if (e.target instanceof Element && e.target.closest("button")) {
return;
}
- e.currentTarget.parentElement?.querySelector("input")?.focus();
+ e.currentTarget.parentElement
+ ?.querySelector<HTMLElement>("input, textarea")
+ ?.focus();
}}
{...props}
/>
diff --git a/src/client/features/keywords/components/DisplayPrimitives.tsx b/src/client/features/keywords/components/DisplayPrimitives.tsx
index 9a586fcf..86a9f9a1 100644
--- a/src/client/features/keywords/components/DisplayPrimitives.tsx
+++ b/src/client/features/keywords/components/DisplayPrimitives.tsx
@@ -1,4 +1,3 @@
-import { ChevronDown, ChevronUp } from "lucide-react";
import { Area, AreaChart } from "recharts";
import {
ChartGrid,
@@ -17,11 +16,6 @@ import {
lastTwelveMonths,
MONTH_SHORT_LABELS,
} from "../utils";
-import {
- Tooltip as HelpTooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@/client/components/ui/tooltip";
export type SortField =
| "keyword"
@@ -91,55 +85,3 @@ export function AreaTrendChart({ trend }: { trend: MonthlySearch[] }) {
</ChartContainer>
);
}
-
-export function SortHeader({
- label,
- helpText,
- field,
- current,
- dir,
- onToggle,
- className,
-}: {
- label: string;
- helpText?: string;
- field: SortField;
- current: SortField;
- dir: SortDir;
- onToggle: (f: SortField) => void;
- className?: string;
-}) {
- const isActive = field === current;
- const content = (
- <>
- {label}
- {isActive &&
- (dir === "asc" ? (
- <ChevronUp className="size-3" />
- ) : (
- <ChevronDown className="size-3" />
- ))}
- </>
- );
- const buttonClassName = `inline-flex items-center gap-0.5 hover:text-primary transition-colors cursor-pointer select-none ${className ?? ""}`;
-
- if (!helpText) {
- return (
- <button className={buttonClassName} onClick={() => onToggle(field)}>
- {content}
- </button>
- );
- }
- return (
- <HelpTooltip>
- <TooltipTrigger
- delay={150}
- className={buttonClassName}
- onClick={() => onToggle(field)}
- >
- {content}
- </TooltipTrigger>
- <TooltipContent>{helpText}</TooltipContent>
- </HelpTooltip>
- );
-}
diff --git a/src/client/features/keywords/components/IntentBadge.tsx b/src/client/features/keywords/components/IntentBadge.tsx
index 180b5ddc..34ab7465 100644
--- a/src/client/features/keywords/components/IntentBadge.tsx
+++ b/src/client/features/keywords/components/IntentBadge.tsx
@@ -1,16 +1,20 @@
import type { KeywordIntent } from "@/types/keywords";
+import { Badge } from "@/client/components/ui/badge";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/client/components/ui/tooltip";
-const COLORS: Record<KeywordIntent, string> = {
- informational: "border-info/30 bg-info/15 text-info",
- commercial: "border-warning/35 bg-warning/20 text-warning",
- transactional: "border-success/30 bg-success/15 text-success",
- navigational: "border-primary/30 bg-primary/15 text-primary",
- unknown: "border-base-300 bg-base-200 text-base-content/60",
+const VARIANTS: Record<
+ KeywordIntent,
+ "info" | "warning" | "success" | "soft" | "secondary"
+> = {
+ informational: "info",
+ commercial: "warning",
+ transactional: "success",
+ navigational: "soft",
+ unknown: "secondary",
};
const SHORT_LABELS: Record<KeywordIntent, string> = {
@@ -68,8 +72,13 @@ export function IntentBadge({ intent }: { intent: KeywordIntent }) {
<Tooltip>
<TooltipTrigger
delay={0}
- render={<span tabIndex={0} />}
- className={`inline-flex h-6 min-w-11 cursor-help items-center justify-center rounded-full border px-2 text-xs font-semibold leading-none ${COLORS[intent]}`}
+ render={
+ <Badge
+ variant={VARIANTS[intent]}
+ tabIndex={0}
+ className="h-6 min-w-11 cursor-help font-semibold"
+ />
+ }
aria-label={`${details.label} search intent`}
>
{SHORT_LABELS[intent]}
diff --git a/src/client/features/keywords/components/KeywordUi.tsx b/src/client/features/keywords/components/KeywordUi.tsx
index fac0be39..1a967686 100644
--- a/src/client/features/keywords/components/KeywordUi.tsx
+++ b/src/client/features/keywords/components/KeywordUi.tsx
@@ -1,15 +1,17 @@
import type { KeywordResearchRow } from "@/types/keywords";
+import { Card } from "@/client/components/ui/card";
+import { Separator } from "@/client/components/ui/separator";
import { ScoreBadge } from "@/client/components/table/ScoreBadge";
import { formatNumber } from "../utils";
import { IntentBadge } from "./IntentBadge";
export { SerpAnalysisCard } from "./SerpAnalysisCard";
export type { SortDir, SortField } from "./DisplayPrimitives";
-export { AreaTrendChart, SortHeader } from "./DisplayPrimitives";
+export { AreaTrendChart } from "./DisplayPrimitives";
export function OverviewStats({ keyword }: { keyword: KeywordResearchRow }) {
return (
- <div className="shrink-0 bg-base-100 border border-base-300 rounded-xl px-4 py-2.5 flex items-center gap-4 min-h-[48px]">
+ <Card className="shrink-0 flex-row items-center gap-4 px-4 py-2.5 min-h-[48px]">
<div className="flex items-center gap-2 min-w-0 shrink-0">
<span className="font-bold text-base truncate max-w-[240px] capitalize">
{keyword.keyword}
@@ -17,29 +19,29 @@ export function OverviewStats({ keyword }: { keyword: KeywordResearchRow }) {
<ScoreBadge value={keyword.keywordDifficulty} />
</div>
- <div className="w-px h-6 bg-base-300 shrink-0" />
+ <Separator orientation="vertical" className="h-6" />
<div className="flex items-center gap-4 text-sm flex-wrap min-w-0">
<div className="flex items-center gap-1.5">
- <span className="text-base-content/50">Vol</span>
+ <span className="text-muted-foreground">Vol</span>
<span className="font-semibold tabular-nums">
{formatNumber(keyword.searchVolume)}
</span>
</div>
<div className="flex items-center gap-1.5">
- <span className="text-base-content/50">CPC</span>
+ <span className="text-muted-foreground">CPC</span>
<span className="font-semibold tabular-nums">
{keyword.cpc == null ? "-" : `$${keyword.cpc.toFixed(2)}`}
</span>
</div>
<div className="flex items-center gap-1.5">
- <span className="text-base-content/50">Comp</span>
+ <span className="text-muted-foreground">Comp</span>
<span className="font-semibold tabular-nums">
{keyword.competition == null ? "-" : keyword.competition.toFixed(2)}
</span>
</div>
<IntentBadge intent={keyword.intent} />
</div>
- </div>
+ </Card>
);
}
diff --git a/src/client/features/keywords/components/SerpAnalysisCard.tsx b/src/client/features/keywords/components/SerpAnalysisCard.tsx
index 27d2e106..00898e86 100644
--- a/src/client/features/keywords/components/SerpAnalysisCard.tsx
+++ b/src/client/features/keywords/components/SerpAnalysisCard.tsx
@@ -1,7 +1,58 @@
-import { ExternalLink } from "lucide-react";
+import { useMemo } from "react";
+import { createColumnHelper } from "@tanstack/react-table";
+import { ExternalLink, Globe } from "lucide-react";
+import { ErrorState } from "@/client/components/ErrorState";
+import { Button } from "@/client/components/ui/button";
+import { DataTable, useDataTable } from "@/client/components/table/DataTable";
+import { DataTableToolbar } from "@/client/components/table/DataTableToolbar";
import { ExportToSheetsButton } from "@/client/components/table/ExportToSheetsButton";
import { TablePagination } from "@/client/components/table/TablePagination";
import type { SerpResultItem } from "@/types/keywords";
+import { safeHttpUrl } from "@/shared/safe-url";
+
+const columnHelper = createColumnHelper<SerpResultItem>();
+
+const columns = [
+ columnHelper.accessor("rank", {
+ header: "#",
+ cell: ({ getValue }) => getValue(),
+ meta: {
+ headerClassName: "w-8",
+ cellClassName: "font-mono text-xs text-muted-foreground",
+ },
+ }),
+ columnHelper.display({
+ id: "page",
+ header: "Page",
+ cell: ({ row }) => {
+ const label = row.original.title || row.original.url;
+ // Provider URLs are untrusted: only http(s) links become clickable.
+ const safeUrl = safeHttpUrl(row.original.url);
+ return (
+ <div className="flex flex-col gap-0.5">
+ {safeUrl ? (
+ <a
+ href={safeUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex items-center gap-1 font-medium text-primary hover:underline"
+ title={row.original.title}
+ >
+ <span className="truncate">{label}</span>
+ <ExternalLink className="size-3 shrink-0 opacity-40" />
+ </a>
+ ) : (
+ <span className="truncate font-medium">{label}</span>
+ )}
+ <span className="truncate text-xs text-muted-foreground">
+ {row.original.domain}
+ </span>
+ </div>
+ );
+ },
+ meta: { cellClassName: "min-w-0 max-w-0" },
+ }),
+];
export function SerpAnalysisCard({
items,
@@ -34,127 +85,91 @@ export function SerpAnalysisCard({
onPageChange: (p: number) => void;
}) {
const totalPages = Math.ceil(items.length / pageSize);
- const pageItems = items.slice(page * pageSize, (page + 1) * pageSize);
-
- if (loading) return <SerpAnalysisLoadingState />;
- const errorBox = error ? (
- <div className="rounded-lg border border-error/30 bg-error/10 p-3 text-sm text-error space-y-2 mb-3">
- <p>{error}</p>
- {onRetry ? (
- <button className="btn btn-xs" onClick={onRetry} disabled={retrying}>
- {retrying ? "Retrying…" : deepFetchFailed ? "Show top 20" : "Retry"}
- </button>
- ) : null}
- </div>
- ) : null;
- if (items.length === 0) {
- return errorBox ?? <SerpAnalysisEmptyState keyword={keyword} />;
- }
-
- return (
- <div>
- {errorBox}
- <div className="flex items-center justify-between mb-3">
- <div className="text-xs text-base-content/50">
- {items.length} organic results
- </div>
- <ExportToSheetsButton
- headers={["Rank", "Title", "URL", "Domain"]}
- rows={items.map((item) => [
- item.rank,
- item.title ?? "",
- item.url,
- item.domain,
- ])}
- feature="serp_analysis"
- />
- </div>
- {pageItems.length === 0 && loadingMore ? (
- <SerpAnalysisLoadingState />
- ) : (
- <SerpAnalysisTable items={pageItems} />
- )}
- {totalPages > 1 || canLoadMore ? (
- <TablePagination
- page={page + 1}
- pageSize={pageSize}
- totalCount={items.length}
- isLoading={loadingMore}
- // Past the loaded results, "Next" buys a deeper crawl. The button
- // says so rather than spending silently.
- loadMoreLabel={canLoadMore ? "Load top 100" : undefined}
- onPageChange={(nextPage) => onPageChange(nextPage - 1)}
- />
- ) : null}
- </div>
+ const pageItems = useMemo(
+ () => items.slice(page * pageSize, (page + 1) * pageSize),
+ [items, page, pageSize],
);
-}
+ const table = useDataTable({ data: pageItems, columns });
+ const hasItems = !loading && items.length > 0;
-function SerpAnalysisTable({ items }: { items: SerpResultItem[] }) {
- return (
- <div className="overflow-x-auto">
- <table className="table table-xs w-full">
- <thead>
- <tr className="text-xs text-base-content/60">
- <th className="w-8">#</th>
- <th>Page</th>
- </tr>
- </thead>
- <tbody>
- {items.map((item) => (
- <tr
- key={`${item.rank}-${item.url}`}
- className="hover:bg-base-200/50"
- >
- <td className="font-mono text-base-content/50 text-xs">
- {item.rank}
- </td>
- <td className="min-w-0 max-w-0">
- <div className="flex flex-col gap-0.5">
- <a
- href={item.url}
- target="_blank"
- rel="noopener noreferrer"
- className="font-medium text-primary hover:underline truncate flex items-center gap-1"
- title={item.title}
- >
- {item.title || item.url}
- <ExternalLink className="size-3 shrink-0 opacity-40" />
- </a>
- <span className="text-xs text-base-content/40 truncate">
- {item.domain}
- </span>
- </div>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- );
-}
-
-function SerpAnalysisLoadingState() {
- return (
- <div className="space-y-2">
- {Array.from({ length: 8 }).map((_, index) => (
- <div
- key={index}
- className="h-8 rounded bg-base-200 animate-pulse"
- style={{ animationDelay: `${index * 50}ms` }}
- />
- ))}
- </div>
- );
-}
+ const retryButton = onRetry ? (
+ <Button variant="outline" size="sm" pending={retrying} onClick={onRetry}>
+ {deepFetchFailed ? "Show top 20" : "Retry"}
+ </Button>
+ ) : null;
-function SerpAnalysisEmptyState({ keyword }: { keyword?: string | null }) {
return (
- <div className="text-sm text-base-content/50 text-center py-8">
- <p>No SERP details available for this keyword yet.</p>
- {keyword ? (
- <p className="mt-1">Try clicking another keyword to load data.</p>
- ) : null}
- </div>
+ <DataTable
+ table={table}
+ isLoading={loading || (pageItems.length === 0 && loadingMore)}
+ toolbar={
+ <>
+ <DataTableToolbar
+ actions={
+ hasItems ? (
+ <ExportToSheetsButton
+ headers={["Rank", "Title", "URL", "Domain"]}
+ rows={items.map((item) => [
+ item.rank,
+ item.title ?? "",
+ item.url,
+ item.domain,
+ ])}
+ feature="serp_analysis"
+ />
+ ) : null
+ }
+ >
+ <h3 className="flex min-w-0 items-center gap-1.5 text-sm font-semibold">
+ <Globe className="size-3.5 shrink-0" />
+ SERP Analysis
+ {keyword ? (
+ <span className="truncate font-normal text-muted-foreground">
+ : {keyword}
+ </span>
+ ) : null}
+ </h3>
+ {hasItems ? (
+ <span className="text-xs text-muted-foreground">
+ {items.length} organic results
+ </span>
+ ) : null}
+ </DataTableToolbar>
+ {error && hasItems ? (
+ <div className="border-b border-border px-4 py-3">
+ <ErrorState
+ variant="inline"
+ message={error}
+ action={retryButton}
+ />
+ </div>
+ ) : null}
+ </>
+ }
+ empty={
+ error
+ ? { kind: "error", title: error, action: retryButton }
+ : {
+ title: "No SERP details available for this keyword yet.",
+ description: keyword
+ ? "Try clicking another keyword to load data."
+ : undefined,
+ }
+ }
+ footer={
+ hasItems && (totalPages > 1 || canLoadMore) ? (
+ <TablePagination
+ page={page + 1}
+ pageSize={pageSize}
+ totalCount={items.length}
+ isLoading={loadingMore}
+ // Past the loaded results, "Next" buys a deeper crawl. The button
+ // says so rather than spending silently.
+ loadMoreLabel={canLoadMore ? "Load top 100" : undefined}
+ onPageChange={(nextPage) => onPageChange(nextPage - 1)}
+ />
+ ) : null
+ }
+ />
);
}
diff --git a/src/client/features/keywords/page/KeywordAreaField.tsx b/src/client/features/keywords/page/KeywordAreaField.tsx
index db6db14d..d6aeabae 100644
--- a/src/client/features/keywords/page/KeywordAreaField.tsx
+++ b/src/client/features/keywords/page/KeywordAreaField.tsx
@@ -46,7 +46,7 @@ export function LocalVolumeCostNote() {
? applyBillingMarkupUsd(LOCAL_VOLUME_COST_USD)
: LOCAL_VOLUME_COST_USD;
return (
- <span className="text-xs text-base-content/60">
+ <span className="text-xs text-muted-foreground">
Local volume adds ~${costUsd.toFixed(2)} per search.
</span>
);
diff --git a/src/client/features/keywords/page/KeywordResearchEmptyState.tsx b/src/client/features/keywords/page/KeywordResearchEmptyState.tsx
index d849095e..5aea693b 100644
--- a/src/client/features/keywords/page/KeywordResearchEmptyState.tsx
+++ b/src/client/features/keywords/page/KeywordResearchEmptyState.tsx
@@ -1,5 +1,6 @@
import { Link } from "@tanstack/react-router";
import { Globe, Search } from "lucide-react";
+import { EmptyState } from "@/client/components/EmptyState";
import { RecentSearches } from "@/client/components/RecentSearches";
import { LOCATIONS } from "@/client/features/keywords/utils";
import type { KeywordResearchControllerState } from "./types";
@@ -26,26 +27,25 @@ function NoResultsState({
const { lastSearchKeyword, lastSearchLocationCode } = controller;
return (
- <div className="pt-1">
- <div className="w-full max-w-2xl rounded-2xl border border-base-300 bg-base-100 p-6 md:p-8 text-center space-y-4 mx-auto">
- <Globe className="size-10 mx-auto text-base-content/40" />
- <div className="space-y-2">
- <p className="text-lg font-semibold text-base-content">
- Not enough keyword data for this query yet
- </p>
- <p className="text-sm text-base-content/70">
+ <div className="mx-auto w-full max-w-2xl pt-1">
+ <EmptyState
+ variant="card"
+ icon={Globe}
+ title="Not enough keyword data for this query yet"
+ description={
+ <>
We could not find keyword opportunities for
- <span className="font-medium text-base-content">
+ <span className="font-medium text-foreground">
{` "${lastSearchKeyword}" `}
</span>
in
- <span className="font-medium text-base-content">
+ <span className="font-medium text-foreground">
{` ${LOCATIONS[lastSearchLocationCode] || "this location"}`}
</span>
.
- </p>
- </div>
- </div>
+ </>
+ }
+ />
</div>
);
}
diff --git a/src/client/features/keywords/page/KeywordResearchLoadingState.tsx b/src/client/features/keywords/page/KeywordResearchLoadingState.tsx
index 7e543d19..96d057ac 100644
--- a/src/client/features/keywords/page/KeywordResearchLoadingState.tsx
+++ b/src/client/features/keywords/page/KeywordResearchLoadingState.tsx
@@ -5,7 +5,7 @@ import { Skeleton } from "@/client/components/ui/skeleton";
export function KeywordResearchLoadingState() {
return (
<div className="flex-1 w-full flex flex-col">
- <div className="md:hidden flex border-b border-base-300 mb-4">
+ <div className="md:hidden flex border-b border-border mb-4">
<div className="flex-1 py-2.5">
<Skeleton className="h-4 w-28 mx-auto" />
</div>
@@ -15,11 +15,11 @@ export function KeywordResearchLoadingState() {
</div>
<div className="flex-1 flex flex-col xl:flex-row gap-4">
<div className="order-2 xl:order-1 flex flex-col min-w-0 gap-2 xl:basis-3/5">
- <div className="hidden md:block rounded-xl border border-base-300 bg-base-100 p-4">
+ <div className="hidden md:block rounded-xl border border-border bg-card p-4">
<Skeleton className="h-5 w-56" />
</div>
- <div className="flex-1 rounded-xl border border-base-300 bg-base-100 overflow-hidden">
- <div className="border-b border-base-300 px-4 py-3 flex items-center gap-3">
+ <div className="flex-1 rounded-xl border border-border bg-card overflow-hidden">
+ <div className="border-b border-border px-4 py-3 flex items-center gap-3">
<Skeleton className="h-8 w-24" />
<Skeleton className="h-4 w-40" />
</div>
@@ -41,11 +41,11 @@ export function KeywordResearchLoadingState() {
</div>
</div>
<div className="hidden md:flex order-1 xl:order-2 flex-col min-w-0 gap-2 xl:basis-2/5">
- <div className="rounded-xl border border-base-300 bg-base-100 p-4 space-y-3">
+ <div className="rounded-xl border border-border bg-card p-4 space-y-3">
<Skeleton className="h-4 w-36" />
<Skeleton className="h-56 w-full" />
</div>
- <div className="flex-1 rounded-xl border border-base-300 bg-base-100 p-4 space-y-3">
+ <div className="flex-1 rounded-xl border border-border bg-card p-4 space-y-3">
<Skeleton className="h-4 w-44" />
{Array.from({ length: 6 }).map((_, index) => (
<div key={index} className="grid grid-cols-[24px_1fr_72px] gap-2">
diff --git a/src/client/features/keywords/page/KeywordResearchPage.tsx b/src/client/features/keywords/page/KeywordResearchPage.tsx
index a1cb2846..ee5c80c9 100644
--- a/src/client/features/keywords/page/KeywordResearchPage.tsx
+++ b/src/client/features/keywords/page/KeywordResearchPage.tsx
@@ -1,7 +1,10 @@
import { Link } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
-import { AlertCircle } from "lucide-react";
+import { ErrorState } from "@/client/components/ErrorState";
+import { FormDialog } from "@/client/components/FormDialog";
+import { PageHeader } from "@/client/components/PageHeader";
import { RecentSearchesBackLink } from "@/client/components/RecentSearches";
+import { Button } from "@/client/components/ui/button";
import { getErrorCode } from "@/client/lib/error-messages";
import { BILLING_ROUTE } from "@/shared/billing";
import { formatLocationLabel } from "@/shared/keyword-locations";
@@ -197,12 +200,10 @@ export function KeywordResearchPage(input: Props) {
return (
<div className="px-4 py-4 md:px-6 md:py-6 pb-24 md:pb-8 overflow-auto">
<div className="mx-auto flex max-w-7xl flex-col gap-5">
- <div>
- <h1 className="text-2xl font-semibold">Keyword Research</h1>
- <p className="text-sm text-base-content/70">
- Discover keyword ideas, search demand, and ranking opportunities.
- </p>
- </div>
+ <PageHeader
+ title="Keyword Research"
+ description="Discover keyword ideas, search demand, and ranking opportunities."
+ />
<KeywordResearchSearchBar controller={controller} />
{controller.hasSearched ? (
@@ -249,7 +250,10 @@ function KeywordResearchContent({
}
const errorCard = controller.researchError ? (
- <ResearchErrorCard controller={controller} />
+ <ResearchErrorCard
+ controller={controller}
+ message={controller.researchError}
+ />
) : null;
if (controller.rows.length === 0) {
@@ -274,32 +278,34 @@ function KeywordResearchContent({
function ResearchErrorCard({
controller,
+ message,
}: {
controller: KeywordResearchControllerState;
+ message: string;
}) {
const errorCode = getErrorCode(controller.researchMutationError);
return (
- <div className="flex-1 flex items-center justify-center pt-1">
- <div className="w-full max-w-xl rounded-xl border border-error/30 bg-error/10 p-5 text-error space-y-3">
- <div className="flex items-start gap-2">
- <AlertCircle className="mt-0.5 size-4 shrink-0" />
- <p className="text-sm">{controller.researchError}</p>
- </div>
- {errorCode === "INSUFFICIENT_CREDITS" ? (
- <Link to={BILLING_ROUTE} className="btn btn-sm">
- Go to Billing
- </Link>
- ) : errorCode === "UNKNOWN_LOCATION" ? null : (
- <button
- className="btn btn-sm"
- onClick={controller.retrySearch}
- disabled={controller.researchRetrying}
- >
- {controller.researchRetrying ? "Retrying…" : "Try again"}
- </button>
- )}
- </div>
+ <div className="mx-auto w-full max-w-xl pt-1">
+ <ErrorState
+ message={message}
+ onRetry={
+ errorCode === "UNKNOWN_LOCATION" ? undefined : controller.retrySearch
+ }
+ isRetrying={controller.researchRetrying}
+ action={
+ errorCode === "INSUFFICIENT_CREDITS" ? (
+ <Button
+ variant="outline"
+ size="sm"
+ nativeButton={false}
+ render={<Link to={BILLING_ROUTE} />}
+ >
+ Go to Billing
+ </Button>
+ ) : undefined
+ }
+ />
</div>
);
}
@@ -312,38 +318,35 @@ function KeywordSaveDialog({
if (!controller.showSaveDialog) return null;
return (
- <div className="modal modal-open">
- <div className="modal-box">
- <h3 className="font-bold text-lg">
- Save {controller.selectedKeywordRows.length} Keywords
- </h3>
- <div className="py-4">
- <p className="text-base-content/70 text-sm">
- These keywords will be saved to your current project.
- </p>
- {controller.locationName ? (
- <p className="mt-2 text-base-content/70 text-sm">
- Saved keywords show national metrics. The local volume for{" "}
- {formatLocationLabel(controller.locationName)} is not saved.
- </p>
- ) : null}
- </div>
- <div className="modal-action">
- <button
- className="btn"
+ <FormDialog
+ title={`Save ${controller.selectedKeywordRows.length} Keywords`}
+ onClose={() => controller.setShowSaveDialog(false)}
+ actions={
+ <>
+ <Button
+ variant="outline"
onClick={() => controller.setShowSaveDialog(false)}
>
Cancel
- </button>
- <button className="btn btn-primary" onClick={controller.confirmSave}>
+ </Button>
+ <Button
+ pending={controller.savePending}
+ onClick={controller.confirmSave}
+ >
Save
- </button>
- </div>
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-2 text-sm text-muted-foreground">
+ <p>These keywords will be saved to your current project.</p>
+ {controller.locationName ? (
+ <p>
+ Saved keywords show national metrics. The local volume for{" "}
+ {formatLocationLabel(controller.locationName)} is not saved.
+ </p>
+ ) : null}
</div>
- <div
- className="modal-backdrop"
- onClick={() => controller.setShowSaveDialog(false)}
- />
- </div>
+ </FormDialog>
);
}
diff --git a/src/client/features/keywords/page/KeywordResearchResults.tsx b/src/client/features/keywords/page/KeywordResearchResults.tsx
index 44355e22..2d058647 100644
--- a/src/client/features/keywords/page/KeywordResearchResults.tsx
+++ b/src/client/features/keywords/page/KeywordResearchResults.tsx
@@ -1,11 +1,4 @@
-import {
- FileDown,
- Globe,
- RotateCcw,
- Save,
- Sheet,
- SlidersHorizontal,
-} from "lucide-react";
+import { FileDown, Save, Sheet } from "lucide-react";
import {
lastTwelveMonths,
MONTH_SHORT_LABELS,
@@ -16,6 +9,20 @@ import {
SerpAnalysisCard,
} from "@/client/features/keywords/components";
import type { KeywordResearchRow } from "@/types/keywords";
+import { ExportMenu } from "@/client/components/ExportMenu";
+import { Alert, AlertDescription } from "@/client/components/ui/alert";
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+} from "@/client/components/ui/card";
+import { Tabs, TabsList, TabsTrigger } from "@/client/components/ui/tabs";
+import {
+ DataTableFilterPanel,
+ DataTableFilterToggle,
+ DataTableToolbar,
+} from "@/client/components/table/DataTableToolbar";
import type { KeywordResearchControllerState } from "./types";
import {
FilterIntentSelect,
@@ -32,7 +39,6 @@ import {
TableBulkActionBar,
TableBulkActionButton,
TableBulkExportMenu,
- TableExportMenu,
} from "@/client/components/table/TableBulkActionBar";
function formatTrendRangeLabel(trend: KeywordResearchRow["trend"]): string {
@@ -64,30 +70,19 @@ export function KeywordResearchResults({ controller }: Props) {
}
function MobileTabs({ controller }: Props) {
- const tabs = [
- {
- value: "keywords",
- label: `Keywords (${controller.filteredRows.length})`,
- },
- { value: "serp", label: "SERP Analysis" },
- ] as const;
-
return (
- <div className="md:hidden shrink-0 flex border-b border-base-300 bg-base-100 mb-4">
- {tabs.map((tab) => (
- <button
- key={tab.value}
- className={`flex-1 py-2 text-sm font-medium text-center border-b-2 transition-colors ${
- controller.mobileTab === tab.value
- ? "border-primary text-primary"
- : "border-transparent text-base-content/60"
- }`}
- onClick={() => controller.setMobileTab(tab.value)}
- >
- {tab.label}
- </button>
- ))}
- </div>
+ <Tabs
+ value={controller.mobileTab}
+ onValueChange={controller.setMobileTab}
+ className="mb-4 shrink-0 md:hidden"
+ >
+ <TabsList variant="line" className="w-full">
+ <TabsTrigger value="keywords">
+ Keywords ({controller.filteredRows.length})
+ </TabsTrigger>
+ <TabsTrigger value="serp">SERP Analysis</TabsTrigger>
+ </TabsList>
+ </Tabs>
);
}
@@ -99,14 +94,13 @@ function KeywordPanel({ controller }: Props) {
className={`${mobileTab === "keywords" ? "flex" : "hidden md:flex"} order-2 xl:order-1 flex-col min-w-0 gap-2 xl:basis-3/5`}
>
{showApproximateMatchNotice ? (
- <div
- className="rounded-lg border border-warning/40 bg-warning/15 px-3 py-2 text-sm text-base-content"
- role="status"
- >
- No exact match for{" "}
- <span className="font-medium">"{searchedKeyword}"</span>. Showing
- closest related keywords instead.
- </div>
+ <Alert variant="warning" role="status">
+ <AlertDescription className="text-foreground">
+ No exact match for{" "}
+ <span className="font-medium">"{searchedKeyword}"</span>. Showing
+ closest related keywords instead.
+ </AlertDescription>
+ </Alert>
) : null}
{controller.overviewKeyword ? (
<div className="hidden md:block">
@@ -137,47 +131,8 @@ function TableCard({ controller }: Props) {
? `Showing ${keywordCount} of ${rows.length} keywords`
: `Showing ${keywordCount} keywords`;
- const canExport = filteredRows.length > 0;
return (
- <div className="flex-1 flex flex-col min-w-0 border border-base-300 rounded-xl bg-base-100 overflow-hidden">
- <div className="shrink-0 flex flex-wrap items-center gap-2 px-4 py-2 border-b border-base-300">
- <button
- className={`btn btn-ghost btn-xs md:btn-sm gap-1.5 ${showFilters ? "btn-active" : ""}`}
- onClick={() => controller.setShowFilters((current) => !current)}
- title="Toggle table filters"
- >
- <SlidersHorizontal className="size-3.5" />
- Filters
- {activeFilterCount > 0 ? (
- <span className="badge badge-xs badge-primary border-0 text-primary-content">
- {activeFilterCount}
- </span>
- ) : null}
- </button>
- <span className="text-xs md:text-sm text-base-content/60">
- {keywordCountLabel}
- </span>
- <div className="flex-1" />
- <TableExportMenu
- buttonClassName={`btn btn-ghost btn-xs md:btn-sm gap-1 ${canExport ? "" : "btn-disabled"}`}
- labelClassName="hidden lg:inline"
- actions={[
- {
- label: "Export to Sheets",
- icon: <Sheet className="size-4" />,
- onClick: () => controller.exportAll("sheets"),
- disabled: !canExport,
- },
- {
- label: "Export CSV",
- icon: <FileDown className="size-4" />,
- onClick: () => controller.exportAll("csv"),
- disabled: !canExport,
- },
- ]}
- />
- </div>
-
+ <>
<TableBulkActionBar
selectedCount={selectedKeywordRows.length}
onClear={() => controller.setSelectedRows(new Set())}
@@ -206,8 +161,6 @@ function TableCard({ controller }: Props) {
</div>
}
/>
-
- {showFilters ? <TableFilters controller={controller} /> : null}
<KeywordResearchTable
filteredRows={pageRows}
overviewKeyword={controller.overviewKeyword}
@@ -216,21 +169,49 @@ function TableCard({ controller }: Props) {
sortDir={controller.sortDir}
sortField={controller.sortField}
toggleSort={controller.toggleSort}
+ isFiltered={activeFilterCount > 0}
resetFilters={controller.resetFilters}
handleRowClick={controller.handleRowClick}
+ toolbar={
+ <>
+ <DataTableToolbar
+ actions={
+ <ExportMenu
+ actions={["sheets", "csv"]}
+ onExport={controller.exportAll}
+ disabled={filteredRows.length === 0}
+ />
+ }
+ >
+ <DataTableFilterToggle
+ open={showFilters}
+ activeCount={activeFilterCount}
+ onToggle={() =>
+ controller.setShowFilters((current) => !current)
+ }
+ />
+ <span className="text-xs text-muted-foreground md:text-sm">
+ {keywordCountLabel}
+ </span>
+ </DataTableToolbar>
+ {showFilters ? <TableFilters controller={controller} /> : null}
+ </>
+ }
+ footer={
+ filteredRows.length > 0 ? (
+ <TablePagination
+ page={page}
+ pageSize={pageSize}
+ pageSizes={KEYWORD_RESEARCH_PAGE_SIZES}
+ pageRange={pageRange}
+ totalCount={filteredRows.length}
+ onPageChange={setPage}
+ onPageSizeChange={setPageSize}
+ />
+ ) : null
+ }
/>
- {filteredRows.length > 0 ? (
- <TablePagination
- page={page}
- pageSize={pageSize}
- pageSizes={KEYWORD_RESEARCH_PAGE_SIZES}
- pageRange={pageRange}
- totalCount={filteredRows.length}
- onPageChange={setPage}
- onPageSizeChange={setPageSize}
- />
- ) : null}
- </div>
+ </>
);
}
@@ -238,26 +219,10 @@ function TableFilters({ controller }: Props) {
const { activeFilterCount, filtersForm } = controller;
return (
- <div className="shrink-0 border-b border-base-300 bg-gradient-to-b from-base-100 to-base-200/30 px-4 py-3 space-y-3">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div className="flex items-center gap-2">
- <p className="text-sm font-semibold">Refine table results</p>
- {activeFilterCount > 0 ? (
- <span className="badge badge-xs badge-primary border-0 text-primary-content">
- {activeFilterCount} active
- </span>
- ) : null}
- </div>
- <button
- className="btn btn-xs btn-ghost gap-1"
- onClick={controller.resetFilters}
- disabled={activeFilterCount === 0}
- >
- <RotateCcw className="size-3" />
- Clear all
- </button>
- </div>
-
+ <DataTableFilterPanel
+ activeCount={activeFilterCount}
+ onReset={controller.resetFilters}
+ >
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
<FilterTextInput
form={filtersForm}
@@ -296,7 +261,7 @@ function TableFilters({ controller }: Props) {
</div>
<FilterIntentSelect form={filtersForm} />
- </div>
+ </DataTableFilterPanel>
);
}
@@ -308,46 +273,35 @@ function SerpPanel({ controller }: Props) {
className={`${mobileTab === "serp" ? "flex" : "hidden md:flex"} order-1 xl:order-2 flex-col min-w-0 gap-2 xl:basis-2/5 xl:overflow-y-auto`}
>
{overviewKeyword && overviewKeyword.trend.length > 0 ? (
- <div className="hidden md:block shrink-0 overflow-hidden border border-base-300 rounded-xl bg-base-100 px-4 py-3">
- <h4 className="text-sm font-semibold mb-1">
- Search Trends{" "}
- <span className="font-normal text-base-content/50">
- {formatTrendRangeLabel(overviewKeyword.trend)}
- </span>
- </h4>
- <AreaTrendChart trend={overviewKeyword.trend} />
- </div>
+ <Card size="sm" className="hidden shrink-0 md:flex">
+ <CardHeader>
+ <CardTitle>
+ Search Trends{" "}
+ <span className="font-normal text-muted-foreground">
+ {formatTrendRangeLabel(overviewKeyword.trend)}
+ </span>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <AreaTrendChart trend={overviewKeyword.trend} />
+ </CardContent>
+ </Card>
) : null}
- <div className="flex flex-col overflow-hidden border border-base-300 rounded-xl bg-base-100">
- <div className="shrink-0 px-4 py-3 border-b border-base-300">
- <h3 className="text-sm font-semibold flex items-center gap-1.5">
- <Globe className="size-3.5" />
- SERP Analysis
- {controller.activeSerpKeyword ? (
- <span className="font-normal text-base-content/50 truncate">
- : {controller.activeSerpKeyword}
- </span>
- ) : null}
- </h3>
- </div>
- <div className="p-4">
- <SerpAnalysisCard
- items={controller.serpResults}
- keyword={controller.activeSerpKeyword}
- loading={controller.serpLoading}
- loadingMore={controller.serpLoadingMore}
- canLoadMore={controller.canLoadMoreSerp}
- error={controller.serpError}
- onRetry={controller.retrySerp}
- retrying={controller.serpRetrying}
- deepFetchFailed={controller.deepFetchFailed}
- page={controller.serpPage}
- pageSize={controller.SERP_PAGE_SIZE}
- onPageChange={controller.setSerpPage}
- />
- </div>
- </div>
+ <SerpAnalysisCard
+ items={controller.serpResults}
+ keyword={controller.activeSerpKeyword}
+ loading={controller.serpLoading}
+ loadingMore={controller.serpLoadingMore}
+ canLoadMore={controller.canLoadMoreSerp}
+ error={controller.serpError}
+ onRetry={controller.retrySerp}
+ retrying={controller.serpRetrying}
+ deepFetchFailed={controller.deepFetchFailed}
+ page={controller.serpPage}
+ pageSize={controller.SERP_PAGE_SIZE}
+ onPageChange={controller.setSerpPage}
+ />
</div>
);
}
diff --git a/src/client/features/keywords/page/KeywordResearchSearchBar.tsx b/src/client/features/keywords/page/KeywordResearchSearchBar.tsx
index b714cf4c..31b4071f 100644
--- a/src/client/features/keywords/page/KeywordResearchSearchBar.tsx
+++ b/src/client/features/keywords/page/KeywordResearchSearchBar.tsx
@@ -3,6 +3,14 @@ import { getFieldError } from "@/client/lib/forms";
import { MAX_KEYWORDS_PER_SUBMIT } from "@/client/features/keywords/keywordResearchTypes";
import { isLabsLocationCode } from "@/client/features/keywords/locations";
import { LocationSelect } from "@/client/components/LocationSelect";
+import { Alert, AlertDescription } from "@/client/components/ui/alert";
+import { Button } from "@/client/components/ui/button";
+import { Card, CardContent } from "@/client/components/ui/card";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupTextarea,
+} from "@/client/components/ui/input-group";
import { KeywordAreaField, LocalVolumeCostNote } from "./KeywordAreaField";
import { KeywordSearchOptions } from "./KeywordSearchOptions";
import type { KeywordResearchControllerState } from "./types";
@@ -21,9 +29,12 @@ export function KeywordResearchSearchBar({ controller }: Props) {
const { controlsForm, handleSearchSubmit } = controller;
return (
- <div className="card border border-base-300 bg-base-100">
- <div className="card-body gap-2">
+ // The city field opens an absolute menu below the row, so the card must
+ // not clip it.
+ <Card className="overflow-visible">
+ <CardContent className="space-y-2">
<form
+ noValidate
className="flex flex-col gap-3 lg:flex-row lg:flex-wrap lg:items-start lg:gap-2"
onSubmit={handleSearchSubmit}
>
@@ -33,20 +44,19 @@ export function KeywordResearchSearchBar({ controller }: Props) {
const rows = getTextareaRows(field.state.value);
return (
- // Same input styling as the location field beside it. Extra
- // lines grow the field.
- <label
- className={`input input-bordered flex w-full lg:flex-1 lg:min-w-0 lg:max-w-md gap-2 pr-3 ${
- rows > 1 ? "h-auto items-start py-2" : "items-center"
- } ${keywordError ? "input-error" : ""}`}
- >
- <Search
- className={`size-4 shrink-0 text-base-content/50 ${rows > 1 ? "mt-1" : ""}`}
- />
- <textarea
- className="grow min-w-0 resize-none bg-transparent leading-6 outline-none placeholder:text-base-content/40"
+ // Extra lines grow the field.
+ <InputGroup className="min-h-10 w-full lg:max-w-md lg:min-w-0 lg:flex-1">
+ <InputGroupAddon
+ className={rows > 1 ? "self-start pt-3" : undefined}
+ >
+ <Search />
+ </InputGroupAddon>
+ <InputGroupTextarea
+ className="min-h-0 leading-6 field-sizing-fixed"
rows={rows}
placeholder="Enter a keyword"
+ aria-label="Keywords"
+ aria-invalid={keywordError ? true : undefined}
value={field.state.value}
onChange={(event) => field.handleChange(event.target.value)}
onKeyDown={(event) => {
@@ -59,7 +69,7 @@ export function KeywordResearchSearchBar({ controller }: Props) {
}
}}
/>
- </label>
+ </InputGroup>
);
}}
</controlsForm.Field>
@@ -97,12 +107,13 @@ export function KeywordResearchSearchBar({ controller }: Props) {
<KeywordSearchOptions controller={controller} />
- <button
+ <Button
type="submit"
- className="btn btn-primary w-full px-6 lg:w-auto lg:shrink-0"
+ size="lg"
+ className="h-10 w-full px-6 lg:w-auto lg:shrink-0"
>
Search
- </button>
+ </Button>
</div>
</form>
<controlsForm.Field name="keyword">
@@ -110,7 +121,9 @@ export function KeywordResearchSearchBar({ controller }: Props) {
const keywordError = getFieldError(field.state.meta.errors);
return keywordError ? (
- <p className="text-sm text-error">{keywordError}</p>
+ <p role="alert" className="text-sm text-destructive">
+ {keywordError}
+ </p>
) : null;
}}
</controlsForm.Field>
@@ -122,23 +135,20 @@ export function KeywordResearchSearchBar({ controller }: Props) {
{([locationCode, locationName]) => (
<>
{isLabsLocationCode(locationCode) ? null : (
- <div
- className="flex items-start gap-2 rounded-lg border border-info/30 bg-info/10 px-3 py-2 text-sm text-base-content/80"
- role="status"
- >
- <Info className="mt-0.5 size-4 shrink-0 text-info" />
- <span>
+ <Alert variant="info" role="status">
+ <Info />
+ <AlertDescription>
Keyword data for this country comes from Google Ads — search
volume, CPC, and trends are available, but difficulty and
intent are not.
- </span>
- </div>
+ </AlertDescription>
+ </Alert>
)}
{locationName ? <LocalVolumeCostNote /> : null}
</>
)}
</controlsForm.Subscribe>
- </div>
- </div>
+ </CardContent>
+ </Card>
);
}
diff --git a/src/client/features/keywords/page/KeywordResearchTable.tsx b/src/client/features/keywords/page/KeywordResearchTable.tsx
index 4c33e91d..5bafc50c 100644
--- a/src/client/features/keywords/page/KeywordResearchTable.tsx
+++ b/src/client/features/keywords/page/KeywordResearchTable.tsx
@@ -4,23 +4,23 @@ import {
type ColumnDef,
type RowSelectionState,
} from "@tanstack/react-table";
-import { AppDataTable } from "@/client/components/table/AppDataTable";
+import type { ReactNode } from "react";
import {
+ DataTable,
makeSelectionColumn,
useDataTable,
useSelectionAnchor,
} from "@/client/components/table/DataTable";
import {
IntentBadge,
- SortHeader,
type SortDir,
type SortField,
} from "@/client/features/keywords/components";
+import { SortableHeader } from "@/client/components/table/SortableHeader";
import { ScoreBadge } from "@/client/components/table/ScoreBadge";
import { formatNumber } from "@/client/features/keywords/utils";
import type { KeywordResearchDisplayRow } from "@/client/features/keywords/groupSharedVolumeRows";
import type { KeywordResearchRow } from "@/types/keywords";
-import { EmptyFilterResults } from "./keywordResearchFilters";
type Props = {
filteredRows: KeywordResearchDisplayRow[];
@@ -30,8 +30,11 @@ type Props = {
sortDir: SortDir;
sortField: SortField;
toggleSort: (field: SortField) => void;
+ isFiltered: boolean;
resetFilters: () => void;
handleRowClick: (row: KeywordResearchRow) => void;
+ toolbar: ReactNode;
+ footer: ReactNode;
};
const keywordColumnHelper = createColumnHelper<KeywordResearchDisplayRow>();
@@ -44,8 +47,11 @@ export function KeywordResearchTable({
sortDir,
sortField,
toggleSort,
+ isFiltered,
resetFilters,
handleRowClick,
+ toolbar,
+ footer,
}: Props) {
const selectAnchorRef = useSelectionAnchor();
const rowSelection = useMemo<RowSelectionState>(
@@ -55,17 +61,19 @@ export function KeywordResearchTable({
) as RowSelectionState,
[selectedRows],
);
- const columns = useMemo<ColumnDef<KeywordResearchDisplayRow>[]>(
- () => [
+ const columns = useMemo<ColumnDef<KeywordResearchDisplayRow>[]>(() => {
+ // The controller sorts the rows, so each header reads and sets its sort.
+ const sortColumn = (field: SortField) => ({
+ getIsSorted: () => (field === sortField ? sortDir : false),
+ getToggleSortingHandler: () => () => toggleSort(field),
+ });
+ return [
makeSelectionColumn<KeywordResearchDisplayRow>(selectAnchorRef),
keywordColumnHelper.accessor("keyword", {
header: () => (
- <SortHeader
+ <SortableHeader
+ column={sortColumn("keyword")}
label="Keyword"
- field="keyword"
- current={sortField}
- dir={sortDir}
- onToggle={toggleSort}
className="min-w-48 md:min-w-0"
/>
),
@@ -85,20 +93,19 @@ export function KeywordResearchTable({
</span>
</div>
),
+ // From md, the keyword column takes the free width and truncates, so
+ // the metric columns stay in view.
meta: {
- headerClassName: "min-w-48 md:min-w-0",
- cellClassName: "min-w-48 md:min-w-0",
+ headerClassName: "min-w-48 md:w-full md:max-w-0 md:min-w-0",
+ cellClassName: "min-w-48 md:w-full md:max-w-0 md:min-w-0",
},
}),
keywordColumnHelper.accessor("searchVolume", {
header: () => (
- <SortHeader
+ <SortableHeader
+ column={sortColumn("searchVolume")}
label="Volume"
- field="searchVolume"
- current={sortField}
- dir={sortDir}
- onToggle={toggleSort}
- className="justify-end"
+ align="right"
/>
),
cell: ({ row, getValue }) =>
@@ -106,19 +113,16 @@ export function KeywordResearchTable({
meta: {
headerClassName: "text-right",
cellClassName:
- "whitespace-nowrap text-right tabular-nums text-base-content/70",
+ "whitespace-nowrap text-right tabular-nums text-muted-foreground",
},
}),
keywordColumnHelper.accessor("cpc", {
header: () => (
- <SortHeader
+ <SortableHeader
+ column={sortColumn("cpc")}
label="CPC"
helpText="Cost per click in USD."
- field="cpc"
- current={sortField}
- dir={sortDir}
- onToggle={toggleSort}
- className="justify-end"
+ align="right"
/>
),
cell: ({ row, getValue }) => {
@@ -129,19 +133,16 @@ export function KeywordResearchTable({
meta: {
headerClassName: "text-right",
cellClassName:
- "whitespace-nowrap text-right tabular-nums text-base-content/70",
+ "whitespace-nowrap text-right tabular-nums text-muted-foreground",
},
}),
keywordColumnHelper.accessor("competition", {
header: () => (
- <SortHeader
+ <SortableHeader
+ column={sortColumn("competition")}
label="Comp."
helpText="Paid-search competition from Google Ads (0-1): higher means more advertisers bidding."
- field="competition"
- current={sortField}
- dir={sortDir}
- onToggle={toggleSort}
- className="justify-end"
+ align="right"
/>
),
cell: ({ row, getValue }) => {
@@ -152,19 +153,16 @@ export function KeywordResearchTable({
meta: {
headerClassName: "text-right",
cellClassName:
- "whitespace-nowrap text-right tabular-nums text-base-content/70",
+ "whitespace-nowrap text-right tabular-nums text-muted-foreground",
},
}),
keywordColumnHelper.accessor("keywordDifficulty", {
header: () => (
- <SortHeader
+ <SortableHeader
+ column={sortColumn("keywordDifficulty")}
label="Score"
helpText="Organic ranking difficulty (0-100): higher means harder to reach Google's top 10."
- field="keywordDifficulty"
- current={sortField}
- dir={sortDir}
- onToggle={toggleSort}
- className="justify-end"
+ align="right"
/>
),
cell: ({ getValue }) => <ScoreBadge value={getValue()} />,
@@ -178,9 +176,8 @@ export function KeywordResearchTable({
cellClassName: "whitespace-nowrap text-center",
},
}),
- ],
- [selectAnchorRef, sortDir, sortField, toggleSort],
- );
+ ];
+ }, [selectAnchorRef, sortDir, sortField, toggleSort]);
const table = useDataTable({
data: filteredRows,
columns,
@@ -201,24 +198,15 @@ export function KeywordResearchTable({
});
return (
- <div className="flex-1 min-h-0">
- {filteredRows.length === 0 ? (
- <EmptyFilterResults resetFilters={resetFilters} />
- ) : (
- <AppDataTable
- table={table}
- className="table table-xs min-w-max md:w-full"
- wrapperClassName="h-full overflow-auto"
- getRowProps={(row) => ({
- className: `cursor-pointer border-b border-base-200 hover:bg-base-200/50 ${
- overviewKeyword?.keyword === row.original.keyword
- ? "bg-primary/5 border-l-2 border-l-primary"
- : ""
- }`,
- onClick: () => handleRowClick(row.original),
- })}
- />
- )}
- </div>
+ <DataTable
+ table={table}
+ toolbar={toolbar}
+ footer={footer}
+ empty={{ title: "No keywords" }}
+ isFiltered={isFiltered}
+ onClearFilters={resetFilters}
+ onRowClick={(row) => handleRowClick(row.original)}
+ activeRowId={overviewKeyword?.keyword}
+ />
);
}
diff --git a/src/client/features/keywords/page/KeywordSearchOptions.tsx b/src/client/features/keywords/page/KeywordSearchOptions.tsx
index c581eb26..63fb8562 100644
--- a/src/client/features/keywords/page/KeywordSearchOptions.tsx
+++ b/src/client/features/keywords/page/KeywordSearchOptions.tsx
@@ -53,15 +53,16 @@ export function KeywordSearchOptions({ controller }: Props) {
return (
<>
- <button
- type="button"
- className="btn w-full gap-2 border-base-300 bg-base-100 font-normal lg:w-auto lg:shrink-0"
+ <Button
+ variant="outline"
+ size="lg"
+ className="h-10 w-full font-normal lg:w-auto lg:shrink-0"
aria-haspopup="dialog"
onClick={() => setOpen(true)}
>
- <SlidersHorizontal className="size-4" />
+ <SlidersHorizontal data-icon="inline-start" />
Options
- </button>
+ </Button>
{open ? (
<FormDialog
diff --git a/src/client/features/keywords/page/keywordResearchFilters.tsx b/src/client/features/keywords/page/keywordResearchFilters.tsx
index 166adc5e..eecf7436 100644
--- a/src/client/features/keywords/page/keywordResearchFilters.tsx
+++ b/src/client/features/keywords/page/keywordResearchFilters.tsx
@@ -1,3 +1,9 @@
+import {
+ DataTableFilterGroup,
+ DataTableRangeFilter,
+} from "@/client/components/table/DataTableToolbar";
+import { Input } from "@/client/components/ui/input";
+import { Toggle } from "@/client/components/ui/toggle";
import {
KEYWORD_INTENT_ORDER,
parseIntentFilter,
@@ -6,55 +12,37 @@ import {
import { INTENT_LABELS } from "@/client/features/keywords/components/IntentBadge";
import type { KeywordResearchControllerState } from "./types";
-export function FilterIntentSelect({
- form,
-}: {
- form: KeywordResearchControllerState["filtersForm"];
-}) {
+type FiltersForm = KeywordResearchControllerState["filtersForm"];
+
+export function FilterIntentSelect({ form }: { form: FiltersForm }) {
return (
- <div
- role="group"
- aria-labelledby="keyword-intent-filter-label"
- className="rounded-lg border border-base-300 bg-base-100 p-2.5 space-y-2"
- >
- <p
- id="keyword-intent-filter-label"
- className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60"
- >
- Intent
- </p>
+ <DataTableFilterGroup label="Intent">
<form.Field name="intents">
{(field) => {
const selected = parseIntentFilter(field.state.value);
return (
<div className="flex flex-wrap gap-1.5">
- {KEYWORD_INTENT_ORDER.map((intent) => {
- const isActive = selected.includes(intent);
- return (
- <button
- key={intent}
- type="button"
- aria-pressed={isActive}
- className={`btn btn-xs ${
- isActive
- ? "btn-primary"
- : "btn-ghost border border-base-300"
- }`}
- onClick={() =>
- field.handleChange(
- toggleIntentFilter(field.state.value, intent),
- )
- }
- >
- {INTENT_LABELS[intent]}
- </button>
- );
- })}
+ {KEYWORD_INTENT_ORDER.map((intent) => (
+ <Toggle
+ key={intent}
+ variant="outline"
+ size="sm"
+ className="aria-pressed:border-primary aria-pressed:bg-primary/10 aria-pressed:text-primary"
+ pressed={selected.includes(intent)}
+ onPressedChange={() =>
+ field.handleChange(
+ toggleIntentFilter(field.state.value, intent),
+ )
+ }
+ >
+ {INTENT_LABELS[intent]}
+ </Toggle>
+ ))}
</div>
);
}}
</form.Field>
- </div>
+ </DataTableFilterGroup>
);
}
@@ -64,27 +52,25 @@ export function FilterTextInput({
label,
placeholder,
}: {
- form: KeywordResearchControllerState["filtersForm"];
+ form: FiltersForm;
name: "include" | "exclude";
label: string;
placeholder: string;
}) {
return (
- <label className="form-control gap-1.5">
- <span className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">
- {label}
- </span>
+ <DataTableFilterGroup label={label}>
<form.Field name={name}>
{(field) => (
- <input
- className="input input-bordered input-sm bg-base-100"
+ <Input
+ aria-label={label}
+ className="h-7"
placeholder={placeholder}
value={field.state.value}
onChange={(event) => field.handleChange(event.target.value)}
/>
)}
</form.Field>
- </label>
+ </DataTableFilterGroup>
);
}
@@ -95,75 +81,33 @@ export function FilterRangeInputs({
maxName,
step,
}: {
- form: KeywordResearchControllerState["filtersForm"];
+ form: FiltersForm;
title: string;
minName: "minVol" | "minCpc" | "minKd";
maxName: "maxVol" | "maxCpc" | "maxKd";
step?: string;
}) {
return (
- <div className="rounded-lg border border-base-300 bg-base-100 p-2.5 space-y-2">
- <p className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">
- {title}
- </p>
- <div className="grid grid-cols-2 gap-2">
- <CompactRangeInput
- form={form}
- name={minName}
- placeholder="Min"
- step={step}
- />
- <CompactRangeInput
- form={form}
- name={maxName}
- placeholder="Max"
- step={step}
- />
- </div>
- </div>
- );
-}
-
-function CompactRangeInput({
- form,
- name,
- placeholder,
- step,
-}: {
- form: KeywordResearchControllerState["filtersForm"];
- name: "minVol" | "maxVol" | "minCpc" | "maxCpc" | "minKd" | "maxKd";
- placeholder: string;
- step?: string;
-}) {
- return (
- <form.Field name={name}>
- {(field) => (
- <input
- className="input input-bordered input-xs bg-base-100"
- placeholder={placeholder}
- type="number"
- step={step}
- value={field.state.value}
- onChange={(event) => field.handleChange(event.target.value)}
- />
+ <form.Field name={minName}>
+ {(minField) => (
+ <form.Field name={maxName}>
+ {(maxField) => (
+ <DataTableRangeFilter
+ label={title}
+ min={{
+ step,
+ value: minField.state.value,
+ onChange: (event) => minField.handleChange(event.target.value),
+ }}
+ max={{
+ step,
+ value: maxField.state.value,
+ onChange: (event) => maxField.handleChange(event.target.value),
+ }}
+ />
+ )}
+ </form.Field>
)}
</form.Field>
);
}
-
-export function EmptyFilterResults({
- resetFilters,
-}: {
- resetFilters: () => void;
-}) {
- return (
- <div className="h-full flex flex-col items-center justify-center text-center px-4 text-base-content/50 gap-3">
- <p className="text-sm font-medium">
- No keywords match your current filters.
- </p>
- <button className="btn btn-ghost btn-sm" onClick={resetFilters}>
- Clear filters
- </button>
- </div>
- );
-}
diff --git a/src/client/features/keywords/state/useKeywordResearchController.ts b/src/client/features/keywords/state/useKeywordResearchController.ts
index 97e02cf5..27fb69af 100644
--- a/src/client/features/keywords/state/useKeywordResearchController.ts
+++ b/src/client/features/keywords/state/useKeywordResearchController.ts
@@ -288,6 +288,7 @@ export function useKeywordResearchController(
resetFilters,
retrySerp,
rows,
+ savePending: saveMutation.isPending,
searchedKeyword,
selectedRows,
selectedKeywordRows,