Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Port rank tracking to shadcn, with inline config form errors (EVE-315) (#759)
Carter Smithbf7e68d64a24
diff --git a/src/client/components/CountryCombobox.tsx b/src/client/components/CountryCombobox.tsxnew file mode 100644index 00000000..c288da60--- /dev/null+++ b/src/client/components/CountryCombobox.tsx@@ -0,0 +1,66 @@+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];++// Matches the start of the name or of any word in it, so "uni" finds United+// States, not Tunisia, and "united states" still finds United States.+function matchesCountry(option: LocationOption, query: string) {+ const needle = query.trim().toLowerCase();+ const label = option.label.toLowerCase();+ return (+ label.startsWith(needle) ||+ label.split(/[\s-]+/).some((word) => word.startsWith(needle)) ||+ option.shortLabel.toLowerCase().startsWith(needle)+ );+}++/** A searchable country picker. `value` is a DataForSEO location code. */+export function CountryCombobox({+ id,+ value,+ onChange,+}: {+ id?: string;+ value: number;+ onChange: (locationCode: number) => void;+}) {+ const country =+ LOCATION_OPTIONS.find((option) => option.code === value) ?? null;++ return (+ <Combobox+ items={LOCATION_OPTIONS}+ value={country}+ itemToStringLabel={(option) => option.label}+ autoHighlight+ filter={matchesCountry}+ onValueChange={(option) => {+ if (option) onChange(option.code);+ }}+ >+ <ComboboxInput+ id={id}+ className="w-full"+ placeholder="Search countries"+ />+ <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.tsxindex 233e7c5e..5eca6657 100644--- a/src/client/components/SerpLocationCombobox.tsx+++ b/src/client/components/SerpLocationCombobox.tsx@@ -1,21 +1,34 @@-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 { useEffect, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { MapPin } from "lucide-react";import { Badge } from "@/client/components/ui/badge";import {- InputGroup,- InputGroupAddon,- InputGroupInput,-} from "@/client/components/ui/input-group";+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ useComboboxAnchor,+} from "@/client/components/ui/combobox";+import { InputGroupAddon } from "@/client/components/ui/input-group";+import { Spinner } from "@/client/components/ui/spinner";+import { searchSerpLocations } from "@/serverFunctions/serp-locations";+import { formatLocationLabel } from "@/shared/keyword-locations";import type { SerpLocationResult } from "@/server/lib/dataforseo/serp-locations";+// The selected value is only a location name, so it has no type badge.+type LocationItem = Pick<SerpLocationResult, "locationName" | "displayLabel"> &+ Partial<Pick<SerpLocationResult, "locationType">>;+type Props = {value: string | undefined;onChange: (locationName: string | undefined) => void;/** ISO 3166-1 alpha-2 country code, e.g. "us". */countryCode: string;placeholder?: string;+ id?: string;+ invalid?: boolean;};function useDebounce<T>(value: T, delayMs: number): T {@@ -27,244 +40,97 @@ function useDebounce<T>(value: T, delayMs: number): T {return debounced;}+/** Searches the cities, counties and regions of one country. */export function SerpLocationCombobox({value,onChange,countryCode,placeholder = "Search cities...",+ id,+ invalid,}: Props) {- const selectedLabel = value ? formatLocationLabel(value) : "";- const [inputValue, setInputValue] = useState(selectedLabel);- const [results, setResults] = useState<SerpLocationResult[]>([]);- const [isLoading, setIsLoading] = useState(false);- const [isError, setIsError] = useState(false);- const [open, setOpen] = useState(false);- const [activeIndex, setActiveIndex] = useState(0);- const containerRef = useRef<HTMLDivElement>(null);- const listRef = useRef<HTMLUListElement>(null);- // The input shows the selection's label. Searching for that text again would- // reopen the list the selection just closed. A ref, so a new selection does- // not re-run the search for the text typed before it.- const selectedLabelRef = useRef(selectedLabel);- // Bumped by a pick or a blur, so a search still in flight cannot reopen the- // list the user just dismissed.- const searchGenerationRef = useRef(0);-- // Each keystroke makes a new query, so retyping a query the user dismissed- // before its debounce settled still starts a search.- const [editCount, setEditCount] = useState(0);- const query = useMemo(- () => ({ text: inputValue, editCount }),- [inputValue, editCount],- );- const debouncedQuery = useDebounce(query, 350);+ // The list lines up with the whole field, not only the text input.+ const anchor = useComboboxAnchor();+ const [query, setQuery] = useState("");+ const trimmed = query.trim();+ const debounced = useDebounce(trimmed, 350);- // Show the label of a value set from outside (a reset or a restored search).- useEffect(() => {- selectedLabelRef.current = selectedLabel;- setInputValue(selectedLabel);- if (!selectedLabel) {- setResults([]);- setOpen(false);- }- }, [selectedLabel]);+ const searchQuery = useQuery({+ queryKey: ["serpLocations", countryCode, debounced],+ queryFn: () =>+ searchSerpLocations({ data: { query: debounced, countryCode } }),+ enabled: debounced !== "",+ staleTime: 5 * 60 * 1000,+ });+ const searching =+ trimmed !== "" && (trimmed !== debounced || searchQuery.isFetching);+ // Only show matches for the text in the field right now.+ const results = searching || !trimmed ? [] : (searchQuery.data ?? []);- // Fetch results when debounced query changes- useEffect(() => {- const trimmed = debouncedQuery.text.trim();- if (!trimmed) {- setResults([]);- setOpen(false);- setIsLoading(false);- return;- }- if (trimmed === selectedLabelRef.current) {- // Any fetch this change superseded was cancelled before its own- // finally could clear the spinner, so clear it here.- setIsLoading(false);- return;- }- let cancelled = false;- const generation = searchGenerationRef.current;- const isStale = () =>- cancelled || generation !== searchGenerationRef.current;- setIsLoading(true);- setIsError(false);- searchSerpLocations({ data: { query: trimmed, countryCode } })- .then((data) => {- if (isStale()) return;- setResults(data);- setOpen(true);- setActiveIndex(0);- })- .catch(() => {- if (isStale()) return;- setIsError(true);- setOpen(true);- })- .finally(() => {- if (!isStale()) setIsLoading(false);- });- return () => {- cancelled = true;- };- }, [debouncedQuery, countryCode]);+ const selected: LocationItem | null = value+ ? { locationName: value, displayLabel: formatLocationLabel(value) }+ : null;- // Close on outside click- useEffect(() => {- if (!open) return;- const handlePointerDown = (e: PointerEvent) => {- if (- e.target instanceof Node &&- !containerRef.current?.contains(e.target)- ) {- setOpen(false);- }- };- document.addEventListener("pointerdown", handlePointerDown);- return () => document.removeEventListener("pointerdown", handlePointerDown);- }, [open]);-- // Scroll active item into view- useEffect(() => {- if (!open) return;- listRef.current?.children[activeIndex]?.scrollIntoView({- block: "nearest",- });- }, [activeIndex, open]);-- const dismissPendingSearch = () => {- searchGenerationRef.current += 1;- setIsLoading(false);- };-- const select = (loc: SerpLocationResult) => {- dismissPendingSearch();- onChange(loc.locationName);- setInputValue(loc.displayLabel);- setResults([]);- setOpen(false);- };-- const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {- const v = e.target.value;- setInputValue(v);- setEditCount((count) => count + 1);- if (!v.trim()) {- onChange(undefined);- }- };-- const handleKeyDown = (e: React.KeyboardEvent) => {- if (!open) {- // Text that is not a picked location must not submit the form with- // the previous selection: wait for the list, then pick a result.- const typed = inputValue.trim();- if (e.key === "Enter" && typed && typed !== selectedLabelRef.current) {- e.preventDefault();- }- return;- }- switch (e.key) {- case "ArrowDown":- e.preventDefault();- setActiveIndex((i) => Math.min(i + 1, results.length - 1));- break;- case "ArrowUp":- e.preventDefault();- setActiveIndex((i) => Math.max(i - 1, 0));- break;- case "Enter": {- e.preventDefault();- const loc = results[activeIndex];- if (loc) select(loc);- break;- }- case "Escape":- e.preventDefault();- setOpen(false);- break;- }- };+ const emptyMessage = !trimmed+ ? "Type a city, county, or region"+ : searching+ ? "Searching..."+ : searchQuery.isError+ ? "Unable to load locations"+ : `No locations found for "${trimmed}"`;return (- <div- ref={containerRef}- className="relative w-full"- onBlur={(e) => {- if (containerRef.current?.contains(e.relatedTarget)) return;- // Leaving without picking a result shows the selection again, so the- // field never names a place the form will not use.- dismissPendingSearch();- setInputValue(selectedLabelRef.current);- // The matches were for the abandoned text; focusing again must not- // offer them under the restored label.- setResults([]);- setOpen(false);+ <Combobox+ items={results}+ value={selected}+ // The server already matched the query.+ filter={null}+ itemToStringLabel={(item: LocationItem) => item.displayLabel}+ isItemEqualToValue={(item, current) =>+ item.locationName === current.locationName+ }+ onValueChange={(item) => {+ setQuery("");+ onChange(item?.locationName);+ }}+ // A closed list drops its search, so the next open starts fresh.+ onOpenChange={(open) => {+ if (!open) setQuery("");+ }}+ onInputValueChange={(text, { reason }) => {+ if (reason !== "input-change") return;+ setQuery(text);+ if (!text.trim()) onChange(undefined);}}>- <InputGroup className="h-10">- <InputGroupAddon>- {isLoading ? <Loader2 className="animate-spin" /> : <MapPin />}- </InputGroupAddon>- <InputGroupInput- type="text"+ <div ref={anchor}>+ <ComboboxInput+ id={id}+ aria-invalid={invalid || undefined}+ className="w-full"placeholder={placeholder}- value={inputValue}- onChange={handleInputChange}- onKeyDown={handleKeyDown}- onFocus={() => {- if (results.length > 0) setOpen(true);- }}- autoComplete="off"- />- </InputGroup>-- {open && (- <div- 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()}+ showTrigger={false}>- {isError ? (- <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-muted-foreground">- No locations found for "{debouncedQuery.text.trim()}"- </p>- ) : (- <ul- ref={listRef}- role="listbox"- className="max-h-56 w-full overflow-y-auto"- >- {results.map((loc, index) => (- <li- key={loc.locationCode}- role="option"- aria-selected={loc.locationName === value}- >- <button- type="button"- 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>- <Badge variant="secondary" size="sm">- {loc.locationType}- </Badge>- </button>- </li>- ))}- </ul>+ <InputGroupAddon align="inline-start">+ {searching ? <Spinner /> : <MapPin />}+ </InputGroupAddon>+ </ComboboxInput>+ </div>+ <ComboboxContent anchor={anchor}>+ <ComboboxEmpty>{emptyMessage}</ComboboxEmpty>+ <ComboboxList>+ {(item: LocationItem) => (+ <ComboboxItem key={item.locationName} value={item}>+ <span className="truncate">{item.displayLabel}</span>+ {item.locationType ? (+ <Badge variant="secondary" size="sm" className="ml-auto">+ {item.locationType}+ </Badge>+ ) : null}+ </ComboboxItem>)}- </div>- )}- </div>+ </ComboboxList>+ </ComboboxContent>+ </Combobox>);}diff --git a/src/client/components/table/DataTable.tsx b/src/client/components/table/DataTable.tsxindex c94faa1c..597eb879 100644--- a/src/client/components/table/DataTable.tsx+++ b/src/client/components/table/DataTable.tsx@@ -13,6 +13,7 @@ import {import {useRef,type ComponentProps,+ type MouseEvent,type MutableRefObject,type ReactNode,} from "react";@@ -157,6 +158,7 @@ export function DataTable<TData>({footer,onRowClick,activeRowId,+ scrollClassName,}: DataTableFrameProps & {table: TanStackTable<TData>;/** Shown when there are no rows and no filters. */@@ -165,9 +167,14 @@ export function DataTable<TData>({"kind" | "title" | "description" | "action">;/** Makes each row clickable, for example to open its details beside the table. */- onRowClick?: (row: Row<TData>) => void;+ onRowClick?: (+ row: Row<TData>,+ event: MouseEvent<HTMLTableRowElement>,+ ) => void;/** Highlights the row whose details are open. */activeRowId?: string;+ /** Caps the table height, for example `max-h-96`. The header stays in view while the rows scroll. */+ scrollClassName?: string;}) {const columns = table.getVisibleLeafColumns();const rows = table.getRowModel().rows;@@ -177,8 +184,12 @@ export function DataTable<TData>({{toolbar}{error ? <div className="p-4">{error}</div> : null}{error && !isLoading && rows.length === 0 ? null : (- <Table>- <TableHeader>+ <Table containerClassName={scrollClassName}>+ <TableHeader+ className={+ scrollClassName ? "sticky top-0 z-10 bg-card" : undefined+ }+ >{table.getHeaderGroups().map((headerGroup) => (<TableRow key={headerGroup.id} className="hover:bg-transparent">{headerGroup.headers.map((header) => (@@ -249,7 +260,9 @@ export function DataTable<TData>({? "cursor-pointer data-active:bg-primary/5 data-active:shadow-[inset_2px_0_0_var(--color-primary)]": undefined}- onClick={onRowClick ? () => onRowClick(row) : undefined}+ onClick={+ onRowClick ? (event) => onRowClick(row, event) : undefined+ }>{row.getVisibleCells().map((cell) => {const meta = cell.column.columnDef.meta?.cellClassName;diff --git a/src/client/components/ui/radio-group.tsx b/src/client/components/ui/radio-group.tsxnew file mode 100644index 00000000..5a2c7291--- /dev/null+++ b/src/client/components/ui/radio-group.tsx@@ -0,0 +1,35 @@+import { Radio as RadioPrimitive } from "@base-ui/react/radio";+import { RadioGroup as RadioGroupPrimitive } from "@base-ui/react/radio-group";+import { cn } from "cn";++function RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) {+ return (+ <RadioGroupPrimitive+ data-slot="radio-group"+ className={cn("grid w-full gap-2", className)}+ {...props}+ />+ );+}++function RadioGroupItem({ className, ...props }: RadioPrimitive.Root.Props) {+ return (+ <RadioPrimitive.Root+ data-slot="radio-group-item"+ className={cn(+ "group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",+ className,+ )}+ {...props}+ >+ <RadioPrimitive.Indicator+ data-slot="radio-group-indicator"+ className="flex size-4 items-center justify-center"+ >+ <span className="absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground" />+ </RadioPrimitive.Indicator>+ </RadioPrimitive.Root>+ );+}++export { RadioGroup, RadioGroupItem };diff --git a/src/client/components/ui/table.tsx b/src/client/components/ui/table.tsxindex d4256d84..5ebd4b5b 100644--- a/src/client/components/ui/table.tsx+++ b/src/client/components/ui/table.tsx@@ -5,11 +5,15 @@ import { cn } from "cn";// page background in the light theme, so it would not show on a card.// Cells wrap, because tables hold long URLs and titles.-function Table({ className, ...props }: React.ComponentProps<"table">) {+function Table({+ className,+ containerClassName,+ ...props+}: React.ComponentProps<"table"> & { containerClassName?: string }) {return (<divdata-slot="table-container"- className="relative w-full overflow-x-auto"+ className={cn("relative w-full overflow-x-auto", containerClassName)}><tabledata-slot="table"diff --git a/src/client/features/projects/ProjectMarketFields.tsx b/src/client/features/projects/ProjectMarketFields.tsxindex 8e91ba42..dee3feed 100644--- a/src/client/features/projects/ProjectMarketFields.tsx+++ b/src/client/features/projects/ProjectMarketFields.tsx@@ -1,12 +1,5 @@import { useId } from "react";-import {- Combobox,- ComboboxContent,- ComboboxEmpty,- ComboboxInput,- ComboboxItem,- ComboboxList,-} from "@/client/components/ui/combobox";+import { CountryCombobox } from "@/client/components/CountryCombobox";import { Field, FieldLabel } from "@/client/components/ui/field";import {Select,@@ -20,21 +13,6 @@ import {getLanguageOptions,} from "@/client/features/keywords/locations";import type { ProjectMarket } from "@/client/features/projects/types";-import { LOCATION_OPTIONS } from "@/shared/keyword-locations";--type LocationOption = (typeof LOCATION_OPTIONS)[number];--// Matches the start of the name or of any word in it, so "uni" finds United-// States, not Tunisia, and "united states" still finds United States.-function matchesCountry(option: LocationOption, query: string) {- const needle = query.trim().toLowerCase();- const label = option.label.toLowerCase();- return (- label.startsWith(needle) ||- label.split(/[\s-]+/).some((word) => word.startsWith(needle)) ||- option.shortLabel.toLowerCase().startsWith(needle)- );-}/*** The project's default market: country plus the language served for it.@@ -53,9 +31,6 @@ export function ProjectMarketFields({}) {const countryId = useId();const languageId = useId();- const country =- LOCATION_OPTIONS.find((option) => option.code === value.locationCode) ??- null;const languageItems = getLanguageOptions(value.locationCode).map((option) => ({ value: option.code, label: option.label }),);@@ -67,36 +42,16 @@ export function ProjectMarketFields({<div className="grid gap-4 sm:grid-cols-2"><Field><FieldLabel htmlFor={countryId}>Country</FieldLabel>- <Combobox- items={LOCATION_OPTIONS}- value={country}- itemToStringLabel={(option) => option.label}- autoHighlight- filter={matchesCountry}- onValueChange={(option) => {- if (!option) return;+ <CountryCombobox+ id={countryId}+ value={value.locationCode}+ onChange={(locationCode) =>onChange({- locationCode: option.code,- languageCode: getLanguageCode(option.code),- });- }}- >- <ComboboxInput- id={countryId}- className="w-full"- placeholder="Search countries"- />- <ComboboxContent>- <ComboboxEmpty>No countries match.</ComboboxEmpty>- <ComboboxList>- {(option: LocationOption) => (- <ComboboxItem key={option.code} value={option}>- {option.label}- </ComboboxItem>- )}- </ComboboxList>- </ComboboxContent>- </Combobox>+ locationCode,+ languageCode: getLanguageCode(locationCode),+ })+ }+ /></Field><FieldclassName={hideLanguageOnMobile ? "hidden sm:flex" : undefined}diff --git a/src/client/features/rank-tracking/AddKeywordsPanel.tsx b/src/client/features/rank-tracking/AddKeywordsPanel.tsxindex b797c0aa..328d5afd 100644--- a/src/client/features/rank-tracking/AddKeywordsPanel.tsx+++ b/src/client/features/rank-tracking/AddKeywordsPanel.tsx@@ -1,9 +1,12 @@-import { useState } from "react";+import { useId, useState } from "react";import { toast } from "sonner";import { useMutation } from "@tanstack/react-query";import { addTrackingKeywords } from "@/serverFunctions/rank-tracking";import { MAX_TRACKED_KEYWORD_LENGTH } from "@/shared/rank-tracking";-import { Loader2 } from "lucide-react";+import { Button } from "@/client/components/ui/button";+import { Checkbox } from "@/client/components/ui/checkbox";+import { Label } from "@/client/components/ui/label";+import { Textarea } from "@/client/components/ui/textarea";export function AddKeywordsPanel({configId,@@ -20,6 +23,7 @@ export function AddKeywordsPanel({}) => void;onCancel: () => void;}) {+ const matchCaseId = useId();const [keywordInput, setKeywordInput] = useState("");const [matchCase, setMatchCase] = useState(false);const mutation = useMutation({@@ -34,31 +38,35 @@ export function AddKeywordsPanel({});const isPending = mutation.isPending;return (- <div className="flex gap-2 items-end">- <div className="flex flex-col gap-1 flex-1">- <textarea- className="textarea textarea-bordered textarea-sm w-full"+ <div className="flex items-end gap-2">+ <div className="flex min-w-0 flex-1 flex-col gap-2">+ <Textarearows={3}+ // The field grows with its text; a long line must wrap, not widen the card.+ className="min-w-0"+ aria-label="Keywords to add"placeholder="Enter keywords, one per line"value={keywordInput}onChange={(e) => setKeywordInput(e.target.value)}/>- <label- className="flex items-center gap-2 text-xs cursor-pointer w-fit"+ <div+ className="flex w-fit items-center gap-2"title="Track these keywords exactly as typed instead of lowercasing them. Google can return different results for a capitalized brand name.">- <input- type="checkbox"- className="checkbox checkbox-xs [--radius-selector:0.25rem]"+ <Checkbox+ id={matchCaseId}checked={matchCase}- onChange={(e) => setMatchCase(e.target.checked)}+ onCheckedChange={(checked) => setMatchCase(checked)}/>- Match case- </label>+ <Label htmlFor={matchCaseId} className="text-xs font-normal">+ Match case+ </Label>+ </div></div><div className="flex flex-col gap-1">- <button- className="btn btn-primary btn-sm"+ <Button+ size="sm"+ pending={isPending}onClick={() => {const lines = keywordInput.split("\n")@@ -72,14 +80,13 @@ export function AddKeywordsPanel({}if (lines.length > 0) mutation.mutate(lines);}}- disabled={isPending || !keywordInput.trim()}+ disabled={!keywordInput.trim()}>- {isPending && <Loader2 className="size-3 animate-spin" />}Add- </button>- <button className="btn btn-ghost btn-sm" onClick={onCancel}>+ </Button>+ <Button variant="ghost" size="sm" onClick={onCancel}>Cancel- </button>+ </Button></div></div>);diff --git a/src/client/features/rank-tracking/CheckConfirmModal.tsx b/src/client/features/rank-tracking/CheckConfirmModal.tsxindex 09480a17..c7afdfcc 100644--- a/src/client/features/rank-tracking/CheckConfirmModal.tsx+++ b/src/client/features/rank-tracking/CheckConfirmModal.tsx@@ -1,5 +1,4 @@-import { Loader2, Zap } from "lucide-react";-import { Modal } from "@/client/components/Modal";+import { ConfirmDialog } from "@/client/components/ConfirmDialog";import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";import {devicesCount,@@ -28,49 +27,29 @@ export function CheckConfirmModal({const liveTime =Math.ceil(totalChecks / KEYWORDS_PER_BATCH) * SECONDS_PER_BATCH;+ const eta =+ liveTime < 60 ? `${liveTime}s` : `${Math.ceil(liveTime / 60)} min`;+return (- <Modal- maxWidth="max-w-md"+ <ConfirmDialog+ title={`Check ${keywordCount} keyword${keywordCount !== 1 ? "s" : ""}?`}+ confirmLabel="Run now"+ pending={isPending}+ onConfirm={onRunNow}onClose={onCancel}- labelledBy="rank-check-confirm-title">- <div>- <h3 id="rank-check-confirm-title" className="text-lg font-semibold">- Check {keywordCount} keyword- {keywordCount !== 1 ? "s" : ""}- </h3>- <p className="text-sm text-base-content/60 mt-1">- {keywordCount} keywords × {dc} device- {dc !== 1 ? "s" : ""} = {totalChecks} SERP checks- </p>- </div>-- <button- className="flex w-full items-center gap-4 rounded-xl border-2 border-base-300 p-4 text-left transition-colors hover:border-primary hover:bg-primary/5"- onClick={onRunNow}- disabled={isPending}- >- <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10">- <Zap className="size-5 text-primary" />- </div>- <div className="flex-1">- <p className="font-medium">Run Now</p>- <p className="text-xs text-base-content/60">- Results in ~- {liveTime < 60 ? `${liveTime}s` : `${Math.ceil(liveTime / 60)} min`}- </p>- </div>- <div className="text-right">- {costUsd != null && (- <p className="font-mono font-semibold">~${costUsd.toFixed(2)}</p>- )}- {isPending && <Loader2 className="size-3 animate-spin ml-auto" />}- </div>- </button>-- <button className="btn btn-ghost btn-sm self-center" onClick={onCancel}>- Cancel- </button>- </Modal>+ {keywordCount} keywords × {dc} device{dc !== 1 ? "s" : ""} ={" "}+ {totalChecks} SERP checks. Results in ~{eta}.+ {costUsd != null ? (+ <>+ {" "}+ Costs about{" "}+ <span className="font-mono font-semibold text-foreground">+ ${costUsd.toFixed(2)}+ </span>+ .+ </>+ ) : null}+ </ConfirmDialog>);}diff --git a/src/client/features/rank-tracking/FreePlanAlert.tsx b/src/client/features/rank-tracking/FreePlanAlert.tsxindex 34b940e3..9b5f8df1 100644--- a/src/client/features/rank-tracking/FreePlanAlert.tsx+++ b/src/client/features/rank-tracking/FreePlanAlert.tsx@@ -1,24 +1,27 @@import { Link } from "@tanstack/react-router";import { AlertTriangle } from "lucide-react";+import { Alert, AlertDescription } from "@/client/components/ui/alert";import { SUBSCRIBE_ROUTE } from "@/shared/billing";export function FreePlanAlert({ visible }: { visible: boolean }) {if (!visible) return null;return (- <div className="alert alert-warning text-sm py-2">- <AlertTriangle className="size-4" />- <span>- We only start to track keyword positions once you{" "}- <Link- to={SUBSCRIBE_ROUTE}- search={{ upgrade: true }}- className="link font-medium"- >- upgrade to the paid plan- </Link>- .- </span>- </div>+ <Alert variant="warning">+ <AlertTriangle />+ <AlertDescription className="text-foreground">+ <p>+ We only start to track keyword positions once you{" "}+ <Link+ to={SUBSCRIBE_ROUTE}+ search={{ upgrade: true }}+ className="font-medium underline underline-offset-3"+ >+ upgrade to the paid plan+ </Link>+ .+ </p>+ </AlertDescription>+ </Alert>);}diff --git a/src/client/features/rank-tracking/KeywordSuggestionStep.tsx b/src/client/features/rank-tracking/KeywordSuggestionStep.tsxindex 9d665ea4..2f5d13d3 100644--- a/src/client/features/rank-tracking/KeywordSuggestionStep.tsx+++ b/src/client/features/rank-tracking/KeywordSuggestionStep.tsx@@ -5,16 +5,23 @@ import {type RowSelectionState,type SortingState,} from "@tanstack/react-table";-import { Loader2, AlertCircle, X } from "lucide-react";import { toast } from "sonner";import { getDomainKeywordSuggestions } from "@/serverFunctions/domain";import { addTrackingKeywords } from "@/serverFunctions/rank-tracking";import { isLabsLocationCode } from "@/client/features/keywords/locations";-import { AppDataTable } from "@/client/components/table/AppDataTable";+import { Spinner } from "@/client/components/Spinner";import {+ DataTable,makeSelectionColumn,useDataTable,} from "@/client/components/table/DataTable";+import { Button } from "@/client/components/ui/button";+import {+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/client/components/ui/dialog";import { SortableHeader } from "@/client/components/table/SortableHeader";import { RANK_TRACKING_HEADER_CLASS } from "./RankTrackingColumns";import {@@ -64,7 +71,7 @@ const baseColumns: ColumnDef<SuggestedKeyword>[] = [return pos != null ? (pos) : (- <span className="text-base-content/40">—</span>+ <span className="text-muted-foreground">—</span>);},sortingFn: (rowA, rowB) => {@@ -89,7 +96,7 @@ const baseColumns: ColumnDef<SuggestedKeyword>[] = [return vol != null ? (vol.toLocaleString()) : (- <span className="text-base-content/40">—</span>+ <span className="text-muted-foreground">—</span>);},sortingFn: (rowA, rowB) => {@@ -114,7 +121,7 @@ const baseColumns: ColumnDef<SuggestedKeyword>[] = [return traffic != null ? (Math.round(traffic).toLocaleString()) : (- <span className="text-base-content/40">—</span>+ <span className="text-muted-foreground">—</span>);},sortingFn: (rowA, rowB) => {@@ -224,135 +231,112 @@ export function KeywordSuggestionStep({}};- const sectionHeader = (title: string) => (- <div className="flex items-center justify-between">- <h2 id="keyword-suggestions-title" className="text-lg font-semibold">- {title}- </h2>- <button className="btn btn-ghost btn-sm btn-square" onClick={onClose}>- <X className="size-4" />- </button>- </div>- );-if (!labsSupported) {return (<>- {sectionHeader("Add keywords manually")}- <div className="flex flex-col items-center justify-center gap-3 py-16">- <p className="text-xs text-base-content/50">- Ranked-keyword suggestions aren't available for this country.- Continue and add the keywords you want to track manually.- </p>- <button className="btn btn-primary btn-sm mt-2" onClick={onClose}>- Continue- </button>- </div>+ <StepHeader+ title="Add keywords manually"+ description="Ranked-keyword suggestions aren't available for this country. Continue and add the keywords you want to track manually."+ />+ <DialogFooter>+ <Button onClick={onClose}>Continue</Button>+ </DialogFooter></>);}- // Loading stateif (suggestionsQuery.isLoading) {return (<>- {sectionHeader("Finding your top keywords...")}- <div className="flex flex-col items-center justify-center gap-3 py-16">- <Loader2 className="size-8 animate-spin text-primary" />- <p className="text-xs text-base-content/50">- This usually takes a few seconds- </p>+ <StepHeader title="Finding your top keywords..." />+ <div className="flex flex-col items-center justify-center py-16">+ <Spinner label="This usually takes a few seconds" /></div></>);}- // Error stateif (suggestionsQuery.isError) {return (<>- {sectionHeader("Couldn't fetch keywords")}- <div className="flex flex-col items-center justify-center gap-3 py-16">- <AlertCircle className="size-8 text-error" />- <p className="text-xs text-base-content/50">- You can skip this step and add keywords manually later.- </p>- <div className="flex gap-2 mt-2">- <button className="btn btn-primary btn-sm" onClick={onClose}>- Skip- </button>- </div>- </div>+ <StepHeader+ title="Couldn't fetch keywords"+ description="You can skip this step and add keywords manually later."+ />+ <DialogFooter>+ <Button onClick={onClose}>Skip</Button>+ </DialogFooter></>);}- // Empty stateif (data.length === 0) {return (<>- {sectionHeader("No rankings found")}- <div className="flex flex-col items-center justify-center gap-3 py-16">- <p className="text-xs text-base-content/50">- We couldn't find any keywords {domain} currently ranks for. You can- add keywords manually.- </p>- <button className="btn btn-primary btn-sm mt-2" onClick={onClose}>- Skip- </button>- </div>+ <StepHeader+ title="No rankings found"+ description={`We couldn't find any keywords ${domain} currently ranks for. You can add keywords manually.`}+ />+ <DialogFooter>+ <Button onClick={onClose}>Skip</Button>+ </DialogFooter></>);}- // Data loadedreturn (- <div className="flex flex-col gap-3">- {sectionHeader("Choose keywords to track")}- <div className="flex items-center justify-between">- <p className="text-sm text-base-content/60">- We found {data.length} keywords {domain} ranks for.- </p>- </div>+ <>+ <StepHeader+ title="Choose keywords to track"+ description={`We found ${data.length} keywords ${domain} ranks for.`}+ />- <AppDataTable+ <DataTabletable={table}- className="table table-xs table-pin-rows w-full"- wrapperClassName="overflow-y-auto max-h-[400px] border border-base-300 rounded-lg"- stickyHeader- getRowProps={(row) => ({- className: "hover:bg-base-200/50 cursor-pointer",- onClick: (event) => {- if (applyShiftRangeSelection(event, row, table, selectAnchorRef)) {- return;- }-- row.toggleSelected();- },- })}+ empty={{ title: "No keywords" }}+ scrollClassName="max-h-[400px]"+ onRowClick={(row, event) => {+ if (applyShiftRangeSelection(event, row, table, selectAnchorRef)) {+ return;+ }+ row.toggleSelected();+ }}/>- <div className="flex items-center justify-between gap-3 pt-1">- <p className="text-xs text-base-content/60">+ <DialogFooter className="items-center sm:justify-between">+ <p className="text-xs text-muted-foreground">{selectedCount} of {data.length} selected</p><div className="flex items-center gap-2">- <button className="btn btn-ghost btn-sm" onClick={onClose}>+ <Button variant="ghost" onClick={onClose}>Skip- </button>- <button- type="button"- className="btn btn-primary btn-sm"+ </Button>+ <ButtononClick={handleAdd}- disabled={addMutation.isPending || selectedCount === 0}+ pending={addMutation.isPending}+ disabled={selectedCount === 0}>- {addMutation.isPending && (- <Loader2 className="size-3.5 animate-spin" />- )}Save Keyword{selectedCount !== 1 ? "s" : ""}- </button>+ </Button></div>- </div>- </div>+ </DialogFooter>+ </>+ );+}++function StepHeader({+ title,+ description,+}: {+ title: string;+ description?: string;+}) {+ return (+ <DialogHeader>+ <DialogTitle>{title}</DialogTitle>+ {description ? (+ <DialogDescription>{description}</DialogDescription>+ ) : null}+ </DialogHeader>);}diff --git a/src/client/features/rank-tracking/KeywordTrendModal.tsx b/src/client/features/rank-tracking/KeywordTrendModal.tsxindex 4cdb3a3e..a7486281 100644--- a/src/client/features/rank-tracking/KeywordTrendModal.tsx+++ b/src/client/features/rank-tracking/KeywordTrendModal.tsx@@ -1,10 +1,27 @@import { useMemo, useState } from "react";-import { Copy, Download, Loader2 } from "lucide-react";+import { Copy, Download } from "lucide-react";import { reverse, sortBy } from "remeda";import { toast } from "sonner";import { useQuery } from "@tanstack/react-query";-import { Modal } from "@/client/components/Modal";import { QueryState } from "@/client/components/QueryState";+import { PageLoading } from "@/client/components/Spinner";+import { Button } from "@/client/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/client/components/ui/dialog";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/client/components/ui/table";import { buildCsv, type CsvValue } from "@/client/lib/csv";import { exportRows } from "@/client/lib/exportRows";import { captureClientEvent } from "@/client/lib/posthog";@@ -15,6 +32,7 @@ import { formatLocationLabel } from "@/shared/keyword-locations";import { csvChange, DeviceRankCell } from "./RankTrackingTableParts";import {RankTrendChart,+ TrendEmptyState,TrendRangeToggle,type TrendSeries,} from "./RankTrackingTrendChart";@@ -136,175 +154,152 @@ export function KeywordTrendModal({};return (- <Modal- onClose={onClose}- labelledBy="keyword-trend-title"- maxWidth="max-w-3xl"+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}>- <div className="flex items-start justify-between gap-3">- <div>- <h3 id="keyword-trend-title" className="text-lg font-semibold">- {target.keyword}- </h3>- <p className="text-xs text-base-content/60">- {domain} ·{" "}- {locationName- ? formatLocationLabel(locationName, 2)- : (LOCATIONS[locationCode] ?? "US")}{" "}- · Position over time- </p>- </div>- <TrendRangeToggle value={sinceDays} onChange={setSinceDays} />- </div>-- <QueryState- query={historyQuery}- errorFallback="Failed to load keyword history"- loading={- <div className="flex items-center justify-center py-16">- <Loader2 className="size-5 animate-spin text-base-content/50" />+ <DialogContent showCloseButton={false} className="sm:max-w-3xl">+ <DialogHeader className="flex-row items-start justify-between gap-3">+ <div className="space-y-1">+ <DialogTitle>{target.keyword}</DialogTitle>+ <DialogDescription className="text-xs">+ {domain} ·{" "}+ {locationName+ ? formatLocationLabel(locationName, 2)+ : (LOCATIONS[locationCode] ?? "US")}{" "}+ · Position over time+ </DialogDescription></div>- }- >- {() =>- maxPerDevice <= 1 ? (- <EmptyState count={maxPerDevice} />- ) : (- <>- <RankTrendChart- data={chartData}- series={series}- serpDepth={serpDepth}- showBottomBand- valueFormatter={(value, item) => {- // The payload is the chart row, typed `any` upstream.- const row: unknown = item.payload;- const checkedAt =- typeof row === "object" &&- row !== null &&- "checkedAt" in row- ? row.checkedAt- : undefined;- return typeof checkedAt === "number" &&- typeof item.dataKey === "string" &&- bottomBandKeys.has(`${checkedAt}:${item.dataKey}`) ? (- <span className="font-normal text-muted-foreground">- Not in top {serpDepth}- </span>- ) : (- String(value)- );- }}- />+ <TrendRangeToggle value={sinceDays} onChange={setSinceDays} />+ </DialogHeader>- <div className="flex items-center justify-end gap-2">- <button- className="btn btn-ghost btn-xs gap-1"- onClick={handleCopy}- >- <Copy className="size-3.5" />- Copy- </button>- <button- className="btn btn-ghost btn-xs gap-1"- onClick={handleExport}- >- <Download className="size-3.5" />- Export CSV- </button>- </div>+ <QueryState+ query={historyQuery}+ errorFallback="Failed to load keyword history"+ loading={<PageLoading />}+ >+ {() =>+ maxPerDevice <= 1 ? (+ <TrendEmptyState checks={maxPerDevice} />+ ) : (+ <>+ <RankTrendChart+ data={chartData}+ series={series}+ serpDepth={serpDepth}+ showBottomBand+ valueFormatter={(value, item) => {+ // The payload is the chart row, typed `any` upstream.+ const row: unknown = item.payload;+ const checkedAt =+ typeof row === "object" &&+ row !== null &&+ "checkedAt" in row+ ? row.checkedAt+ : undefined;+ return typeof checkedAt === "number" &&+ typeof item.dataKey === "string" &&+ bottomBandKeys.has(`${checkedAt}:${item.dataKey}`) ? (+ <span className="font-normal text-muted-foreground">+ Not in top {serpDepth}+ </span>+ ) : (+ String(value)+ );+ }}+ />- <div className="max-h-64 overflow-auto rounded-lg border border-base-300">- <table className="table table-sm">- <thead className="sticky top-0 bg-base-100">- <tr>- <th>Date</th>- {devices.length > 1 && <th>Device</th>}- <th>Position</th>- <th>Δ vs previous check</th>- </tr>- </thead>- <tbody>- {historyRows.map((r, idx) => {- // No prior ranking to compare against (first check, or the- // previous check was unranked): show the lone position as a- // centered neutral pill so it doesn't look like a stray number- // next to the "before → after" rows.- const noPrevious =- r.position !== null && r.previousPosition === null;- return (- <tr key={`${r.device}-${r.checkedAt}-${idx}`}>- <td className="whitespace-nowrap text-xs">- {new Date(r.checkedAt).toLocaleDateString()}- </td>- {devices.length > 1 && (- <td className="text-xs">- {DEVICE_STYLE[r.device].label}- </td>- )}- <td>- {r.position === null ? (- <span className="text-base-content/40 text-xs">- Not in top {serpDepth}- </span>- ) : (- <span className="font-mono text-sm">- {r.position}- </span>+ <div className="flex items-center justify-end gap-2">+ <Button variant="ghost" size="xs" onClick={handleCopy}>+ <Copy data-icon="inline-start" />+ Copy+ </Button>+ <Button variant="ghost" size="xs" onClick={handleExport}>+ <Download data-icon="inline-start" />+ Export CSV+ </Button>+ </div>++ <div className="overflow-hidden rounded-lg border border-border">+ <Table containerClassName="max-h-64">+ <TableHeader className="sticky top-0 z-10 bg-popover">+ <TableRow className="hover:bg-transparent">+ <TableHead>Date</TableHead>+ {devices.length > 1 && <TableHead>Device</TableHead>}+ <TableHead>Position</TableHead>+ <TableHead>Δ vs previous check</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {historyRows.map((r, idx) => {+ // No prior ranking to compare against (first check, or the+ // previous check was unranked): show the lone position as a+ // centered neutral pill so it doesn't look like a stray number+ // next to the "before → after" rows.+ const noPrevious =+ r.position !== null && r.previousPosition === null;+ return (+ <TableRow key={`${r.device}-${r.checkedAt}-${idx}`}>+ <TableCell className="text-xs whitespace-nowrap">+ {new Date(r.checkedAt).toLocaleDateString()}+ </TableCell>+ {devices.length > 1 && (+ <TableCell className="text-xs">+ {DEVICE_STYLE[r.device].label}+ </TableCell>)}- </td>- <td>- {noPrevious ? (- // Invisible placeholders matching the "before → after"- // layout so the lone pill lines up under the position- // badge column instead of floating.- <span className="inline-flex items-center gap-1.5">- <span className="w-6" aria-hidden />- <span aria-hidden className="opacity-0">- →+ <TableCell>+ {r.position === null ? (+ <span className="text-xs text-muted-foreground">+ Not in top {serpDepth}</span>- <span className="font-mono rounded bg-base-200 px-1.5 py-0.5 text-xs font-semibold text-base-content/70">+ ) : (+ <span className="font-mono text-sm">{r.position}</span>- </span>- ) : (- <DeviceRankCell- result={{- position: r.position,- previousPosition: r.previousPosition,- rankingUrl: null,- serpFeatures: [],- }}- />- )}- </td>- </tr>- );- })}- </tbody>- </table>- </div>- </>- )- }- </QueryState>-- <div className="flex justify-end">- <button className="btn btn-ghost btn-sm" onClick={onClose}>- Close- </button>- </div>- </Modal>- );-}+ )}+ </TableCell>+ <TableCell>+ {noPrevious ? (+ // Invisible placeholders matching the "before → after"+ // layout so the lone pill lines up under the position+ // badge column instead of floating.+ <span className="inline-flex items-center gap-1.5">+ <span className="w-6" aria-hidden />+ <span aria-hidden className="opacity-0">+ →+ </span>+ <span className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs font-semibold text-muted-foreground">+ {r.position}+ </span>+ </span>+ ) : (+ <DeviceRankCell+ result={{+ position: r.position,+ previousPosition: r.previousPosition,+ rankingUrl: null,+ serpFeatures: [],+ }}+ />+ )}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ </>+ )+ }+ </QueryState>-function EmptyState({ count }: { count: number }) {- return (- <div className="rounded-lg border border-dashed border-base-300 p-10 text-center text-sm text-base-content/60">- {count === 0- ? "No history yet — run a check to start tracking position over time."- : "Only 1 check so far — the trend chart fills in after the next check."}- </div>+ <DialogFooter showCloseButton />+ </DialogContent>+ </Dialog>);}diff --git a/src/client/features/rank-tracking/RankTrackingColumns.tsx b/src/client/features/rank-tracking/RankTrackingColumns.tsxindex 63e0393b..03329f43 100644--- a/src/client/features/rank-tracking/RankTrackingColumns.tsx+++ b/src/client/features/rank-tracking/RankTrackingColumns.tsx@@ -2,6 +2,7 @@ import { useMemo, type MutableRefObject } from "react";import type { ColumnDef } from "@tanstack/react-table";import { makeSelectionColumn } from "@/client/components/table/DataTable";import { ScoreBadge } from "@/client/components/table/ScoreBadge";+import { Badge } from "@/client/components/ui/badge";import { SortableHeader } from "@/client/components/table/SortableHeader";import type { RankTrackingRow } from "@/types/schemas/rank-tracking";import { formatLocationLabel } from "@/shared/keyword-locations";@@ -15,7 +16,7 @@ import {import type { SelectionAnchor } from "@/client/components/table/tableSelection";export const RANK_TRACKING_HEADER_CLASS =- "text-xs uppercase tracking-wide text-base-content/60";+ "text-xs uppercase tracking-wide text-muted-foreground";const HEADER_TOOLTIPS: Record<string, string> = {keyword: "The search term being tracked in Google",@@ -111,19 +112,21 @@ function makeKeywordColumn(<div className="flex items-center gap-1.5"><buttontype="button"- className="font-medium text-left link link-hover decoration-dotted underline-offset-2"+ className="text-left font-medium decoration-dotted underline-offset-2 hover:underline"onClick={() => onKeywordClick(row.original)}title="View position history">{row.original.keyword}</button>{row.original.matchCase && (- <span- className="badge badge-xs cursor-help bg-base-300 border-0 text-base-content/70"+ <Badge+ variant="secondary"+ size="sm"+ className="cursor-help"title="Tracked exactly as typed, not lowercased">Aa- </span>+ </Badge>)}</div>),@@ -162,7 +165,7 @@ function makeUrlColumn(enableSorting: false,header: () => (<span- className="text-xs uppercase tracking-wide font-medium text-base-content/60 cursor-help"+ className="cursor-help text-xs font-medium tracking-wide uppercase text-muted-foreground"title={HEADER_TOOLTIPS.url}>URL@@ -183,7 +186,7 @@ function makeSerpColumn(enableSorting: false,header: () => (<span- className="text-xs uppercase tracking-wide font-medium text-base-content/60 cursor-help"+ className="cursor-help text-xs font-medium tracking-wide uppercase text-muted-foreground"title={HEADER_TOOLTIPS.serp}>SERP Featuresdiff --git a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx b/src/client/features/rank-tracking/RankTrackingConfigModal.tsxindex 32f431e7..070b45c7 100644--- a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx+++ b/src/client/features/rank-tracking/RankTrackingConfigModal.tsx@@ -1,33 +1,43 @@-import { useMemo, useState } from "react";+import { useId, useState } from "react";import { projectsQueryOptions } from "@/client/features/projects/projectQueries";import { useQuery } from "@tanstack/react-query";-import { toast } from "sonner";-import { Info, Loader2, X } from "lucide-react";-import { Modal } from "@/client/components/Modal";+import { revalidateLogic, useStore } from "@tanstack/react-form";+import { Info } from "lucide-react";+import { useAppForm } from "@/client/components/form/useAppForm";+import { CountryCombobox } from "@/client/components/CountryCombobox";+import { Button } from "@/client/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/client/components/ui/dialog";+import { Field, FieldLabel } from "@/client/components/ui/field";import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";import { domainField, normalizeDomain } from "@/types/schemas/domain";-import {- depthToPages,- pagesToDepth,- estimateRankCheckCredits,-} from "@/shared/rank-tracking";+import { pagesToDepth, estimateRankCheckCredits } from "@/shared/rank-tracking";import { getLanguageCode } from "@/client/features/keywords/locations";import {SERP_LANGUAGE_OPTIONS,getIsoCountryCode,} from "@/shared/keyword-locations";-import { LocationSelect } from "@/client/components/LocationSelect";import type { ProjectMarket } from "@/client/features/projects/types";import { QueryError } from "@/client/components/QueryState";import { Spinner } from "@/client/components/Spinner";+import { getFieldError } from "@/client/lib/forms";import { SearchTargetingField } from "./SearchTargetingField";import { KeywordSuggestionStep } from "./KeywordSuggestionStep";-import { useSaveConfigMutations } from "./useSaveConfigMutations";+import {+ useSaveConfigMutations,+ type SaveConfigInput,+} from "./useSaveConfigMutations";import { ScheduleField } from "./ScheduleField";import {localScheduleTimeFrom,randomScheduleDate,withBrowserTimeZone,+ type LocalScheduleTime,} from "./scheduleTime";type Props = {@@ -38,6 +48,41 @@ type Props = {onConfigCreated?: () => void;};+type ConfigFormValues = Omit<SaveConfigInput, "scheduleTime"> & {+ scheduleTime: LocalScheduleTime;+};++const LANGUAGE_ITEMS = SERP_LANGUAGE_OPTIONS.map((language) => ({+ value: language.code,+ label: language.label,+}));++const DEVICE_ITEMS: { value: SaveConfigInput["devices"]; label: string }[] = [+ { value: "both", label: "Desktop + Mobile" },+ { value: "desktop", label: "Desktop only" },+ { value: "mobile", label: "Mobile only" },+];++const DEPTH_ITEMS = Array.from({ length: 10 }, (_, i) => i + 1).map(+ (pages) => ({+ value: pagesToDepth(pages),+ label: `${pages} ${pages === 1 ? "page" : "pages"} (top ${pages * 10} results)`,+ }),+);++function validateConfig(values: ConfigFormValues) {+ const fields: Partial<Record<keyof ConfigFormValues, string>> = {};+ if (!values.domain.trim()) {+ fields.domain = "Enter a domain";+ } else if (!domainField.safeParse(values.domain).success) {+ fields.domain = "Enter a valid domain, like example.com";+ }+ if (values.targetingMode === "local" && !values.locationName) {+ fields.locationName = "Select a city or region for local targeting";+ }+ return Object.keys(fields).length > 0 ? { fields } : undefined;+}+export function RankTrackingConfigModal({projectId,existingConfig,@@ -56,27 +101,30 @@ export function RankTrackingConfigModal({if (!initialMarket) {return (- <Modal- maxWidth="max-w-lg"- onClose={onClose}- labelledBy="rank-config-modal-title"+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}>- <h2 id="rank-config-modal-title" className="sr-only">- Add Domain- </h2>- <div className="flex min-h-40 items-center justify-center">- {projectsQuery.isPending ? (- <Spinner />- ) : (- <QueryError- error={projectsQuery.error}- fallback="Failed to load the project."- onRetry={() => void projectsQuery.refetch()}- isRetrying={projectsQuery.isFetching}- />- )}- </div>- </Modal>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle className="sr-only">Add Domain</DialogTitle>+ </DialogHeader>+ <div className="flex min-h-40 items-center justify-center">+ {projectsQuery.isPending ? (+ <Spinner />+ ) : (+ <QueryError+ error={projectsQuery.error}+ fallback="Failed to load the project."+ onRetry={() => void projectsQuery.refetch()}+ isRetrying={projectsQuery.isFetching}+ />+ )}+ </div>+ </DialogContent>+ </Dialog>);}@@ -100,316 +148,265 @@ function RankTrackingConfigModalContent({onSaved,onConfigCreated,}: Props & { initialMarket: ProjectMarket }) {+ const countryId = useId();const isEdit = !!existingConfig;- const [step, setStep] = useState<"config" | "keywords">("config");- const [domain, setDomain] = useState(existingConfig?.domain ?? "");- const [devices, setDevices] = useState<"both" | "desktop" | "mobile">(- existingConfig?.devices ?? "mobile",- );- const [locationCode, setLocationCode] = useState(- existingConfig?.locationCode ?? initialMarket.locationCode,- );- const [languageCode, setLanguageCode] = useState(- existingConfig?.languageCode ?? initialMarket.languageCode,- );- const [serpDepth, setSerpDepth] = useState(existingConfig?.serpDepth ?? 40);- const [schedule, setSchedule] = useState<- RankTrackingConfig["scheduleInterval"]- >(existingConfig?.scheduleInterval ?? "weekly");- const [targetingMode, setTargetingMode] = useState<"national" | "local">(- existingConfig?.locationName ? "local" : "national",- );- const [locationName, setLocationName] = useState<string | undefined>(- existingConfig?.locationName ?? undefined,- );- const [createdConfigId, setCreatedConfigId] = useState<string | null>(null);- // Shown and edited in the browser's timezone; the server converts it to UTC.- const [scheduleTime, setScheduleTime] = useState(() =>- localScheduleTimeFrom(- existingConfig?.nextCheckAt- ? new Date(existingConfig.nextCheckAt)- : randomScheduleDate(),- ),- );- const [scheduleTimeEdited, setScheduleTimeEdited] = useState(false);+ const [createdConfigId, setCreatedConfigId] = useState<string>();// An untouched edit leaves the stored run time alone; anything that changes// the schedule sends the time on screen so it is the one that gets saved.- const sendScheduleTime =- schedule !== "manual" &&- (!existingConfig ||- scheduleTimeEdited ||- schedule !== existingConfig.scheduleInterval);-- const selectedCountryCode = useMemo(- () => getIsoCountryCode(locationCode),- [locationCode],- );+ const [scheduleTimeEdited, setScheduleTimeEdited] = useState(false);const { createMutation, updateMutation } = useSaveConfigMutations({projectId,existingConfig,- fields: {- devices,- serpDepth,- locationCode,- languageCode,- targetingMode,- locationName,- schedule,- scheduleTime: sendScheduleTime- ? withBrowserTimeZone(scheduleTime)- : undefined,- },onCreated: (configId) => {setCreatedConfigId(configId);onConfigCreated?.();- setStep("keywords");},onUpdated: () => onSaved(),});- const handleSubmit = (e: React.FormEvent) => {- e.preventDefault();- if (isPending) return;- if (targetingMode === "local" && !locationName) {- toast.error("Please select a city or region for local targeting");- return;- }- const parsedDomain = domainField.safeParse(domain);- if (!parsedDomain.success) {- toast.error("Please enter a valid domain");- return;- }- setDomain(parsedDomain.data);- if (isEdit) {- updateMutation.mutate(parsedDomain.data);- } else {- createMutation.mutate(parsedDomain.data);- }- };-- const handleDomainBlur = () => {- try {- setDomain(normalizeDomain(domain));- } catch {- // Keep invalid partial input editable; submit validation will show the error.- }- };-- const isPending = createMutation.isPending || updateMutation.isPending;+ // Built once: the schedule default is random, and new default values would+ // reset the form on every render.+ const [defaultValues] = useState<ConfigFormValues>(() => ({+ domain: existingConfig?.domain ?? "",+ locationCode: existingConfig?.locationCode ?? initialMarket.locationCode,+ languageCode: existingConfig?.languageCode ?? initialMarket.languageCode,+ targetingMode: existingConfig?.locationName ? "local" : "national",+ locationName: existingConfig?.locationName ?? undefined,+ devices: existingConfig?.devices ?? "mobile",+ schedule: existingConfig?.scheduleInterval ?? "weekly",+ // Shown and edited in the browser's timezone; the server converts it to UTC.+ scheduleTime: localScheduleTimeFrom(+ existingConfig?.nextCheckAt+ ? new Date(existingConfig.nextCheckAt)+ : randomScheduleDate(),+ ),+ serpDepth: existingConfig?.serpDepth ?? 40,+ }));- if (step === "keywords" && createdConfigId) {- const closeKeywordStep = () => onSaved(createdConfigId);+ const form = useAppForm({+ defaultValues,+ validationLogic: revalidateLogic(),+ validators: { onDynamic: ({ value }) => validateConfig(value) },+ onSubmit: async ({ value, formApi }) => {+ const domain = domainField.parse(value.domain);+ formApi.setFieldValue("domain", domain);+ const sendScheduleTime =+ value.schedule !== "manual" &&+ (!existingConfig ||+ scheduleTimeEdited ||+ value.schedule !== existingConfig.scheduleInterval);+ const input: SaveConfigInput = {+ ...value,+ domain,+ scheduleTime: sendScheduleTime+ ? withBrowserTimeZone(value.scheduleTime)+ : undefined,+ };+ await (isEdit+ ? updateMutation.mutateAsync(input)+ : createMutation.mutateAsync(input));+ },+ });+ const values = useStore(form.store, (state) => state.values);+ const isSubmitting = useStore(form.store, (state) => state.isSubmitting);- return (- <Modal- maxWidth="max-w-3xl"- onClose={closeKeywordStep}- labelledBy="keyword-suggestions-title"- >- <KeywordSuggestionStep- configId={createdConfigId}- projectId={projectId}- domain={domain}- locationCode={locationCode}- onDone={(id) => onSaved(id)}- onClose={closeKeywordStep}- />- </Modal>- );- }+ const closeKeywordStep = () => onSaved(createdConfigId);return (- <Modal- maxWidth="max-w-lg"- onClose={onClose}- labelledBy="rank-config-modal-title"+ <Dialog+ open+ onOpenChange={(open) => {+ if (open || isSubmitting) return;+ if (createdConfigId) closeKeywordStep();+ else onClose();+ }}>- <div className="flex items-center justify-between">- <h2 id="rank-config-modal-title" className="text-lg font-semibold">- {isEdit ? "Edit Domain Config" : "Add Domain"}- </h2>- <button className="btn btn-ghost btn-sm btn-square" onClick={onClose}>- <X className="size-4" />- </button>- </div>-- <form onSubmit={handleSubmit} className="flex flex-col gap-4">- <div className="form-control">- <label className="label">- <span className="label-text font-medium">Target Domain</span>- </label>- <input- type="text"- placeholder="example.com"- className="input input-bordered w-full"- value={domain}- onChange={(e) => setDomain(e.target.value)}- onBlur={handleDomainBlur}+ <DialogContent+ showCloseButton={!!createdConfigId}+ className={createdConfigId ? "sm:max-w-3xl" : "sm:max-w-lg"}+ >+ {createdConfigId ? (+ <KeywordSuggestionStep+ configId={createdConfigId}+ projectId={projectId}+ domain={values.domain}+ locationCode={values.locationCode}+ onDone={onSaved}+ onClose={closeKeywordStep}/>- </div>+ ) : (+ <form.AppForm>+ <form.Form className="flex flex-col gap-4">+ <DialogHeader>+ <DialogTitle>+ {isEdit ? "Edit Domain Config" : "Add Domain"}+ </DialogTitle>+ </DialogHeader>- <div className="form-control">- <label className="label">- <span className="label-text font-medium">Country</span>- </label>- <LocationSelect- value={locationCode}- onChange={(newLocationCode) => {- setLocationCode(newLocationCode);- setLanguageCode(getLanguageCode(newLocationCode));- // A picked city belongs to the previous country.- setLocationName(undefined);- }}- />- </div>+ <form.AppField+ name="domain"+ listeners={{+ onBlur: ({ value }) => {+ try {+ form.setFieldValue("domain", normalizeDomain(value), {+ dontValidate: true,+ });+ } catch {+ // Keep invalid partial input editable; submit shows the error.+ }+ },+ }}+ >+ {(field) => (+ <field.TextField+ label="Target Domain"+ placeholder="example.com"+ />+ )}+ </form.AppField>- <SearchTargetingField- mode={targetingMode}- onModeChange={setTargetingMode}- locationName={locationName}- onLocationNameChange={setLocationName}- countryCode={selectedCountryCode}- />+ <Field>+ <FieldLabel htmlFor={countryId}>Country</FieldLabel>+ <CountryCombobox+ id={countryId}+ value={values.locationCode}+ onChange={(locationCode) => {+ form.setFieldValue("locationCode", locationCode);+ form.setFieldValue(+ "languageCode",+ getLanguageCode(locationCode),+ );+ // A picked city belongs to the previous country.+ form.setFieldValue("locationName", undefined);+ }}+ />+ </Field>- <div className="form-control">- <label className="label">- <span className="label-text font-medium">Language</span>- </label>- <select- className="select select-bordered w-full"- value={languageCode}- onChange={(e) => setLanguageCode(e.target.value)}- >- {SERP_LANGUAGE_OPTIONS.map((language) => (- <option key={language.code} value={language.code}>- {language.label}- </option>- ))}- </select>- <div className="mt-1.5 text-xs text-base-content/50">- Defaults to the country's language. Any language can be tracked in- any country — pick the one your customers search in.- </div>- </div>+ <form.Field name="locationName">+ {(field) => (+ <SearchTargetingField+ mode={values.targetingMode}+ onModeChange={(mode) =>+ form.setFieldValue("targetingMode", mode)+ }+ locationName={field.state.value}+ onLocationNameChange={field.handleChange}+ countryCode={getIsoCountryCode(values.locationCode)}+ error={getFieldError(field.state.meta.errors) ?? undefined}+ />+ )}+ </form.Field>- <div className="form-control">- <label className="label">- <span className="label-text font-medium">Devices</span>- </label>- <select- className="select select-bordered w-full"- value={devices}- onChange={(e) => {- const value = e.target.value;- if (- value === "both" ||- value === "desktop" ||- value === "mobile"- ) {- setDevices(value);- }- }}- >- <option value="both">Desktop + Mobile</option>- <option value="desktop">Desktop only</option>- <option value="mobile">Mobile only</option>- </select>- <div className="mt-1.5 text-xs text-base-content/50">- Most Google searches come from mobile, but select this based on your- customer.- </div>- {devices === "both" && (- <div className="mt-1.5 flex items-start gap-1.5 text-xs text-info">- <Info className="size-3.5 shrink-0 mt-0.5" />- <span>- Tracking both devices uses 2x credits per keyword check- </span>- </div>- )}- </div>+ <form.AppField name="languageCode">+ {(field) => (+ <field.SelectField+ label="Language"+ items={LANGUAGE_ITEMS}+ description="Defaults to the country's language. Any language can be tracked in any country — pick the one your customers search in."+ />+ )}+ </form.AppField>- <ScheduleField- schedule={schedule}- onScheduleChange={setSchedule}- scheduleTime={scheduleTime}- onScheduleTimeChange={(time) => {- setScheduleTime(time);- setScheduleTimeEdited(true);- }}- />+ <div className="flex flex-col gap-1.5">+ <form.AppField name="devices">+ {(field) => (+ <field.SelectField+ label="Devices"+ items={DEVICE_ITEMS}+ description="Most Google searches come from mobile, but select this based on your customer."+ />+ )}+ </form.AppField>+ {values.devices === "both" && (+ <p className="flex items-start gap-1.5 text-xs text-info">+ <Info className="mt-0.5 size-3.5 shrink-0" />+ Tracking both devices uses 2x credits per keyword check+ </p>+ )}+ </div>- <div className="form-control">- <label className="label">- <span className="label-text font-medium">Search Depth</span>- </label>- <select- className="select select-bordered w-full"- value={depthToPages(serpDepth)}- onChange={(e) => setSerpDepth(pagesToDepth(Number(e.target.value)))}- >- {Array.from({ length: 10 }, (_, i) => i + 1).map((pages) => (- <option key={pages} value={pages}>- {pages} {pages === 1 ? "page" : "pages"} (top {pages * 10}{" "}- results)- </option>- ))}- </select>- <div className="mt-1.5 text-xs text-base-content/50">- 10 pages is ~8x more expensive than 1 page- </div>- </div>+ <ScheduleField+ schedule={values.schedule}+ onScheduleChange={(schedule) =>+ form.setFieldValue("schedule", schedule)+ }+ scheduleTime={values.scheduleTime}+ onScheduleTimeChange={(time) => {+ form.setFieldValue("scheduleTime", time);+ setScheduleTimeEdited(true);+ }}+ />- {(() => {- // Scheduled checks run through the cheaper task queue; manual- // configs only ever pay the live price.- const { costUsd: costPerKeyword } = estimateRankCheckCredits(- ["plain keyword"],- devices,- serpDepth,- schedule === "manual" ? "live" : "queued",- );- const checksPerMonth =- schedule === "daily" ? 30 : schedule === "weekly" ? 4 : 1;- return (- <div className="rounded-lg bg-base-200/50 px-3 py-2.5 text-xs text-base-content/70 space-y-0.5">- <div>- <span className="font-mono font-semibold text-base-content">- ~${costPerKeyword.toFixed(4)}- </span>{" "}- per keyword per check- </div>- {schedule !== "manual" && (- <div>- 50 keywords would cost{" "}- <span className="font-mono font-semibold text-base-content">- ~${(costPerKeyword * 50 * checksPerMonth).toFixed(2)}- </span>- /month- </div>- )}- </div>- );- })()}+ <form.AppField name="serpDepth">+ {(field) => (+ <field.SelectField+ label="Search Depth"+ items={DEPTH_ITEMS}+ description="10 pages is ~8x more expensive than 1 page"+ />+ )}+ </form.AppField>- <div className="flex justify-end gap-2 pt-2">- <button- type="button"- className="btn btn-ghost btn-sm"- onClick={onClose}- >- Cancel- </button>- <button- type="submit"- className="btn btn-primary btn-sm"- disabled={isPending || !domain.trim()}- >- {isPending && <Loader2 className="size-3.5 animate-spin" />}- {isEdit ? "Save Changes" : "Add Domain"}- </button>+ <CostEstimate+ devices={values.devices}+ serpDepth={values.serpDepth}+ schedule={values.schedule}+ />++ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={onClose}+ disabled={isSubmitting}+ >+ Cancel+ </Button>+ <form.SubmitButton>+ {isEdit ? "Save Changes" : "Add Domain"}+ </form.SubmitButton>+ </DialogFooter>+ </form.Form>+ </form.AppForm>+ )}+ </DialogContent>+ </Dialog>+ );+}++function CostEstimate({+ devices,+ serpDepth,+ schedule,+}: Pick<ConfigFormValues, "devices" | "serpDepth" | "schedule">) {+ // Scheduled checks run through the cheaper task queue; manual configs only+ // ever pay the live price.+ const { costUsd: costPerKeyword } = estimateRankCheckCredits(+ ["plain keyword"],+ devices,+ serpDepth,+ schedule === "manual" ? "live" : "queued",+ );+ const checksPerMonth =+ schedule === "daily" ? 30 : schedule === "weekly" ? 4 : 1;+ return (+ <div className="space-y-0.5 rounded-lg bg-muted px-3 py-2.5 text-xs text-muted-foreground">+ <div>+ <span className="font-mono font-semibold text-foreground">+ ~${costPerKeyword.toFixed(4)}+ </span>{" "}+ per keyword per check+ </div>+ {schedule !== "manual" && (+ <div>+ 50 keywords would cost{" "}+ <span className="font-mono font-semibold text-foreground">+ ~${(costPerKeyword * 50 * checksPerMonth).toFixed(2)}+ </span>+ /month</div>- </form>- </Modal>+ )}+ </div>);}diff --git a/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx b/src/client/features/rank-tracking/RankTrackingDetailHeader.tsxindex 1b566d86..a7918e85 100644--- a/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx+++ b/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx@@ -1,5 +1,13 @@import { Monitor, Plus, Settings, Smartphone } from "lucide-react";import { SegmentedToggle } from "@/client/components/SegmentedToggle";+import { Button } from "@/client/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/client/components/ui/select";import { LOCATIONS } from "@/client/features/keywords/locations";import { devicesLabel, scheduleLabel } from "@/shared/rank-tracking";import { formatNextCheck } from "./scheduleTime";@@ -10,6 +18,13 @@ import {type ComparePeriod,} from "@/types/schemas/rank-tracking-search";+const COMPARE_ITEMS: { value: ComparePeriod; label: string }[] = [+ { value: "1d", label: "vs yesterday" },+ { value: "7d", label: "vs last week" },+ { value: "30d", label: "vs last month" },+ { value: "90d", label: "vs 90 days ago" },+];+export function RankTrackingDetailHeader({config,run,@@ -37,7 +52,7 @@ export function RankTrackingDetailHeader({<div className="flex flex-col sm:flex-row sm:items-start justify-between gap-2 px-4 pt-4 pb-3"><div><h2 className="text-lg font-semibold">{config.domain}</h2>- <p className="text-xs text-base-content/60">+ <p className="text-xs text-muted-foreground">{config.locationName? formatLocationLabel(config.locationName, 2): (LOCATIONS[config.locationCode] ?? "US")}{" "}@@ -76,32 +91,39 @@ export function RankTrackingDetailHeader({onChange={onActiveDeviceChange}/>)}- <select- className="select select-bordered select-sm text-xs w-auto"- title="Comparison period"+ <Select+ items={COMPARE_ITEMS}value={comparePeriod}- onChange={(e) => {- const parsed = comparePeriodSchema.safeParse(e.target.value);+ onValueChange={(value) => {+ const parsed = comparePeriodSchema.safeParse(value);if (parsed.success) onComparePeriodChange(parsed.data);}}>- <option value="1d">vs yesterday</option>- <option value="7d">vs last week</option>- <option value="30d">vs last month</option>- <option value="90d">vs 90 days ago</option>- </select>- <div className="hidden sm:block h-6 w-px bg-base-300" />- <button className="btn btn-sm gap-1" onClick={onEdit}>- <Settings className="size-3.5" />+ <SelectTrigger+ size="sm"+ aria-label="Comparison period"+ title="Comparison period"+ className="text-xs"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {COMPARE_ITEMS.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <div className="hidden h-6 w-px bg-border sm:block" />+ <Button variant="outline" size="sm" onClick={onEdit}>+ <Settings data-icon="inline-start" />Configure- </button>- <button- className="btn btn-primary btn-sm gap-1"- onClick={onToggleAddKeywords}- >- <Plus className="size-3.5" />+ </Button>+ <Button size="sm" onClick={onToggleAddKeywords}>+ <Plus data-icon="inline-start" />Add Keywords- </button>+ </Button></div></div>);diff --git a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsxindex 1d98a3f2..7b629e98 100644--- a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx+++ b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx@@ -10,8 +10,11 @@ import {getRankPositionMatrix,estimateRankCheckCost,} from "@/serverFunctions/rank-tracking";-import { AlertTriangle, ArrowLeft, Loader2 } from "lucide-react";+import { AlertTriangle } from "lucide-react";+import { BackLink } from "@/client/components/PageHeader";import { QueryState } from "@/client/components/QueryState";+import { PageLoading } from "@/client/components/Spinner";+import { Alert, AlertDescription } from "@/client/components/ui/alert";import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";import { captureClientEvent } from "@/client/lib/posthog";import { FreePlanAlert } from "./FreePlanAlert";@@ -78,14 +81,12 @@ export function RankTrackingDomainDetail({projectId,search,onSearchChange,- onBack,onEdit,}: {config: RankTrackingConfig;projectId: string;search: RankTrackingDetailSearch;onSearchChange: (update: Partial<RankTrackingDetailSearch>) => void;- onBack: () => void;onEdit: () => void;}) {const planStatus = useHostedPlanGate();@@ -234,47 +235,45 @@ export function RankTrackingDomainDetail({return (<div className="space-y-3">- <button- className="btn btn-ghost btn-xs gap-1 -ml-2 text-base-content/60"- onClick={onBack}- >- <ArrowLeft className="size-3" />+ <BackLink to="/p/$projectId/rank-tracking" params={{ projectId }}>Back to domains- </button>+ </BackLink>{config.lastSkipReason === "insufficient_credits" && (- <div className="alert alert-warning text-sm py-2">- <AlertTriangle className="size-4" />- <span>+ <Alert variant="warning">+ <AlertTriangle />+ <AlertDescription className="text-foreground">Last scheduled check was skipped due to insufficient credits. Top upyour balance to resume automatic tracking.- </span>- </div>+ </AlertDescription>+ </Alert>)}{latestRun?.maybeStale && (- <div className="alert alert-warning text-sm py-2">- <AlertTriangle className="size-4" />- <span>+ <Alert variant="warning">+ <AlertTriangle />+ <AlertDescription className="text-foreground">This run may be unresponsive and will be cleaned up automatically.- </span>- </div>+ </AlertDescription>+ </Alert>)}{latestRun?.status === "failed" && (- <div className="alert alert-error text-sm py-2">- <AlertTriangle className="size-4" />- <span>- <span className="font-medium">Last check failed.</span>{" "}- {latestRun.errorMessage}- </span>- </div>+ <Alert variant="destructive">+ <AlertTriangle />+ <AlertDescription className="text-foreground">+ <p>+ <span className="font-medium">Last check failed.</span>{" "}+ {latestRun.errorMessage}+ </p>+ </AlertDescription>+ </Alert>)}<FreePlanAlert visible={planStatus === "free"} />{/* Results card */}- <div className="flex-1 flex flex-col min-w-0 border border-base-300 rounded-xl bg-base-100 overflow-hidden">+ <div className="flex min-w-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-card shadow-sm">{/* Domain header */}<RankTrackingDetailHeaderconfig={config}@@ -362,16 +361,13 @@ export function RankTrackingDomainDetail({trackingKeywordId: r.trackingKeywordId,keyword: r.keyword,}))}+ onClearFilters={() => setFilters(EMPTY_FILTERS)}/>) : (<QueryStatequery={resultsQuery}errorFallback="Failed to load rank data"- loading={- <div className="flex items-center justify-center p-8">- <Loader2 className="size-5 animate-spin text-base-content/50" />- </div>- }+ loading={<PageLoading />}>{(results) => (<RankTrackingTable@@ -399,7 +395,8 @@ export function RankTrackingDomainDetail({locationCode={config.locationCode}locationName={config.locationName}serpDepth={config.serpDepth}- canCheck={planStatus === "paid"}+ onAddKeywords={() => setShowAddKeywords(true)}+ onClearFilters={() => setFilters(EMPTY_FILTERS)}/>)}</QueryState>diff --git a/src/client/features/rank-tracking/RankTrackingDomainList.tsx b/src/client/features/rank-tracking/RankTrackingDomainList.tsxindex 2b8f5c29..476e62b7 100644--- a/src/client/features/rank-tracking/RankTrackingDomainList.tsx+++ b/src/client/features/rank-tracking/RankTrackingDomainList.tsx@@ -9,7 +9,6 @@ import {Globe,Plus,ChevronRight,- Search,} from "lucide-react";import {getRankTrackingConfigSummaries,@@ -18,7 +17,15 @@ import {import { devicesLabel, scheduleLabel } from "@/shared/rank-tracking";import { formatNextCheck } from "./scheduleTime";import { formatLocationLabel } from "@/shared/keyword-locations";-import { Modal } from "@/client/components/Modal";+import { ConfirmDialog } from "@/client/components/ConfirmDialog";+import { EmptyState } from "@/client/components/EmptyState";+import { Button } from "@/client/components/ui/button";+import {+ Card,+ CardAction,+ CardHeader,+ CardTitle,+} from "@/client/components/ui/card";import {applyDomainListFilters,countActiveDomainListFilters,@@ -125,121 +132,93 @@ export function RankTrackingDomainList({});return (- <div className="card bg-base-100 border border-base-300">- <div className="card-body gap-0 p-0">- <div className="flex items-center justify-between px-5 pt-4 pb-3">+ <Card className="gap-0 py-0">+ <CardHeader className="px-5 pt-4 pb-3">+ <CardTitle><h2 className="text-sm font-semibold">Tracked Domains</h2>- <button- className="btn btn-primary btn-sm gap-1"- onClick={onAddDomain}- >- <Plus className="size-3.5" />+ </CardTitle>+ <CardAction className="self-center">+ <Button size="sm" onClick={onAddDomain}>+ <Plus data-icon="inline-start" />Add Domain- </button>- </div>- {(allSummaries.length >= FILTER_BAR_MIN_DOMAINS ||- activeFilterCount > 0) && (- <DomainListFilterBar- filters={filters}- options={filterOptions}- activeFilterCount={activeFilterCount}- onChange={setFilters}- onReset={clearFilters}- />+ </Button>+ </CardAction>+ </CardHeader>+ {(allSummaries.length >= FILTER_BAR_MIN_DOMAINS ||+ activeFilterCount > 0) && (+ <DomainListFilterBar+ filters={filters}+ options={filterOptions}+ activeFilterCount={activeFilterCount}+ onChange={setFilters}+ onReset={clearFilters}+ />+ )}+ <div className="divide-y divide-border border-t border-border">+ {summariesQuery.isError && (+ <div className="px-5 py-4">+ <QueryError+ error={summariesQuery.error}+ fallback="Failed to load tracked domains"+ onRetry={() => void summariesQuery.refetch()}+ isRetrying={summariesQuery.isFetching}+ />+ </div>)}- <div className="divide-y divide-base-300 border-t border-base-300">- {summariesQuery.isError && (- <div className="px-5 py-4">- <QueryError- error={summariesQuery.error}- fallback="Failed to load tracked domains"- onRetry={() => void summariesQuery.refetch()}- isRetrying={summariesQuery.isFetching}- />- </div>- )}- {summariesQuery.isPending ? (- <div className="space-y-4 px-5 py-4" aria-busy>- {Array.from({ length: 3 }).map((_, index) => (- <div key={index} className="space-y-2">- <Skeleton className="h-4 w-48" />- <Skeleton className="h-3 w-72" />- </div>- ))}- </div>- ) : !summaries ? null : summaries.length === 0 ? (- <div className="px-5 py-10 text-center space-y-2">- <div className="mx-auto flex size-10 items-center justify-center rounded-xl bg-base-200">- <Globe className="size-5 text-base-content/40" />- </div>- <p className="text-sm font-medium text-base-content/70">- No tracked domains yet- </p>- <p className="text-xs text-base-content/40">- Add a domain to start monitoring keyword rankings over time.- </p>- </div>- ) : filteredSummaries.length === 0 ? (- <div className="px-5 py-10 text-center space-y-3">- <div className="mx-auto flex size-10 items-center justify-center rounded-xl bg-base-200">- <Search className="size-5 text-base-content/40" />+ {summariesQuery.isPending ? (+ <div className="space-y-4 px-5 py-4" aria-busy>+ {Array.from({ length: 3 }).map((_, index) => (+ <div key={index} className="space-y-2">+ <Skeleton className="h-4 w-48" />+ <Skeleton className="h-3 w-72" /></div>- <div className="space-y-1">- <p className="text-sm font-medium text-base-content/70">- No matching tracked domains- </p>- <p className="text-xs text-base-content/40">- Try clearing search or adjusting filters.- </p>- </div>- <button className="btn btn-ghost btn-xs" onClick={clearFilters}>+ ))}+ </div>+ ) : !summaries ? null : summaries.length === 0 ? (+ <EmptyState+ variant="plain"+ icon={Globe}+ title="No tracked domains yet"+ description="Add a domain to start monitoring keyword rankings over time."+ />+ ) : filteredSummaries.length === 0 ? (+ <EmptyState+ variant="plain"+ kind="filtered"+ title="No matching tracked domains"+ description="Try clearing search or adjusting filters."+ action={+ <Button variant="outline" size="sm" onClick={clearFilters}>Clear filters- </button>- </div>- ) : (- filteredSummaries.map((summary) => (- <DomainRow- key={summary.id}- projectId={projectId}- summary={summary}- onArchive={() => setArchiveTarget(summary)}- />- ))- )}- </div>+ </Button>+ }+ />+ ) : (+ filteredSummaries.map((summary) => (+ <DomainRow+ key={summary.id}+ projectId={projectId}+ summary={summary}+ onArchive={() => setArchiveTarget(summary)}+ />+ ))+ )}</div>{archiveTarget && (- <Modal+ <ConfirmDialog+ title={`Archive ${archiveTarget.domain}?`}+ confirmLabel="Archive"+ destructive+ pending={archiveMutation.isPending}+ onConfirm={() => archiveMutation.mutate(archiveTarget.id)}onClose={() => setArchiveTarget(null)}- labelledBy="archive-domain-title">- <h3 id="archive-domain-title" className="text-lg font-semibold">- Archive {archiveTarget.domain}?- </h3>- <p className="text-sm text-base-content/70">- Scheduled checks will stop and this domain will be hidden from the- list. Ranking history is preserved.- </p>- <div className="flex justify-end gap-2">- <button- className="btn btn-ghost btn-sm"- onClick={() => setArchiveTarget(null)}- >- Cancel- </button>- <button- className="btn btn-error btn-sm gap-1"- onClick={() => archiveMutation.mutate(archiveTarget.id)}- disabled={archiveMutation.isPending}- >- <Archive className="size-3.5" />- Archive- </button>- </div>- </Modal>+ Scheduled checks will stop and this domain will be hidden from the+ list. Ranking history is preserved.+ </ConfirmDialog>)}- </div>+ </Card>);}@@ -253,7 +232,7 @@ function DomainRow({onArchive: () => void;}) {return (- <div className="relative flex w-full items-center gap-4 px-5 py-3.5 transition-colors hover:bg-base-200/50">+ <div className="relative flex w-full items-center gap-4 px-5 py-3.5 transition-colors hover:bg-foreground/[0.03]"><Linkto="/p/$projectId/rank-tracking/$configId"params={{ projectId, configId: summary.id }}@@ -262,7 +241,7 @@ function DomainRow({/><div className="min-w-0 flex-1 pointer-events-none"><p className="font-medium truncate">{summary.domain}</p>- <p className="text-xs text-base-content/60">+ <p className="text-xs text-muted-foreground">{summary.locationName? formatLocationLabel(summary.locationName, 2): (LOCATIONS[summary.locationCode] ?? "US")}{" "}@@ -295,17 +274,19 @@ function DomainRow({<div className="hidden sm:flex items-center gap-6 text-sm pointer-events-none">{summary.keywordCount > 0 && (<div className="text-center">- <p className="text-xs uppercase tracking-wide text-base-content/60">+ <p className="text-xs uppercase tracking-wide text-muted-foreground">Keywords</p><p className="font-mono font-medium">{summary.keywordCount}</p></div>)}</div>- <button- type="button"- className="btn btn-ghost btn-xs text-base-content/40 hover:text-error relative z-10"+ <Button+ variant="ghost"+ size="icon-xs"+ className="relative z-10 text-muted-foreground hover:text-destructive"title="Archive domain"+ aria-label={`Archive ${summary.domain}`}onClick={(e) => {e.stopPropagation();e.preventDefault();@@ -313,8 +294,8 @@ function DomainRow({}}><Archive className="size-4" />- </button>- <ChevronRight className="size-4 shrink-0 text-base-content/40 pointer-events-none" />+ </Button>+ <ChevronRight className="size-4 shrink-0 text-muted-foreground pointer-events-none" /></div>);}diff --git a/src/client/features/rank-tracking/RankTrackingFilters.tsx b/src/client/features/rank-tracking/RankTrackingFilters.tsxindex 93ac3317..88f1314f 100644--- a/src/client/features/rank-tracking/RankTrackingFilters.tsx+++ b/src/client/features/rank-tracking/RankTrackingFilters.tsx@@ -1,4 +1,16 @@+import { useId } from "react";import { RotateCcw } from "lucide-react";+import { Badge } from "@/client/components/ui/badge";+import { Button } from "@/client/components/ui/button";+import { Input } from "@/client/components/ui/input";+import { Label } from "@/client/components/ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/client/components/ui/select";import type { DomainListFilters, Filters } from "./RankTrackingFilters.logic";export * from "./RankTrackingFilters.logic";@@ -8,6 +20,9 @@ type DomainListFilterOption = {label: string;};+const FILTER_LABEL_CLASS =+ "text-[11px] font-semibold uppercase tracking-wide text-muted-foreground";+/** `draft` is the unapplied panel state; it reaches the URL after a pause. */export function FilterPanel({draft,@@ -20,47 +35,47 @@ export function FilterPanel({activeFilterCount: number;onReset: () => void;}) {+ const id = useId();const update = (key: keyof Filters, value: string) =>setDraft({ ...draft, [key]: value });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="shrink-0 space-y-3 border-b border-border bg-muted/40 px-4 py-3"><div className="flex items-center justify-between"><div className="flex items-center gap-2"><p className="text-sm font-semibold">Refine results</p>{activeFilterCount > 0 && (- <span className="badge badge-xs badge-primary border-0 text-primary-content">- {activeFilterCount} active- </span>+ <Badge size="sm">{activeFilterCount} active</Badge>)}</div>- <button- className="btn btn-xs btn-ghost gap-1"+ <Button+ variant="ghost"+ size="xs"onClick={onReset}disabled={activeFilterCount === 0}>- <RotateCcw className="size-3" />+ <RotateCcw data-icon="inline-start" />Clear all- </button>+ </Button></div><div className="grid grid-cols-1 gap-3 lg:grid-cols-2"><div className="space-y-1.5">- <p className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">+ <Label htmlFor={`${id}-include`} className={FILTER_LABEL_CLASS}>Include- </p>- <input- className="input input-bordered input-sm w-full bg-base-100"+ </Label>+ <Input+ id={`${id}-include`}placeholder="e.g. seo, tool"value={draft.include}onChange={(e) => update("include", e.target.value)}/></div><div className="space-y-1.5">- <p className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">+ <Label htmlFor={`${id}-exclude`} className={FILTER_LABEL_CLASS}>Exclude- </p>- <input- className="input input-bordered input-sm w-full bg-base-100"+ </Label>+ <Input+ id={`${id}-exclude`}placeholder="e.g. free, cheap"value={draft.exclude}onChange={(e) => update("exclude", e.target.value)}@@ -126,31 +141,40 @@ export function DomainListFilterBar({onChange: (filters: DomainListFilters) => void;onReset: () => void;}) {+ const id = useId();+ const deviceItems = [+ { value: "all", label: "All devices" },+ ...options.devices,+ ];+ const locationItems = [+ { value: "all", label: "All countries" },+ ...options.locations,+ ];+return (- <div className="border-t border-base-300 px-5 py-3">+ <div className="border-t border-border px-5 py-3"><div className="flex flex-col gap-3 lg:flex-row lg:items-end">- <label className="form-control flex-1 gap-1.5">- <span className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">+ <div className="flex flex-1 flex-col gap-1.5">+ <Label htmlFor={`${id}-search`} className={FILTER_LABEL_CLASS}>Search- </span>- <input- className="input input-bordered input-sm w-full bg-base-100"+ </Label>+ <Input+ id={`${id}-search`}placeholder="Domain or website"value={filters.query}onChange={(event) =>onChange({ ...filters, query: event.target.value })}/>- </label>- <label className="form-control gap-1.5 lg:w-44">- <span className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">+ </div>+ <div className="flex flex-col gap-1.5 lg:w-44">+ <Label htmlFor={`${id}-device`} className={FILTER_LABEL_CLASS}>Device- </span>- <select- className="select select-bordered select-sm w-full bg-base-100"+ </Label>+ <Select+ items={deviceItems}value={filters.device}- onChange={(event) => {- const value = event.target.value;+ onValueChange={(value) => {if (value === "all" ||value === "both" ||@@ -161,44 +185,51 @@ export function DomainListFilterBar({}}}>- <option value="all">All devices</option>- {options.devices.map((option) => (- <option key={option.value} value={option.value}>- {option.label}- </option>- ))}- </select>- </label>- <label className="form-control gap-1.5 lg:w-52">- <span className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">+ <SelectTrigger id={`${id}-device`} className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {deviceItems.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="flex flex-col gap-1.5 lg:w-52">+ <Label htmlFor={`${id}-country`} className={FILTER_LABEL_CLASS}>Country- </span>- <select- className="select select-bordered select-sm w-full bg-base-100"+ </Label>+ <Select+ items={locationItems}value={filters.locationCode}- onChange={(event) =>- onChange({ ...filters, locationCode: event.target.value })- }+ onValueChange={(value) => {+ if (value) onChange({ ...filters, locationCode: value });+ }}>- <option value="all">All countries</option>- {options.locations.map((option) => (- <option key={option.value} value={option.value}>- {option.label}- </option>- ))}- </select>- </label>+ <SelectTrigger id={`${id}-country`} className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {locationItems.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>{activeFilterCount > 0 && (- <button- className="btn btn-ghost btn-sm gap-1.5 self-start lg:self-auto"+ <Button+ variant="ghost"+ className="self-start lg:self-auto"onClick={onReset}>- <RotateCcw className="size-3" />+ <RotateCcw data-icon="inline-start" />Clear- <span className="badge badge-xs badge-primary border-0 text-primary-content">- {activeFilterCount}- </span>- </button>+ <Badge size="sm">{activeFilterCount}</Badge>+ </Button>)}</div></div>@@ -219,21 +250,21 @@ function RangeFilter({onMaxChange: (v: string) => void;}) {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="space-y-2 rounded-lg border border-border bg-card p-2.5">+ <p className={FILTER_LABEL_CLASS}>{title}</p><div className="grid grid-cols-2 gap-2">- <input- className="input input-bordered input-xs bg-base-100"+ <Input+ className="h-7"placeholder="Min"+ aria-label={`${title} min`}type="number"value={minValue}onChange={(e) => onMinChange(e.target.value)}/>- <input- className="input input-bordered input-xs bg-base-100"+ <Input+ className="h-7"placeholder="Max"+ aria-label={`${title} max`}type="number"value={maxValue}onChange={(e) => onMaxChange(e.target.value)}diff --git a/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx b/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsxindex b3b59768..eba20305 100644--- a/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx+++ b/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx@@ -1,6 +1,16 @@import { useMemo } from "react";import { sort } from "remeda";import type { RankPositionMatrixCell } from "@/serverFunctions/rank-tracking";+import { EmptyState } from "@/client/components/EmptyState";+import { Button } from "@/client/components/ui/button";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/client/components/ui/table";/*** "By date" view: keyword rows × recent check columns, each cell the position@@ -10,9 +20,11 @@ import type { RankPositionMatrixCell } from "@/serverFunctions/rank-tracking";export function RankTrackingHistoryMatrix({cells,keywords,+ onClearFilters,}: {cells: RankPositionMatrixCell[];keywords: { trackingKeywordId: string; keyword: string }[];+ onClearFilters: () => void;}) {const { runs, cellByKeyword } = useMemo(() => buildMatrix(cells), [cells]);@@ -20,53 +32,59 @@ export function RankTrackingHistoryMatrix({// runs, so only filters can leave this empty.if (keywords.length === 0) {return (- <div className="rounded-xl border border-dashed border-base-300 p-10 text-center text-sm text-base-content/55">- No keywords match your search.- </div>+ <EmptyState+ kind="filtered"+ title="No keywords match these filters"+ description="Change or clear the filters to see more keywords."+ action={+ <Button variant="outline" size="sm" onClick={onClearFilters}>+ Clear filters+ </Button>+ }+ />);}return (- <div className="overflow-x-auto rounded-lg border border-base-300">- <table className="table table-sm">- <thead>- <tr>+ <div className="overflow-hidden rounded-xl border border-border bg-card">+ <Table>+ <TableHeader>+ <TableRow className="hover:bg-transparent">{/* Unconstrained keyword column absorbs the slack when only a fewcheck columns exist, so sparse history doesn't stretch oddly. */}- <th className="sticky left-0 z-10 bg-base-100 w-full">Keyword</th>+ <TableHead className="sticky left-0 z-10 w-full bg-card">+ Keyword+ </TableHead>{runs.map((r) => (- <th- key={r.runId}- className="w-24 whitespace-nowrap text-right text-xs font-medium text-base-content/60"- >+ <TableHead key={r.runId} className="w-24 text-right">{formatDate(r.checkedAt)}- </th>+ </TableHead>))}- </tr>- </thead>- <tbody>+ </TableRow>+ </TableHeader>+ <TableBody>{keywords.map((kw) => {const byRun = cellByKeyword.get(kw.trackingKeywordId);return (- <tr key={kw.trackingKeywordId}>- <td className="sticky left-0 z-10 bg-base-100 whitespace-nowrap font-medium">+ <TableRow key={kw.trackingKeywordId}>+ <TableCell className="sticky left-0 z-10 bg-card font-medium whitespace-nowrap">{kw.keyword}- </td>+ </TableCell>{runs.map((r, i) => {const position = byRun?.get(r.runId) ?? null;const previous =i > 0 ? (byRun?.get(runs[i - 1].runId) ?? null) : undefined;return (- <td key={r.runId} className="text-right">+ <TableCell key={r.runId} className="text-right"><MatrixCell position={position} previous={previous} />- </td>+ </TableCell>);})}- </tr>+ </TableRow>);})}- </tbody>- </table>+ </TableBody>+ </Table></div>);}@@ -79,7 +97,7 @@ function MatrixCell({previous: number | null | undefined;}) {if (position === null) {- return <span className="text-base-content/30">—</span>;+ return <span className="text-muted-foreground">—</span>;}// Only show a change arrow when both checks ranked (no subtracting through a// null, matching the rest of the rank-tracking UI).diff --git a/src/client/features/rank-tracking/RankTrackingOverview.tsx b/src/client/features/rank-tracking/RankTrackingOverview.tsxindex e00302f8..cb49bc5d 100644--- a/src/client/features/rank-tracking/RankTrackingOverview.tsx+++ b/src/client/features/rank-tracking/RankTrackingOverview.tsx@@ -1,9 +1,9 @@import { useMemo, useState } from "react";-import { Loader2 } from "lucide-react";import { useQuery } from "@tanstack/react-query";import { Area, AreaChart } from "recharts";import { getRankConfigTrend } from "@/serverFunctions/rank-tracking";import { QueryState } from "@/client/components/QueryState";+import { PageLoading } from "@/client/components/Spinner";import {ChartGrid,ChartXAxis,@@ -18,6 +18,7 @@ import {import {formatDateLabel,TIME_AXIS,+ TrendEmptyState,TrendRangeToggle,} from "./RankTrackingTrendChart";@@ -66,7 +67,7 @@ export function RankTrackingOverview({return (<div className="px-4 pt-4 pb-4">- <div className="rounded-lg border border-base-300 p-3 space-y-2">+ <div className="space-y-2 rounded-lg border border-border p-3"><div className="flex items-center justify-between gap-2"><span className="text-sm font-medium">Position distribution</span><TrendRangeToggle value={sinceDays} onChange={setSinceDays} />@@ -76,7 +77,7 @@ export function RankTrackingOverview({{BUCKETS.map((b) => (<spankey={b.key}- className="inline-flex items-center gap-1 text-[11px] text-base-content/60"+ className="inline-flex items-center gap-1 text-[11px] text-muted-foreground"><spanclassName="size-2 rounded-sm"@@ -90,19 +91,11 @@ export function RankTrackingOverview({<QueryStatequery={trendQuery}errorFallback="Failed to load position history"- loading={- <div className="flex items-center justify-center p-8">- <Loader2 className="size-4 animate-spin text-base-content/50" />- </div>- }+ loading={<PageLoading />}>{() =>chartData.length <= 1 ? (- <div className="rounded-lg border border-dashed border-base-300 p-8 text-center text-xs text-base-content/60">- {chartData.length === 0- ? "No history yet — run a check to start tracking positions over time."- : "Only 1 check so far — the trend fills in after the next check."}- </div>+ <TrendEmptyState checks={chartData.length} />) : (<ChartContainer config={chartConfig} className="h-[220px]"><AreaChartdiff --git a/src/client/features/rank-tracking/RankTrackingTable.tsx b/src/client/features/rank-tracking/RankTrackingTable.tsxindex aa2cce9d..af5c7f68 100644--- a/src/client/features/rank-tracking/RankTrackingTable.tsx+++ b/src/client/features/rank-tracking/RankTrackingTable.tsx@@ -1,9 +1,9 @@import { useCallback, useRef, useState } from "react";import { toast } from "sonner";-import { FileDown, Loader2, Sheet, Trash2 } from "lucide-react";-import { Modal } from "@/client/components/Modal";-import { AppDataTable } from "@/client/components/table/AppDataTable";-import { useDataTable } from "@/client/components/table/DataTable";+import { FileDown, Plus, Sheet, Trash2 } from "lucide-react";+import { ConfirmDialog } from "@/client/components/ConfirmDialog";+import { Button } from "@/client/components/ui/button";+import { DataTable, useDataTable } from "@/client/components/table/DataTable";import {TableBulkActionBar,TableBulkActionButton,@@ -34,7 +34,8 @@ export function RankTrackingTable({locationCode,locationName,serpDepth,- canCheck,+ onAddKeywords,+ onClearFilters,}: {totalCount: number;rows: RankTrackingRow[];@@ -48,7 +49,8 @@ export function RankTrackingTable({locationCode: number;locationName?: string | null;serpDepth: number;- canCheck: boolean;+ onAddKeywords: () => void;+ onClearFilters: () => void;}) {const queryClient = useQueryClient();const [showConfirm, setShowConfirm] = useState(false);@@ -124,18 +126,6 @@ export function RankTrackingTable({},});- if (rows.length === 0) {- return (- <div className="rounded-xl border border-dashed border-base-300 p-10 text-center text-sm text-base-content/55">- {totalCount === 0- ? canCheck- ? 'No rank data yet. Use "Check rankings" in the More actions menu to run the first check.'- : "No rank data yet."- : "No keywords match your search."}- </div>- );- }-return (<><TableBulkActionBar@@ -168,42 +158,19 @@ export function RankTrackingTable({}/>- {/* Confirm modal */}{showConfirm && (- <Modal+ <ConfirmDialog+ title="Remove keywords?"+ confirmLabel={`Remove ${selectedCount} keyword${selectedCount !== 1 ? "s" : ""}`}+ destructive+ pending={removeMutation.isPending}+ onConfirm={() => removeMutation.mutate(selectedRows.map((r) => r.id))}onClose={() => setShowConfirm(false)}- labelledBy="remove-keywords-title">- <h3 id="remove-keywords-title" className="text-lg font-semibold">- Remove keywords?- </h3>- <p className="text-sm text-base-content/70">- This will stop tracking {selectedCount} keyword- {selectedCount !== 1 ? "s" : ""}. Historical ranking data is- preserved but won't appear in the table.- </p>- <div className="flex justify-end gap-2">- <button- className="btn btn-ghost btn-sm"- onClick={() => setShowConfirm(false)}- >- Cancel- </button>- <button- className="btn btn-error btn-sm gap-1"- onClick={() =>- removeMutation.mutate(selectedRows.map((r) => r.id))- }- disabled={removeMutation.isPending}- >- {removeMutation.isPending && (- <Loader2 className="size-3 animate-spin" />- )}- Remove {selectedCount} keyword- {selectedCount !== 1 ? "s" : ""}- </button>- </div>- </Modal>+ This will stop tracking {selectedCount} keyword+ {selectedCount !== 1 ? "s" : ""}. Historical ranking data is preserved+ but won't appear in the table.+ </ConfirmDialog>)}{trendTarget && (@@ -219,10 +186,28 @@ export function RankTrackingTable({/>)}- <AppDataTable table={table} getCellClassName={() => "align-top"} />- <p className="text-xs text-base-content/60 pt-2">- {rows.length} of {totalCount} keywords- </p>+ <DataTable+ table={table}+ isFiltered={totalCount > 0}+ onClearFilters={onClearFilters}+ empty={{+ title: "No keywords yet",+ description: "Add the keywords you want to track for this domain.",+ action: (+ <Button size="sm" onClick={onAddKeywords}>+ <Plus data-icon="inline-start" />+ Add Keywords+ </Button>+ ),+ }}+ footer={+ rows.length > 0 ? (+ <p className="border-t border-border px-4 py-2 text-xs text-muted-foreground">+ {rows.length} of {totalCount} keywords+ </p>+ ) : null+ }+ /></>);}diff --git a/src/client/features/rank-tracking/RankTrackingTableParts.tsx b/src/client/features/rank-tracking/RankTrackingTableParts.tsxindex 2be379f9..b84b54eb 100644--- a/src/client/features/rank-tracking/RankTrackingTableParts.tsx+++ b/src/client/features/rank-tracking/RankTrackingTableParts.tsx@@ -1,4 +1,5 @@import { Sparkles } from "lucide-react";+import { Badge } from "@/client/components/ui/badge";import { exportRows } from "@/client/lib/exportRows";import { captureClientEvent } from "@/client/lib/posthog";import { formatLocationLabel } from "@/shared/keyword-locations";@@ -38,14 +39,16 @@ export function SerpFeatureTags({ features }: { features: string[] }) {return (<div className="flex gap-1 flex-wrap">{notable.map((f) => (- <span+ <Badgekey={f}- className="badge badge-xs gap-0.5 cursor-help bg-base-300 border-0 text-base-content/70"+ variant="secondary"+ size="sm"+ className="cursor-help"title={FEATURE_TOOLTIPS[f] ?? f}>- {f === "ai_overview" && <Sparkles className="size-2.5" />}+ {f === "ai_overview" && <Sparkles />}{FEATURE_SHORT_LABELS[f]}- </span>+ </Badge>))}</div>);@@ -60,18 +63,18 @@ export function DeviceRankCell({// Nothing at allif (position === null && previousPosition === null) {- return <span className="text-base-content/40">-</span>;+ return <span className="text-muted-foreground">-</span>;}// Was ranking, now lostif (position === null && previousPosition !== null) {return (<span className="inline-flex items-center gap-1.5">- <span className="font-mono text-xs text-base-content/40 w-6 text-right">+ <span className="w-6 text-right font-mono text-xs text-muted-foreground">{previousPosition}</span>- <span className="text-base-content/30">→</span>- <span className="font-mono rounded px-1.5 py-0.5 text-xs font-semibold bg-error/20 text-error">+ <span className="text-muted-foreground/60">→</span>+ <span className="font-mono rounded px-1.5 py-0.5 text-xs font-semibold bg-destructive/15 text-destructive">lost</span></span>@@ -85,16 +88,16 @@ export function DeviceRankCell({// Both exist — show old → new with colored badgeconst change = previousPosition - position!;- let badgeClass = "bg-base-200 text-base-content";+ let badgeClass = "bg-muted text-foreground";if (change > 0) badgeClass = "bg-success/20 text-success";if (change < 0) badgeClass = "bg-warning/20 text-warning";return (<span className="inline-flex items-center gap-1.5">- <span className="font-mono text-xs text-base-content/40 w-6 text-right">+ <span className="w-6 text-right font-mono text-xs text-muted-foreground">{previousPosition}</span>- <span className="text-base-content/30">→</span>+ <span className="text-muted-foreground/60">→</span><spanclassName={`font-mono rounded px-1.5 py-0.5 text-xs font-semibold ${badgeClass}`}>@@ -112,14 +115,14 @@ export function DeviceUrlCell({domain: string;}) {if (!result.rankingUrl) {- return <span className="text-base-content/40 text-xs">-</span>;+ return <span className="text-xs text-muted-foreground">-</span>;}return (<ahref={toFullUrl(result.rankingUrl, domain)}target="_blank"rel="noopener noreferrer"- className="link link-hover block truncate text-xs"+ className="block truncate text-xs hover:underline"title={result.rankingUrl}>{toPath(result.rankingUrl)}@@ -133,14 +136,14 @@ const compactFormatter = new Intl.NumberFormat("en-US", {});export function VolumeCell({ value }: { value: number | null }) {- if (value == null) return <span className="text-base-content/40">-</span>;+ if (value == null) return <span className="text-muted-foreground">-</span>;return (<span className="font-mono text-sm">{compactFormatter.format(value)}</span>);}export function CpcCell({ value }: { value: number | null }) {- if (value == null) return <span className="text-base-content/40">-</span>;+ if (value == null) return <span className="text-muted-foreground">-</span>;return <span className="font-mono text-sm">${value.toFixed(2)}</span>;}diff --git a/src/client/features/rank-tracking/RankTrackingTableToolbar.tsx b/src/client/features/rank-tracking/RankTrackingTableToolbar.tsxindex 4b43585c..af114072 100644--- a/src/client/features/rank-tracking/RankTrackingTableToolbar.tsx+++ b/src/client/features/rank-tracking/RankTrackingTableToolbar.tsx@@ -1,7 +1,10 @@-import { CalendarDays, Loader2, SlidersHorizontal, Table } from "lucide-react";+import { CalendarDays, SlidersHorizontal, Table } from "lucide-react";import { SegmentedToggle } from "@/client/components/SegmentedToggle";import { ExportMenu } from "@/client/components/ExportMenu";+import { Badge } from "@/client/components/ui/badge";+import { Button } from "@/client/components/ui/button";import { Progress } from "@/client/components/ui/progress";+import { Spinner } from "@/client/components/ui/spinner";import { MoreMenu } from "./ToolbarMenus";export function RankTrackingTableToolbar({@@ -45,7 +48,7 @@ export function RankTrackingTableToolbar({hasData: boolean;}) {return (- <div className="shrink-0 flex flex-wrap items-center gap-2 px-4 py-2 border-y border-base-300">+ <div className="shrink-0 flex flex-wrap items-center gap-2 px-4 py-2 border-y border-border">{/* History needs at least two checks to compare; until then the togglewould only offer a worse copy of the Latest table. */}{historyAvailable && (@@ -68,23 +71,22 @@ export function RankTrackingTableToolbar({/>)}- <button- className={`btn btn-ghost btn-sm gap-1.5 ${showFilters ? "btn-active" : ""}`}+ <Button+ variant="ghost"+ size="sm"+ aria-pressed={showFilters}+ className="aria-pressed:bg-muted aria-pressed:text-foreground"onClick={onToggleFilters}title="Toggle table filters">- <SlidersHorizontal className="size-3.5" />+ <SlidersHorizontal data-icon="inline-start" />Filters- {activeFilterCount > 0 && (- <span className="badge badge-xs badge-primary border-0 text-primary-content">- {activeFilterCount}- </span>- )}- </button>+ {activeFilterCount > 0 && <Badge size="sm">{activeFilterCount}</Badge>}+ </Button>{isRunning && latestRun ? (- <div className="flex items-center gap-2 text-sm text-base-content/70">- <Loader2 className="size-3.5 animate-spin text-primary" />+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <Spinner className="size-3.5 text-primary" /><span>{latestRun.status === "pending"? "Preparing..."@@ -101,7 +103,7 @@ export function RankTrackingTableToolbar({)}</div>) : (- <span className="text-sm text-base-content/60">+ <span className="text-sm text-muted-foreground">{keywordCount} keywords</span>)}diff --git a/src/client/features/rank-tracking/RankTrackingTrendChart.tsx b/src/client/features/rank-tracking/RankTrackingTrendChart.tsxindex 256bd636..c7a70f1a 100644--- a/src/client/features/rank-tracking/RankTrackingTrendChart.tsx+++ b/src/client/features/rank-tracking/RankTrackingTrendChart.tsx@@ -1,5 +1,8 @@import type { ComponentProps } from "react";import { Line, LineChart, ReferenceArea } from "recharts";+import { TrendingUp } from "lucide-react";+import { EmptyState } from "@/client/components/EmptyState";+import { SegmentedToggle } from "@/client/components/SegmentedToggle";import {ChartGrid,ChartXAxis,@@ -49,7 +52,7 @@ export function RankTrendChart({return (<div className="space-y-1">- <div className="flex items-center justify-between text-[11px] text-base-content/50">+ <div className="flex items-center justify-between text-[11px] text-muted-foreground"><span>Google position (1 = best)</span><span className="inline-flex items-center gap-1">Better <span aria-hidden>↑</span>@@ -135,10 +138,10 @@ export function formatDateLabel(label: unknown): string {/** 30d / 90d / All range toggle shared by the modal and overview charts. */const TREND_RANGES = [- { label: "30d", sinceDays: 30 },- { label: "90d", sinceDays: 90 },- { label: "All", sinceDays: 730 },-] as const;+ { value: "30", icon: null, label: "30d" },+ { value: "90", icon: null, label: "90d" },+ { value: "730", icon: null, label: "All" },+];export function TrendRangeToggle({value,@@ -148,19 +151,27 @@ export function TrendRangeToggle({onChange: (sinceDays: number) => void;}) {return (- <div className="join">- {TREND_RANGES.map((range) => (- <button- key={range.label}- type="button"- className={`btn btn-xs join-item ${- value === range.sinceDays ? "btn-active" : "btn-ghost"- }`}- onClick={() => onChange(range.sinceDays)}- >- {range.label}- </button>- ))}- </div>+ <SegmentedToggle+ showLabels+ items={TREND_RANGES}+ value={String(value)}+ onChange={(next) => onChange(Number(next))}+ />+ );+}++/** Shown instead of a trend chart until there are two checks to connect. */+export function TrendEmptyState({ checks }: { checks: number }) {+ return (+ <EmptyState+ icon={TrendingUp}+ size="sm"+ title={checks === 0 ? "No history yet" : "Only 1 check so far"}+ description={+ checks === 0+ ? "Run a check to start tracking positions over time."+ : "The trend fills in after the next check."+ }+ />);}diff --git a/src/client/features/rank-tracking/ScheduleField.tsx b/src/client/features/rank-tracking/ScheduleField.tsxindex 34acc63d..0833f629 100644--- a/src/client/features/rank-tracking/ScheduleField.tsx+++ b/src/client/features/rank-tracking/ScheduleField.tsx@@ -1,5 +1,19 @@-import { useState } from "react";+import { useId, useState } from "react";import { Info } from "lucide-react";+import { Button } from "@/client/components/ui/button";+import {+ Field,+ FieldDescription,+ FieldLabel,+} from "@/client/components/ui/field";+import { Input } from "@/client/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/client/components/ui/select";import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";import {WEEKDAYS,@@ -8,9 +22,23 @@ import {type LocalScheduleTime,} from "./scheduleTime";+type Schedule = RankTrackingConfig["scheduleInterval"];++const SCHEDULE_ITEMS: { value: Schedule; label: string }[] = [+ { value: "daily", label: "Daily" },+ { value: "weekly", label: "Weekly" },+ { value: "monthly", label: "Monthly (end of month)" },+ { value: "manual", label: "Manual only" },+];++const WEEKDAY_ITEMS = WEEKDAYS.map((day, index) => ({+ value: index,+ label: day,+}));+type Props = {- schedule: RankTrackingConfig["scheduleInterval"];- onScheduleChange: (schedule: RankTrackingConfig["scheduleInterval"]) => void;+ schedule: Schedule;+ onScheduleChange: (schedule: Schedule) => void;scheduleTime: LocalScheduleTime;onScheduleTimeChange: (scheduleTime: LocalScheduleTime) => void;};@@ -21,76 +49,77 @@ export function ScheduleField({scheduleTime,onScheduleTimeChange,}: Props) {+ const id = useId();const [showScheduleTime, setShowScheduleTime] = useState(false);return (- <div className="form-control">- <label className="label">- <span className="label-text font-medium">Schedule</span>- </label>- <select- className="select select-bordered w-full"+ <Field>+ <FieldLabel htmlFor={id}>Schedule</FieldLabel>+ <Select+ items={SCHEDULE_ITEMS}value={schedule}- onChange={(e) => {- const value = e.target.value;- if (- value === "daily" ||- value === "weekly" ||- value === "monthly" ||- value === "manual"- ) {- onScheduleChange(value);- }+ onValueChange={(value) => {+ if (value) onScheduleChange(value);}}>- <option value="daily">Daily</option>- <option value="weekly">Weekly</option>- <option value="monthly">Monthly (end of month)</option>- <option value="manual">Manual only</option>- </select>+ <SelectTrigger id={id} className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {SCHEDULE_ITEMS.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>{schedule !== "manual" && (- <div className="mt-1.5 text-xs text-base-content/60">+ <FieldDescription>{describeSchedule(schedule, scheduleTime)}{!showScheduleTime && (<>{" "}·{" "}- <button+ <Buttontype="button"- className="link"+ variant="link"+ className="h-auto p-0 text-xs"onClick={() => setShowScheduleTime(true)}>change- </button>+ </Button></>)}- </div>+ </FieldDescription>)}{schedule !== "manual" && showScheduleTime && (<>- <div className="mt-2 flex gap-2">+ <div className="flex gap-2">{schedule === "weekly" && (- <select- className="select select-bordered select-sm"- aria-label="Day of week"+ <Select+ items={WEEKDAY_ITEMS}value={scheduleTime.weekday}- onChange={(e) =>- onScheduleTimeChange({- ...scheduleTime,- weekday: Number(e.target.value),- })- }+ onValueChange={(weekday) => {+ if (weekday !== null) {+ onScheduleTimeChange({ ...scheduleTime, weekday });+ }+ }}>- {WEEKDAYS.map((day, index) => (- <option key={day} value={index}>- {day}- </option>- ))}- </select>+ <SelectTrigger aria-label="Day of week">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {WEEKDAY_ITEMS.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>)}- <input+ <Inputtype="time"- className="input input-bordered input-sm"+ className="w-auto"aria-label="Time of day"value={`${String(scheduleTime.hour).padStart(2, "0")}:${String(scheduleTime.minute).padStart(2, "0")}`}onChange={(e) => {@@ -101,17 +130,17 @@ export function ScheduleField({}}/></div>- <div className="mt-1.5 text-xs text-base-content/50">+ <FieldDescription>In your local timezone: {browserTimeZoneLabel()}- </div>+ </FieldDescription></>)}{schedule === "daily" && (- <div className="mt-1.5 flex items-start gap-1.5 text-xs text-warning">- <Info className="size-3.5 shrink-0 mt-0.5" />- <span>Daily checks use 7x more credits than weekly</span>- </div>+ <p className="flex items-start gap-1.5 text-xs text-warning">+ <Info className="mt-0.5 size-3.5 shrink-0" />+ Daily checks use 7x more credits than weekly+ </p>)}- </div>+ </Field>);}diff --git a/src/client/features/rank-tracking/SearchTargetingField.tsx b/src/client/features/rank-tracking/SearchTargetingField.tsxindex cd0285aa..3034abd0 100644--- a/src/client/features/rank-tracking/SearchTargetingField.tsx+++ b/src/client/features/rank-tracking/SearchTargetingField.tsx@@ -1,5 +1,15 @@+import { useId } from "react";import { SerpLocationCombobox } from "@/client/components/SerpLocationCombobox";import { usePrewarmSerpLocations } from "@/client/components/usePrewarmSerpLocations";+import {+ Field,+ FieldDescription,+ FieldError,+ FieldLabel,+ FieldLegend,+ FieldSet,+} from "@/client/components/ui/field";+import { RadioGroup, RadioGroupItem } from "@/client/components/ui/radio-group";type TargetingMode = "national" | "local";@@ -9,47 +19,52 @@ export function SearchTargetingField({locationName,onLocationNameChange,countryCode,+ error,}: {mode: TargetingMode;onModeChange: (mode: TargetingMode) => void;locationName: string | undefined;onLocationNameChange: (locationName: string | undefined) => void;countryCode: string;+ /** The error for the city, shown under the city search. */+ error?: string;}) {+ const id = useId();// Warm the moment Local targeting is in play.usePrewarmSerpLocations(countryCode, mode === "local");return (- <div className="form-control">- <label className="label">- <span className="label-text font-medium">Search Targeting</span>- </label>- <div className="flex gap-2">- <label className="flex items-center gap-2 cursor-pointer">- <input- type="radio"- className="radio radio-sm"- checked={mode === "national"}- onChange={() => {- onModeChange("national");- onLocationNameChange(undefined);- }}- />- <span className="text-sm">National</span>- </label>- <label className="flex items-center gap-2 cursor-pointer">- <input- type="radio"- className="radio radio-sm"- checked={mode === "local"}- onChange={() => onModeChange("local")}- />- <span className="text-sm">Local</span>- </label>- </div>- <p className="text-xs text-base-content/50 mt-1.5">+ <FieldSet className="gap-2" data-invalid={error ? true : undefined}>+ <FieldLegend variant="label" className="mb-0">+ Search Targeting+ </FieldLegend>+ <RadioGroup+ value={mode}+ onValueChange={(value) => {+ if (value === "local") onModeChange("local");+ if (value === "national") {+ onModeChange("national");+ onLocationNameChange(undefined);+ }+ }}+ className="flex gap-4"+ >+ <Field orientation="horizontal" className="w-auto">+ <RadioGroupItem value="national" id={`${id}-national`} />+ <FieldLabel htmlFor={`${id}-national`} className="font-normal">+ National+ </FieldLabel>+ </Field>+ <Field orientation="horizontal" className="w-auto">+ <RadioGroupItem value="local" id={`${id}-local`} />+ <FieldLabel htmlFor={`${id}-local`} className="font-normal">+ Local+ </FieldLabel>+ </Field>+ </RadioGroup>+ <FieldDescription>{mode === "local" ? (<>- <span className="text-success font-medium">Best for:</span> "near+ <span className="font-medium text-success">Best for:</span> "nearme" queries, city/county keywords, service-area pages.</>) : (@@ -57,17 +72,23 @@ export function SearchTargetingField({Local targeting can understate rankings for non-geo-modified terms.</>)}- </p>+ </FieldDescription>{mode === "local" && (- <div className="mt-2">+ <>+ <FieldLabel htmlFor={`${id}-city`} className="sr-only">+ City or region+ </FieldLabel><SerpLocationCombobox+ id={`${id}-city`}value={locationName}onChange={onLocationNameChange}countryCode={countryCode}placeholder="Search cities..."+ invalid={Boolean(error)}/>- </div>+ </>)}- </div>+ {error ? <FieldError>{error}</FieldError> : null}+ </FieldSet>);}diff --git a/src/client/features/rank-tracking/useSaveConfigMutations.ts b/src/client/features/rank-tracking/useSaveConfigMutations.tsindex 0d094ce9..d42d4d96 100644--- a/src/client/features/rank-tracking/useSaveConfigMutations.ts+++ b/src/client/features/rank-tracking/useSaveConfigMutations.ts@@ -10,7 +10,8 @@ import type {RankTrackingConfig,} from "@/types/schemas/rank-tracking";-type ConfigFields = {+export type SaveConfigInput = {+ domain: string;devices: "both" | "desktop" | "mobile";serpDepth: number;locationCode: number;@@ -21,30 +22,32 @@ type ConfigFields = {scheduleTime: RankCheckScheduleTime | undefined;};+function commonFields(input: SaveConfigInput) {+ return {+ domain: input.domain,+ devices: input.devices,+ serpDepth: input.serpDepth,+ locationCode: input.locationCode,+ languageCode: input.languageCode,+ scheduleInterval: input.schedule,+ scheduleTime: input.scheduleTime,+ };+}+export function useSaveConfigMutations(input: {projectId: string;existingConfig?: RankTrackingConfig | null;- fields: ConfigFields;onCreated: (configId: string) => void;onUpdated: () => void;}) {- const { projectId, existingConfig, fields, onCreated, onUpdated } = input;- const common = {- devices: fields.devices,- serpDepth: fields.serpDepth,- locationCode: fields.locationCode,- languageCode: fields.languageCode,- scheduleInterval: fields.schedule,- scheduleTime: fields.scheduleTime,- };+ const { projectId, existingConfig, onCreated, onUpdated } = input;const createMutation = useMutation({- mutationFn: (normalizedDomain: string) =>+ mutationFn: (fields: SaveConfigInput) =>createRankTrackingConfig({data: {projectId,- domain: normalizedDomain,- ...common,+ ...commonFields(fields),locationName:fields.targetingMode === "local" ? fields.locationName : undefined,},@@ -57,13 +60,12 @@ export function useSaveConfigMutations(input: {});const updateMutation = useMutation({- mutationFn: (normalizedDomain: string) =>+ mutationFn: (fields: SaveConfigInput) =>updateRankTrackingConfig({data: {projectId,configId: existingConfig!.id,- domain: normalizedDomain,- ...common,+ ...commonFields(fields),// null clears a previously-set local target; undefined would leave// the old location_name in the DB and silently keep city targeting.locationName:diff --git a/src/routes/_app/p/$projectId/rank-tracking.tsx b/src/routes/_app/p/$projectId/rank-tracking.tsxindex f33b7a2d..34eb1821 100644--- a/src/routes/_app/p/$projectId/rank-tracking.tsx+++ b/src/routes/_app/p/$projectId/rank-tracking.tsx@@ -1,4 +1,5 @@import { createFileRoute, Outlet } from "@tanstack/react-router";+import { PageHeader } from "@/client/components/PageHeader";export const Route = createFileRoute("/_app/p/$projectId/rank-tracking")({component: RankTrackingLayout,@@ -8,12 +9,10 @@ function RankTrackingLayout() {return (<div className="px-4 py-4 pb-24 overflow-auto md:px-6 md:py-6 md:pb-8"><div className="mx-auto max-w-7xl space-y-4">- <div>- <h1 className="text-2xl font-semibold">Rank Tracking</h1>- <p className="text-sm text-base-content/70">- Track keyword positions across domains- </p>- </div>+ <PageHeader+ title="Rank Tracking"+ description="Track keyword positions across domains"+ /><Outlet /></div>diff --git a/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx b/src/routes/_app/p/$projectId/rank-tracking/$configId.tsxindex dc2cca4d..427f1e66 100644--- a/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx+++ b/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx@@ -5,6 +5,8 @@ import { getRankTrackingConfigs } from "@/serverFunctions/rank-tracking";import { RankTrackingDomainDetail } from "@/client/features/rank-tracking/RankTrackingDomainDetail";import { PageLoading } from "@/client/components/Spinner";import { QueryError } from "@/client/components/QueryState";+import { EmptyState } from "@/client/components/EmptyState";+import { Button } from "@/client/components/ui/button";import { RankTrackingConfigModal } from "@/client/features/rank-tracking/RankTrackingConfigModal";import { rankTrackingDetailSearchSchema } from "@/types/schemas/rank-tracking-search";@@ -62,14 +64,16 @@ function RankTrackingConfigRoute() {if (!config) {return (- <>- <p className="text-sm text-base-content/70">- Domain configuration not found.- </p>- <button className="btn btn-ghost btn-sm" onClick={handleBack}>- Back to domains- </button>- </>+ <EmptyState+ kind="no-data"+ title="Domain configuration not found"+ description="This domain was archived or does not exist in this project."+ action={+ <Button variant="outline" size="sm" onClick={handleBack}>+ Back to domains+ </Button>+ }+ />);}@@ -87,7 +91,6 @@ function RankTrackingConfigRoute() {replace: true,});}}- onBack={handleBack}onEdit={() => setShowConfigModal(true)}/>diff --git a/src/shared/rank-tracking.ts b/src/shared/rank-tracking.tsindex bcd06688..a817b81e 100644--- a/src/shared/rank-tracking.ts+++ b/src/shared/rank-tracking.ts@@ -70,10 +70,6 @@ export function costPerSerpAtDepth(: LIVE_BASE_PAGE_COST_USD + (pages - 1) * LIVE_EXTRA_PAGE_COST_USD;}-export function depthToPages(depth: number): number {- return depth / 10;-}-export function pagesToDepth(pages: number): number {return pages * 10;}