Skip to content

Open source alternative to Semrush and Ahrefs

Keep table view state in the URL and scope saved filters by project (EVE-281) (#717)

Ben Senescu7b1b989e1c65
diff --git a/src/client/features/ai-search/components/BrandLookupCitationsCard.tsx b/src/client/features/ai-search/components/BrandLookupCitationsCard.tsx
index 849e1bf9..175e8cef 100644
--- a/src/client/features/ai-search/components/BrandLookupCitationsCard.tsx
+++ b/src/client/features/ai-search/components/BrandLookupCitationsCard.tsx
@@ -48,7 +48,7 @@ export function CitationTabsCard({
const [pagesSort, setPagesSort] = useState<SortingState>(DEFAULT_PAGES_SORT);
const [queriesSort, setQueriesSort] =
useState<SortingState>(DEFAULT_QUERIES_SORT);
- const filters = useBrandLookupFilters();
+ const filters = useBrandLookupFilters(projectId);
// The platform column only earns its place when a tab actually spans >1
// platform; otherwise it repeats one value on every row.
diff --git a/src/client/features/ai-search/useBrandLookupFilters.ts b/src/client/features/ai-search/useBrandLookupFilters.ts
index 986fb78c..94443028 100644
--- a/src/client/features/ai-search/useBrandLookupFilters.ts
+++ b/src/client/features/ai-search/useBrandLookupFilters.ts
@@ -19,11 +19,18 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
-function loadFromStorage<T extends FilterValues>(tab: string, fallback: T): T {
+function storageKey(projectId: string, tab: string) {
+ return `${STORAGE_KEY_PREFIX}${projectId}:${tab}`;
+}
+
+function loadFromStorage<T extends FilterValues>(
+ storageItem: string,
+ fallback: T,
+): T {
const fallbackClone = { ...fallback };
try {
- const raw = localStorage.getItem(`${STORAGE_KEY_PREFIX}${tab}`);
+ const raw = localStorage.getItem(storageItem);
if (!raw) return fallbackClone;
const parsed: unknown = JSON.parse(raw);
@@ -43,24 +50,24 @@ function loadFromStorage<T extends FilterValues>(tab: string, fallback: T): T {
}
}
-function saveToStorage(tab: string, values: FilterValues) {
+function saveToStorage(key: string, values: FilterValues) {
try {
- localStorage.setItem(`${STORAGE_KEY_PREFIX}${tab}`, JSON.stringify(values));
+ localStorage.setItem(key, JSON.stringify(values));
} catch {
// storage full - silently ignore
}
}
-function useTabFilters<T extends FilterValues>(tab: string, emptyValues: T) {
+function useTabFilters<T extends FilterValues>(key: string, emptyValues: T) {
const [defaultValues] = useState<T>(() =>
- loadFromStorage(tab, { ...emptyValues }),
+ loadFromStorage(key, { ...emptyValues }),
);
const form = useForm({ defaultValues });
const values = useStore(form.store, (state) => state.values);
useEffect(() => {
- saveToStorage(tab, values);
- }, [tab, values]);
+ saveToStorage(key, values);
+ }, [key, values]);
const reset = useCallback(() => {
form.reset({ ...emptyValues }, { keepDefaultValues: true });
@@ -74,15 +81,15 @@ function useTabFilters<T extends FilterValues>(tab: string, emptyValues: T) {
};
}
-export function useBrandLookupFilters() {
+export function useBrandLookupFilters(projectId: string) {
const [showFilters, setShowFilters] = useState(false);
const pages = useTabFilters<TopPagesFilterValues>(
- "pages",
+ storageKey(projectId, "pages"),
EMPTY_TOP_PAGES_FILTERS,
);
const queries = useTabFilters<QueriesFilterValues>(
- "queries",
+ storageKey(projectId, "queries"),
EMPTY_QUERIES_FILTERS,
);
diff --git a/src/client/features/backlinks/BacklinksPageContent.tsx b/src/client/features/backlinks/BacklinksPageContent.tsx
index 0a4dba96..3de271ca 100644
--- a/src/client/features/backlinks/BacklinksPageContent.tsx
+++ b/src/client/features/backlinks/BacklinksPageContent.tsx
@@ -102,6 +102,7 @@ export function BacklinksBody({
getSubtitle={(item) => RESEARCH_SCOPE_LABELS[item.scope]}
renderLink={(item, props) => (
<Link
+ from="/p/$projectId/backlinks"
to="/p/$projectId/backlinks"
params={{ projectId }}
search={(prev) => ({
diff --git a/src/client/features/keywords/hooks/useLocalKeywordFilters.ts b/src/client/features/keywords/hooks/useLocalKeywordFilters.ts
index 566a1467..f046de88 100644
--- a/src/client/features/keywords/hooks/useLocalKeywordFilters.ts
+++ b/src/client/features/keywords/hooks/useLocalKeywordFilters.ts
@@ -6,7 +6,9 @@ import {
type KeywordFilterValues,
} from "@/client/features/keywords/keywordResearchTypes";
-const STORAGE_KEY = "keyword-default-filters";
+function storageKey(projectId: string) {
+ return `keyword-default-filters:${projectId}`;
+}
export const filterValuesSchema = z.object({
include: z.string(),
@@ -22,9 +24,9 @@ export const filterValuesSchema = z.object({
intents: z.string().default(""),
});
-function loadFiltersFromStorage(): KeywordFilterValues {
+function loadFiltersFromStorage(projectId: string): KeywordFilterValues {
try {
- const raw = localStorage.getItem(STORAGE_KEY);
+ const raw = localStorage.getItem(storageKey(projectId));
if (!raw) return EMPTY_FILTERS;
return filterValuesSchema.parse(JSON.parse(raw));
} catch {
@@ -32,29 +34,29 @@ function loadFiltersFromStorage(): KeywordFilterValues {
}
}
-function saveFiltersToStorage(filters: KeywordFilterValues) {
+function saveFiltersToStorage(projectId: string, filters: KeywordFilterValues) {
try {
const hasAnyFilter = Object.values(filters).some((v) => v.trim() !== "");
if (hasAnyFilter) {
- localStorage.setItem(STORAGE_KEY, JSON.stringify(filters));
+ localStorage.setItem(storageKey(projectId), JSON.stringify(filters));
} else {
- localStorage.removeItem(STORAGE_KEY);
+ localStorage.removeItem(storageKey(projectId));
}
} catch {
// storage full or unavailable
}
}
-export function useLocalKeywordFilters() {
+export function useLocalKeywordFilters(projectId: string) {
const filtersForm = useForm({
- defaultValues: loadFiltersFromStorage(),
+ defaultValues: loadFiltersFromStorage(projectId),
});
const values = useStore(filtersForm.store, (s) => s.values);
useEffect(() => {
- saveFiltersToStorage(values);
- }, [values]);
+ saveFiltersToStorage(projectId, values);
+ }, [projectId, values]);
const resetFilters = useCallback(() => {
const keys: Array<keyof KeywordFilterValues> = [
diff --git a/src/client/features/keywords/state/useKeywordResearchController.ts b/src/client/features/keywords/state/useKeywordResearchController.ts
index 4677fa87..311f71e6 100644
--- a/src/client/features/keywords/state/useKeywordResearchController.ts
+++ b/src/client/features/keywords/state/useKeywordResearchController.ts
@@ -78,7 +78,7 @@ export function useKeywordResearchController(
filtersForm,
values: filterValues,
resetFilters,
- } = useLocalKeywordFilters();
+ } = useLocalKeywordFilters(input.projectId);
const uiState = useKeywordUiState(
Object.values(filterValues).some((v) => v.trim() !== ""),
);
diff --git a/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx b/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx
index 2f4891eb..1b566d86 100644
--- a/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx
+++ b/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx
@@ -4,20 +4,11 @@ import { LOCATIONS } from "@/client/features/keywords/locations";
import { devicesLabel, scheduleLabel } from "@/shared/rank-tracking";
import { formatNextCheck } from "./scheduleTime";
import { formatLocationLabel } from "@/shared/keyword-locations";
-import type {
- ComparePeriod,
- RankTrackingConfig,
-} from "@/types/schemas/rank-tracking";
-
-const COMPARE_PERIODS: ReadonlySet<string> = new Set([
- "1d",
- "7d",
- "30d",
- "90d",
-]);
-function isComparePeriod(v: string): v is ComparePeriod {
- return COMPARE_PERIODS.has(v);
-}
+import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";
+import {
+ comparePeriodSchema,
+ type ComparePeriod,
+} from "@/types/schemas/rank-tracking-search";
export function RankTrackingDetailHeader({
config,
@@ -90,8 +81,8 @@ export function RankTrackingDetailHeader({
title="Comparison period"
value={comparePeriod}
onChange={(e) => {
- if (isComparePeriod(e.target.value))
- onComparePeriodChange(e.target.value);
+ const parsed = comparePeriodSchema.safeParse(e.target.value);
+ if (parsed.success) onComparePeriodChange(parsed.data);
}}
>
<option value="1d">vs yesterday</option>
diff --git a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx
index 89439995..b1cb067e 100644
--- a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx
+++ b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx
@@ -19,10 +19,12 @@ import {
} from "./RankTrackingHistoryMatrix";
import { RankTrackingTableToolbar } from "./RankTrackingTableToolbar";
import { exportRankTracking } from "./RankTrackingTableParts";
-import type {
- RankTrackingConfig,
- ComparePeriod,
-} from "@/types/schemas/rank-tracking";
+import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";
+import {
+ rankTrackingDetailSearchSchema,
+ type ComparePeriod,
+ type RankTrackingDetailSearch,
+} from "@/types/schemas/rank-tracking-search";
import { AddKeywordsPanel } from "./AddKeywordsPanel";
import {
FilterPanel,
@@ -35,6 +37,12 @@ import { CheckConfirmModal } from "./CheckConfirmModal";
import { useMetricsRefresh } from "./useMetricsRefresh";
import { useRankCheckTrigger } from "./useRankCheckTrigger";
import { useRankRunPolling } from "./useRankRunPolling";
+import {
+ filterValuesFromSearch,
+ filterValuesToSearch,
+ normalizeFilterValues,
+} from "@/client/lib/filterSearchParams";
+import { useDebouncedDraft } from "@/client/hooks/useDebouncedDraft";
function deviceVisibility(
devices: RankTrackingConfig["devices"],
@@ -52,14 +60,26 @@ function deviceVisibility(
};
}
+function defaultComparePeriod(
+ interval: RankTrackingConfig["scheduleInterval"],
+): ComparePeriod {
+ if (interval === "daily") return "1d";
+ if (interval === "monthly") return "30d";
+ return "7d";
+}
+
export function RankTrackingDomainDetail({
config,
projectId,
+ search,
+ onSearchChange,
onBack,
onEdit,
}: {
config: RankTrackingConfig;
projectId: string;
+ search: RankTrackingDetailSearch;
+ onSearchChange: (update: Partial<RankTrackingDetailSearch>) => void;
onBack: () => void;
onEdit: () => void;
}) {
@@ -67,18 +87,24 @@ export function RankTrackingDomainDetail({
const queryClient = useQueryClient();
const [showAddKeywords, setShowAddKeywords] = useState(false);
const [showFilters, setShowFilters] = useState(false);
- const [filters, setFilters] = useState<Filters>(EMPTY_FILTERS);
- const [comparePeriod, setComparePeriod] = useState<ComparePeriod>(
- config.scheduleInterval === "daily"
- ? "1d"
- : config.scheduleInterval === "monthly"
- ? "30d"
- : "7d",
+ const filters = useMemo(
+ () => filterValuesFromSearch(search, EMPTY_FILTERS),
+ [search],
);
- const [activeDevice, setActiveDevice] = useState<"desktop" | "mobile">(
- config.devices === "mobile" ? "mobile" : "desktop",
+ const setFilters = (next: Filters) =>
+ onSearchChange(filterValuesToSearch<RankTrackingDetailSearch>(next));
+ // Held here, not in the panel, so closing the panel keeps a pending edit.
+ const [filterDraft, setFilterDraft] = useDebouncedDraft(
+ filters,
+ setFilters,
+ (values) => normalizeFilterValues(values, EMPTY_FILTERS),
);
- const [viewMode, setViewMode] = useState<"table" | "history">("table");
+ const comparePeriod =
+ search.compare ?? defaultComparePeriod(config.scheduleInterval);
+ // A single-device config has only one device to show.
+ const activeDevice =
+ config.devices === "both" ? (search.device ?? "desktop") : config.devices;
+ const viewMode = search.view ?? "table";
const { data: resultsData, isLoading: resultsLoading } = useQuery({
queryKey: ["rankTrackingResults", projectId, config.id, comparePeriod],
@@ -179,6 +205,12 @@ export function RankTrackingDomainDetail({
);
const activeFilterCount = countActiveFilters(filters);
const defaultSortId = showDesktop ? "desktopPosition" : "mobilePosition";
+ // A position sort for the hidden device falls back to the default.
+ const sortId =
+ (search.sort === "desktopPosition" && !showDesktop) ||
+ (search.sort === "mobilePosition" && !showMobile)
+ ? undefined
+ : search.sort;
// Fall back to the table if history disappears (e.g. device switch).
const effectiveViewMode = historyAvailable ? viewMode : "table";
@@ -232,9 +264,12 @@ export function RankTrackingDomainDetail({
costEstimate={costEstimate}
hasBothDevices={hasBothDevices}
activeDevice={activeDevice}
- onActiveDeviceChange={setActiveDevice}
+ onActiveDeviceChange={(device) =>
+ // The sort column is per device, so a device switch resets it.
+ onSearchChange({ device, sort: undefined, order: undefined })
+ }
comparePeriod={comparePeriod}
- onComparePeriodChange={setComparePeriod}
+ onComparePeriodChange={(compare) => onSearchChange({ compare })}
onEdit={onEdit}
onToggleAddKeywords={() => setShowAddKeywords((c) => !c)}
/>
@@ -268,7 +303,9 @@ export function RankTrackingDomainDetail({
latestRun={latestRun}
keywordCount={filtered.length}
viewMode={effectiveViewMode}
- onViewModeChange={setViewMode}
+ onViewModeChange={(view) =>
+ onSearchChange({ view: view === "history" ? view : undefined })
+ }
historyAvailable={historyAvailable}
onExport={() =>
exportRankTracking({
@@ -310,8 +347,8 @@ export function RankTrackingDomainDetail({
{/* Filters panel */}
{showFilters && (
<FilterPanel
- filters={filters}
- setFilters={setFilters}
+ draft={filterDraft}
+ setDraft={setFilterDraft}
activeFilterCount={activeFilterCount}
onReset={() => setFilters(EMPTY_FILTERS)}
/>
@@ -335,7 +372,19 @@ export function RankTrackingDomainDetail({
resultsLoading={resultsLoading}
showDesktop={showDesktop}
showMobile={showMobile}
- defaultSortId={defaultSortId}
+ sorting={
+ sortId
+ ? [{ id: sortId, desc: search.order === "desc" }]
+ : [{ id: defaultSortId, desc: false }]
+ }
+ onSortingChange={(sorting) => {
+ onSearchChange({
+ sort: rankTrackingDetailSearchSchema.shape.sort.parse(
+ sorting[0]?.id,
+ ),
+ order: sorting[0]?.desc ? "desc" : undefined,
+ });
+ }}
domain={config.domain}
configId={config.id}
projectId={projectId}
diff --git a/src/client/features/rank-tracking/RankTrackingDomainList.tsx b/src/client/features/rank-tracking/RankTrackingDomainList.tsx
index 84f2100f..1cee37fe 100644
--- a/src/client/features/rank-tracking/RankTrackingDomainList.tsx
+++ b/src/client/features/rank-tracking/RankTrackingDomainList.tsx
@@ -23,11 +23,12 @@ import {
applyDomainListFilters,
countActiveDomainListFilters,
DomainListFilterBar,
- EMPTY_DOMAIN_LIST_FILTERS,
getDomainListFilterOptions,
type DomainListFilters,
} from "./RankTrackingFilters";
import { Skeleton } from "@/client/components/Skeleton";
+import { useDebouncedDraft } from "@/client/hooks/useDebouncedDraft";
+import type { RankTrackingListSearch } from "@/types/schemas/rank-tracking-search";
type ConfigSummary = Awaited<
ReturnType<typeof getRankTrackingConfigSummaries>
@@ -40,31 +41,68 @@ const FILTER_BAR_MIN_DOMAINS = 6;
export function RankTrackingDomainList({
projectId,
+ search,
+ onSearchChange,
onAddDomain,
}: {
projectId: string;
+ search: RankTrackingListSearch;
+ onSearchChange: (next: RankTrackingListSearch) => void;
onAddDomain: () => void;
}) {
const queryClient = useQueryClient();
const [archiveTarget, setArchiveTarget] = useState<ConfigSummary | null>(
null,
);
- const [filters, setFilters] = useState<DomainListFilters>(
- EMPTY_DOMAIN_LIST_FILTERS,
+ const [query, setQuery] = useDebouncedDraft(search.q ?? "", (q) =>
+ onSearchChange({ ...search, q: q || undefined }),
);
+ const filters: DomainListFilters = {
+ query,
+ device: search.device ?? "all",
+ locationCode: search.loc ? String(search.loc) : "all",
+ };
+ const setFilters = (next: DomainListFilters) => {
+ setQuery(next.query);
+ if (
+ next.device === filters.device &&
+ next.locationCode === filters.locationCode
+ ) {
+ return;
+ }
+ // Carry the typed query too, so the navigation does not revert it.
+ onSearchChange({
+ q: next.query || undefined,
+ device: next.device === "all" ? undefined : next.device,
+ loc: next.locationCode === "all" ? undefined : Number(next.locationCode),
+ });
+ };
+ const clearFilters = () => {
+ setQuery("");
+ onSearchChange({});
+ };
const { data: summaries, isPending } = useQuery({
queryKey: ["rankTrackingConfigSummaries", projectId],
queryFn: () => getRankTrackingConfigSummaries({ data: { projectId } }),
});
const allSummaries = useMemo(() => summaries ?? [], [summaries]);
- const filteredSummaries = useMemo(
- () => applyDomainListFilters(allSummaries, filters),
- [allSummaries, filters],
- );
- const filterOptions = useMemo(
- () => getDomainListFilterOptions(allSummaries),
- [allSummaries],
- );
+ const filteredSummaries = applyDomainListFilters(allSummaries, filters);
+ const filterOptions = useMemo(() => {
+ const options = getDomainListFilterOptions(allSummaries);
+ // A shared link can filter on a value no tracked domain has. Show it so
+ // the select matches the URL.
+ const { device, loc } = search;
+ if (device && !options.devices.some((o) => o.value === device)) {
+ options.devices.push({ value: device, label: devicesLabel(device) });
+ }
+ if (loc && !options.locations.some((o) => o.value === String(loc))) {
+ options.locations.push({
+ value: String(loc),
+ label: LOCATIONS[loc] ?? String(loc),
+ });
+ }
+ return options;
+ }, [allSummaries, search]);
const activeFilterCount = countActiveDomainListFilters(filters);
const archiveMutation = useMutation({
@@ -104,7 +142,7 @@ export function RankTrackingDomainList({
options={filterOptions}
activeFilterCount={activeFilterCount}
onChange={setFilters}
- onReset={() => setFilters(EMPTY_DOMAIN_LIST_FILTERS)}
+ onReset={clearFilters}
/>
)}
<div className="divide-y divide-base-300 border-t border-base-300">
@@ -142,10 +180,7 @@ export function RankTrackingDomainList({
Try clearing search or adjusting filters.
</p>
</div>
- <button
- className="btn btn-ghost btn-xs"
- onClick={() => setFilters(EMPTY_DOMAIN_LIST_FILTERS)}
- >
+ <button className="btn btn-ghost btn-xs" onClick={clearFilters}>
Clear filters
</button>
</div>
diff --git a/src/client/features/rank-tracking/RankTrackingFilters.tsx b/src/client/features/rank-tracking/RankTrackingFilters.tsx
index 06c58614..93ac3317 100644
--- a/src/client/features/rank-tracking/RankTrackingFilters.tsx
+++ b/src/client/features/rank-tracking/RankTrackingFilters.tsx
@@ -8,19 +8,20 @@ type DomainListFilterOption = {
label: string;
};
+/** `draft` is the unapplied panel state; it reaches the URL after a pause. */
export function FilterPanel({
- filters,
- setFilters,
+ draft,
+ setDraft,
activeFilterCount,
onReset,
}: {
- filters: Filters;
- setFilters: (f: Filters) => void;
+ draft: Filters;
+ setDraft: (f: Filters) => void;
activeFilterCount: number;
onReset: () => void;
}) {
const update = (key: keyof Filters, value: string) =>
- setFilters({ ...filters, [key]: value });
+ 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">
@@ -50,7 +51,7 @@ export function FilterPanel({
<input
className="input input-bordered input-sm w-full bg-base-100"
placeholder="e.g. seo, tool"
- value={filters.include}
+ value={draft.include}
onChange={(e) => update("include", e.target.value)}
/>
</div>
@@ -61,7 +62,7 @@ export function FilterPanel({
<input
className="input input-bordered input-sm w-full bg-base-100"
placeholder="e.g. free, cheap"
- value={filters.exclude}
+ value={draft.exclude}
onChange={(e) => update("exclude", e.target.value)}
/>
</div>
@@ -69,15 +70,15 @@ export function FilterPanel({
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
<RangeFilter
title="Desktop position"
- minValue={filters.minDesktopPos}
- maxValue={filters.maxDesktopPos}
+ minValue={draft.minDesktopPos}
+ maxValue={draft.maxDesktopPos}
onMinChange={(v) => update("minDesktopPos", v)}
onMaxChange={(v) => update("maxDesktopPos", v)}
/>
<RangeFilter
title="Mobile position"
- minValue={filters.minMobilePos}
- maxValue={filters.maxMobilePos}
+ minValue={draft.minMobilePos}
+ maxValue={draft.maxMobilePos}
onMinChange={(v) => update("minMobilePos", v)}
onMaxChange={(v) => update("maxMobilePos", v)}
/>
@@ -85,22 +86,22 @@ export function FilterPanel({
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
<RangeFilter
title="Volume"
- minValue={filters.minVolume}
- maxValue={filters.maxVolume}
+ minValue={draft.minVolume}
+ maxValue={draft.maxVolume}
onMinChange={(v) => update("minVolume", v)}
onMaxChange={(v) => update("maxVolume", v)}
/>
<RangeFilter
title="Keyword difficulty"
- minValue={filters.minKd}
- maxValue={filters.maxKd}
+ minValue={draft.minKd}
+ maxValue={draft.maxKd}
onMinChange={(v) => update("minKd", v)}
onMaxChange={(v) => update("maxKd", v)}
/>
<RangeFilter
title="CPC"
- minValue={filters.minCpc}
- maxValue={filters.maxCpc}
+ minValue={draft.minCpc}
+ maxValue={draft.maxCpc}
onMinChange={(v) => update("minCpc", v)}
onMaxChange={(v) => update("maxCpc", v)}
/>
diff --git a/src/client/features/rank-tracking/RankTrackingTable.tsx b/src/client/features/rank-tracking/RankTrackingTable.tsx
index de85d6b2..06ee3158 100644
--- a/src/client/features/rank-tracking/RankTrackingTable.tsx
+++ b/src/client/features/rank-tracking/RankTrackingTable.tsx
@@ -12,6 +12,7 @@ import {
TableBulkExportMenu,
} from "@/client/components/table/TableBulkActionBar";
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import type { SortingState } from "@tanstack/react-table";
import { removeTrackingKeywords } from "@/serverFunctions/rank-tracking";
import type { RankTrackingRow } from "@/types/schemas/rank-tracking";
import { useRankTrackingColumns } from "./RankTrackingColumns";
@@ -28,7 +29,8 @@ export function RankTrackingTable({
resultsLoading,
showDesktop,
showMobile,
- defaultSortId,
+ sorting,
+ onSortingChange,
domain,
configId,
projectId,
@@ -42,7 +44,8 @@ export function RankTrackingTable({
resultsLoading: boolean;
showDesktop: boolean;
showMobile: boolean;
- defaultSortId: string;
+ sorting: SortingState;
+ onSortingChange: (sorting: SortingState) => void;
domain: string;
configId: string;
projectId: string;
@@ -79,9 +82,13 @@ export function RankTrackingTable({
const table = useAppTable({
data: rows,
columns,
- initialState: {
- sorting: [{ id: defaultSortId, desc: false }],
- },
+ state: { sorting },
+ onSortingChange: (updater) =>
+ onSortingChange(
+ typeof updater === "function" ? updater(sorting) : updater,
+ ),
+ // The URL has no value for "unsorted", so a column stays sorted.
+ enableSortingRemoval: false,
withSorting: true,
getRowId: (row) => row.trackingKeywordId,
enableRowSelection: true,
diff --git a/src/client/features/saved-keywords/useSavedKeywordsFilters.ts b/src/client/features/saved-keywords/useSavedKeywordsFilters.ts
index b017b73d..af9150a7 100644
--- a/src/client/features/saved-keywords/useSavedKeywordsFilters.ts
+++ b/src/client/features/saved-keywords/useSavedKeywordsFilters.ts
@@ -2,7 +2,6 @@ import { useForm, useStore } from "@tanstack/react-form";
import { useCallback } from "react";
import {
countActiveSavedKeywordsFilters,
- EMPTY_SAVED_KEYWORDS_FILTERS,
type SavedKeywordsFilterValues,
} from "./savedKeywordsFilterTypes";
@@ -17,8 +16,10 @@ const FILTER_KEYS: Array<keyof SavedKeywordsFilterValues> = [
"maxKd",
];
-export function useSavedKeywordsFilters() {
- const filtersForm = useForm({ defaultValues: EMPTY_SAVED_KEYWORDS_FILTERS });
+export function useSavedKeywordsFilters(
+ initialValues: SavedKeywordsFilterValues,
+) {
+ const filtersForm = useForm({ defaultValues: initialValues });
const values = useStore(filtersForm.store, (s) => s.values);
const activeFilterCount = countActiveSavedKeywordsFilters(values);
diff --git a/src/client/features/search-performance/SearchPerformancePage.tsx b/src/client/features/search-performance/SearchPerformancePage.tsx
index 9bd9171f..177d0cf5 100644
--- a/src/client/features/search-performance/SearchPerformancePage.tsx
+++ b/src/client/features/search-performance/SearchPerformancePage.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { Link } from "@tanstack/react-router";
import {
keepPreviousData,
@@ -10,6 +10,7 @@ import { toast } from "sonner";
import { TableExportMenu } from "@/client/components/table/TableBulkActionBar";
import { TablePagination } from "@/client/components/table/TablePagination";
import { GoogleConnectionCard } from "@/client/features/integrations/GoogleConnectionCard";
+import { SearchPerformanceSelects } from "@/client/features/search-performance/SearchPerformanceSelects";
import { SearchPerformanceLoadingState } from "@/client/features/search-performance/SearchPerformanceLoadingState";
import {
tableQueryOptions,
@@ -27,7 +28,6 @@ import {
TabButton,
TotalsCards,
type ExportTarget,
- type Tab,
} from "@/client/features/search-performance/SearchPerformanceParts";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
import {
@@ -35,87 +35,72 @@ import {
getSearchPerformanceReport,
} from "@/serverFunctions/searchPerformance";
import {
- GSC_DEVICES,
SEARCH_PERFORMANCE_DEFAULT_PAGE_SIZE,
SEARCH_PERFORMANCE_PAGE_SIZES,
- SEARCH_PERFORMANCE_RANGES,
- type SearchPerformanceDateRange,
- type SearchPerformanceDevice,
+ type SearchPerformanceSearch,
+ type SearchPerformanceTab,
type SearchPerformanceTableDimension,
} from "@/types/schemas/search-performance";
-const RANGE_LABELS: Record<SearchPerformanceDateRange, string> = {
- last_7_days: "Last 7 days",
- last_28_days: "Last 28 days",
- last_3_months: "Last 3 months",
-};
-const RANGE_OPTIONS = SEARCH_PERFORMANCE_RANGES.map((value) => ({
- value,
- label: RANGE_LABELS[value],
-}));
-
-const DEVICE_LABELS: Record<SearchPerformanceDevice, string> = {
- DESKTOP: "Desktop",
- MOBILE: "Mobile",
- TABLET: "Tablet",
-};
-const DEVICE_OPTIONS = GSC_DEVICES.map((value) => ({
- value,
- label: DEVICE_LABELS[value],
-}));
-
-// Sentinel for "no filter" in the selects; never sent to the server.
-const ALL = "ALL";
-
-function isDateRange(value: string): value is SearchPerformanceDateRange {
- return SEARCH_PERFORMANCE_RANGES.some((option) => option === value);
-}
-
-function isDevice(value: string): value is SearchPerformanceDevice {
- return GSC_DEVICES.some((option) => option === value);
-}
-
-function tabDimension(tab: Tab): SearchPerformanceTableDimension {
+function tabDimension(
+ tab: SearchPerformanceTab,
+): SearchPerformanceTableDimension {
return tab === "pages" ? "page" : "query";
}
-// The server filter payload: drop device/country when set to the "ALL" sentinel.
-function buildFilterInput(
- range: SearchPerformanceDateRange,
- device: SearchPerformanceDevice | typeof ALL,
- country: string,
-): FilterInput {
+function buildFilterInput({
+ range = "last_28_days",
+ device,
+ country,
+}: Pick<SearchPerformanceSearch, "range" | "device" | "country">): FilterInput {
return {
dateRange: range,
- ...(device === ALL ? {} : { device }),
- ...(country === ALL ? {} : { country }),
+ ...(device ? { device } : {}),
+ ...(country ? { country } : {}),
};
}
-export function SearchPerformancePage({ projectId }: { projectId: string }) {
+export function SearchPerformancePage({
+ projectId,
+ search,
+ onSearchChange,
+}: {
+ projectId: string;
+ search: SearchPerformanceSearch;
+ onSearchChange: (update: Partial<SearchPerformanceSearch>) => void;
+}) {
const queryClient = useQueryClient();
- const [range, setRange] =
- useState<SearchPerformanceDateRange>("last_28_days");
- const [device, setDevice] = useState<SearchPerformanceDevice | typeof ALL>(
- ALL,
+ const { range, device, country } = search;
+ const textFilters = useMemo<TextFilters>(
+ () => ({
+ pageFilter: search.pageText
+ ? {
+ operator: search.pageMatch ?? "contains",
+ expression: search.pageText,
+ }
+ : undefined,
+ queryFilter: search.queryText
+ ? {
+ operator: search.queryMatch ?? "contains",
+ expression: search.queryText,
+ }
+ : undefined,
+ }),
+ [search.pageText, search.pageMatch, search.queryText, search.queryMatch],
);
- const [country, setCountry] = useState<string>(ALL);
- const [textFilters, setTextFilters] = useState<TextFilters>({});
const [showFilters, setShowFilters] = useState(false);
const activeFilterCount =
Number(Boolean(textFilters.pageFilter)) +
Number(Boolean(textFilters.queryFilter)) +
- Number(country !== ALL) +
- Number(device !== ALL) +
- Number(range !== "last_28_days");
- const [tab, setTab] = useState<Tab>("striking");
- const [page, setPage] = useState(1);
- const [pageSize, setPageSize] = useState<number>(
- SEARCH_PERFORMANCE_DEFAULT_PAGE_SIZE,
- );
+ Number(Boolean(country)) +
+ Number(Boolean(device)) +
+ Number(range !== undefined && range !== "last_28_days");
+ const tab = search.tab ?? "striking";
+ const page = search.page ?? 1;
+ const pageSize = search.size ?? SEARCH_PERFORMANCE_DEFAULT_PAGE_SIZE;
const filterInput = {
- ...buildFilterInput(range, device, country),
+ ...buildFilterInput({ range, device, country }),
...textFilters,
};
@@ -147,7 +132,7 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {
"query",
1,
SEARCH_PERFORMANCE_DEFAULT_PAGE_SIZE,
- { ...buildFilterInput(range, device, country), ...textFilters },
+ { ...buildFilterInput({ range, device, country }), ...textFilters },
),
);
}, [
@@ -178,18 +163,30 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {
const filtersPanel = (
<SearchPerformanceTextFilters
+ // Remount on URL changes (back/forward) so the draft matches.
+ key={JSON.stringify(textFilters)}
value={textFilters}
activeFilterCount={activeFilterCount}
onApply={(filters) => {
- setPage(1);
- setTextFilters(filters);
+ onSearchChange({
+ page: undefined,
+ pageText: filters.pageFilter?.expression,
+ pageMatch: filters.pageFilter?.operator,
+ queryText: filters.queryFilter?.expression,
+ queryMatch: filters.queryFilter?.operator,
+ });
}}
onReset={() => {
- setPage(1);
- setTextFilters({});
- setCountry(ALL);
- setDevice(ALL);
- setRange("last_28_days");
+ onSearchChange({
+ page: undefined,
+ pageText: undefined,
+ pageMatch: undefined,
+ queryText: undefined,
+ queryMatch: undefined,
+ country: undefined,
+ device: undefined,
+ range: undefined,
+ });
}}
/>
);
@@ -241,10 +238,9 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {
<div role="tablist" className="tabs tabs-border w-fit">
<TabButton
active={tab === "striking"}
- onClick={() => {
- setPage(1);
- setTab("striking");
- }}
+ onClick={() =>
+ onSearchChange({ tab: "striking", page: undefined })
+ }
label={
reportQuery.isPlaceholderData
? "Striking distance"
@@ -253,18 +249,16 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {
/>
<TabButton
active={tab === "queries"}
- onClick={() => {
- setPage(1);
- setTab("queries");
- }}
+ onClick={() =>
+ onSearchChange({ tab: "queries", page: undefined })
+ }
label="Queries"
/>
<TabButton
active={tab === "pages"}
- onClick={() => {
- setPage(1);
- setTab("pages");
- }}
+ onClick={() =>
+ onSearchChange({ tab: "pages", page: undefined })
+ }
label="Pages"
/>
</div>
@@ -306,63 +300,11 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {
{reportQuery.isFetching && !reportQuery.isPending ? (
<Loader2 className="size-4 animate-spin text-base-content/40" />
) : null}
- <div className="ml-auto flex flex-wrap items-center justify-end gap-2">
- <select
- className="select select-bordered select-sm w-36"
- value={device}
- onChange={(event) => {
- setPage(1);
- setDevice(
- isDevice(event.target.value) ? event.target.value : ALL,
- );
- }}
- aria-label="Device filter"
- >
- <option value={ALL}>All devices</option>
- {DEVICE_OPTIONS.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- <select
- className="select select-bordered select-sm w-36"
- value={country}
- onChange={(event) => {
- setPage(1);
- setCountry(event.target.value);
- }}
- aria-label="Country filter"
- >
- <option value={ALL}>All countries</option>
- {country !== ALL &&
- !report.countries.some((row) => row.key === country) ? (
- <option value={country}>{country.toUpperCase()}</option>
- ) : null}
- {report.countries.map((row) => (
- <option key={row.key} value={row.key}>
- {row.key.toUpperCase()}
- </option>
- ))}
- </select>
- <select
- className="select select-bordered select-sm w-36"
- value={range}
- onChange={(event) => {
- if (isDateRange(event.target.value)) {
- setPage(1);
- setRange(event.target.value);
- }
- }}
- aria-label="Date range"
- >
- {RANGE_OPTIONS.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- </div>
+ <SearchPerformanceSelects
+ search={search}
+ countries={report.countries}
+ onSearchChange={onSearchChange}
+ />
</div>
{showFilters ? filtersPanel : null}
@@ -404,11 +346,12 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {
}
hasNextPage={hasNextPage}
isLoading={tableQuery.isFetching}
- onPageChange={setPage}
- onPageSizeChange={(size) => {
- setPage(1);
- setPageSize(size);
- }}
+ onPageChange={(nextPage) =>
+ onSearchChange({ page: nextPage })
+ }
+ onPageSizeChange={(size) =>
+ onSearchChange({ page: undefined, size })
+ }
/>
</>
)}
diff --git a/src/client/features/search-performance/SearchPerformanceParts.tsx b/src/client/features/search-performance/SearchPerformanceParts.tsx
index f779be2f..8e38f213 100644
--- a/src/client/features/search-performance/SearchPerformanceParts.tsx
+++ b/src/client/features/search-performance/SearchPerformanceParts.tsx
@@ -30,7 +30,6 @@ import {
} from "@/types/schemas/search-performance";
import { saveKeywords } from "@/serverFunctions/keywords";
-export type Tab = "striking" | "queries" | "pages";
export type ExportTarget = "csv" | "sheets";
type ExportTable = { filename: string; headers: string[]; rows: CsvValue[][] };
diff --git a/src/client/features/search-performance/SearchPerformanceSelects.tsx b/src/client/features/search-performance/SearchPerformanceSelects.tsx
new file mode 100644
index 00000000..827a2460
--- /dev/null
+++ b/src/client/features/search-performance/SearchPerformanceSelects.tsx
@@ -0,0 +1,118 @@
+import {
+ GSC_DEVICES,
+ SEARCH_PERFORMANCE_RANGES,
+ type SearchPerformanceDateRange,
+ type SearchPerformanceDevice,
+ type SearchPerformanceSearch,
+} from "@/types/schemas/search-performance";
+
+const RANGE_LABELS: Record<SearchPerformanceDateRange, string> = {
+ last_7_days: "Last 7 days",
+ last_28_days: "Last 28 days",
+ last_3_months: "Last 3 months",
+};
+const RANGE_OPTIONS = SEARCH_PERFORMANCE_RANGES.map((value) => ({
+ value,
+ label: RANGE_LABELS[value],
+}));
+
+const DEVICE_LABELS: Record<SearchPerformanceDevice, string> = {
+ DESKTOP: "Desktop",
+ MOBILE: "Mobile",
+ TABLET: "Tablet",
+};
+const DEVICE_OPTIONS = GSC_DEVICES.map((value) => ({
+ value,
+ label: DEVICE_LABELS[value],
+}));
+
+// Sentinel for "no filter" in the selects; never written to the URL.
+const ALL = "ALL";
+
+function isDateRange(value: string): value is SearchPerformanceDateRange {
+ return SEARCH_PERFORMANCE_RANGES.some((option) => option === value);
+}
+
+function isDevice(value: string): value is SearchPerformanceDevice {
+ return GSC_DEVICES.some((option) => option === value);
+}
+
+/** Device, country, and date range selects of the table toolbar. */
+export function SearchPerformanceSelects({
+ search,
+ countries,
+ onSearchChange,
+}: {
+ search: SearchPerformanceSearch;
+ countries: { key: string }[];
+ onSearchChange: (update: Partial<SearchPerformanceSearch>) => void;
+}) {
+ const device = search.device ?? ALL;
+ const country = search.country ?? ALL;
+ const range = search.range ?? "last_28_days";
+ return (
+ <div className="ml-auto flex flex-wrap items-center justify-end gap-2">
+ <select
+ className="select select-bordered select-sm w-36"
+ value={device}
+ onChange={(event) =>
+ onSearchChange({
+ page: undefined,
+ device: isDevice(event.target.value)
+ ? event.target.value
+ : undefined,
+ })
+ }
+ aria-label="Device filter"
+ >
+ <option value={ALL}>All devices</option>
+ {DEVICE_OPTIONS.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ <select
+ className="select select-bordered select-sm w-36"
+ value={country}
+ onChange={(event) =>
+ onSearchChange({
+ page: undefined,
+ country:
+ event.target.value === ALL ? undefined : event.target.value,
+ })
+ }
+ aria-label="Country filter"
+ >
+ <option value={ALL}>All countries</option>
+ {country !== ALL && !countries.some((row) => row.key === country) ? (
+ <option value={country}>{country.toUpperCase()}</option>
+ ) : null}
+ {countries.map((row) => (
+ <option key={row.key} value={row.key}>
+ {row.key.toUpperCase()}
+ </option>
+ ))}
+ </select>
+ <select
+ className="select select-bordered select-sm w-36"
+ value={range}
+ onChange={(event) => {
+ if (isDateRange(event.target.value)) {
+ onSearchChange({
+ page: undefined,
+ range: event.target.value,
+ });
+ }
+ }}
+ aria-label="Date range"
+ >
+ {RANGE_OPTIONS.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ );
+}
diff --git a/src/client/hooks/useDebouncedDraft.ts b/src/client/hooks/useDebouncedDraft.ts
new file mode 100644
index 00000000..dc0b832f
--- /dev/null
+++ b/src/client/hooks/useDebouncedDraft.ts
@@ -0,0 +1,42 @@
+import { useEffect, useRef, useState } from "react";
+
+/**
+ * Local draft of a URL-backed value for live-typed inputs. Edits stay local
+ * and commit after a pause, so each keystroke does not navigate. The draft
+ * follows URL changes it did not cause (back/forward, "Clear all").
+ */
+export function useDebouncedDraft<T>(
+ applied: T,
+ commit: (value: T) => void,
+ /** The draft as the URL will store it ("10." becomes "10"). */
+ normalize: (value: T) => T = (value) => value,
+ delayMs = 350,
+) {
+ const [draft, setDraft] = useState(applied);
+ const appliedKey = JSON.stringify(applied);
+ const [syncedKey, setSyncedKey] = useState(appliedKey);
+ // True from a commit until the URL shows it.
+ const [awaitingCommit, setAwaitingCommit] = useState(false);
+ const callbacksRef = useRef({ commit, normalize });
+ useEffect(() => {
+ callbacksRef.current = { commit, normalize };
+ });
+
+ if (syncedKey !== appliedKey) {
+ setSyncedKey(appliedKey);
+ if (awaitingCommit) setAwaitingCommit(false);
+ else setDraft(applied);
+ }
+
+ useEffect(() => {
+ const next = callbacksRef.current.normalize(draft);
+ if (JSON.stringify(next) === appliedKey) return;
+ const timer = window.setTimeout(() => {
+ setAwaitingCommit(true);
+ callbacksRef.current.commit(next);
+ }, delayMs);
+ return () => window.clearTimeout(timer);
+ }, [appliedKey, delayMs, draft]);
+
+ return [draft, setDraft] as const;
+}
diff --git a/src/client/lib/filterSearchParams.ts b/src/client/lib/filterSearchParams.ts
new file mode 100644
index 00000000..4ae135d3
--- /dev/null
+++ b/src/client/lib/filterSearchParams.ts
@@ -0,0 +1,49 @@
+/**
+ * Filter panels hold text. The URL holds numeric fields as numbers, so it
+ * reads `?minVol=100` and not `?minVol="100"`. `include` and `exclude` stay
+ * text.
+ */
+function isTextField(key: string) {
+ return key === "include" || key === "exclude";
+}
+
+export function filterValuesFromSearch<TValues extends Record<string, string>>(
+ search: Partial<Record<keyof TValues, string | number>>,
+ empty: TValues,
+): TValues {
+ const values = { ...empty };
+ for (const key in empty) {
+ const value = search[key];
+ if (value !== undefined) Object.assign(values, { [key]: String(value) });
+ }
+ return values;
+}
+
+export function filterValuesToSearch<TSearch>(
+ values: Record<string, string>,
+): Partial<TSearch> {
+ const update: Partial<TSearch> = {};
+ for (const [key, raw] of Object.entries(values)) {
+ const value = raw.trim();
+ const parsed = Number(value);
+ Object.assign(update, {
+ [key]:
+ value === ""
+ ? undefined
+ : isTextField(key)
+ ? value
+ : Number.isFinite(parsed)
+ ? parsed
+ : undefined,
+ });
+ }
+ return update;
+}
+
+/** Filter values as they come back from the URL ("10." becomes "10"). */
+export function normalizeFilterValues<TValues extends Record<string, string>>(
+ values: TValues,
+ empty: TValues,
+): TValues {
+ return filterValuesFromSearch(filterValuesToSearch(values), empty);
+}
diff --git a/src/routes/_app/p/$projectId/brand-lookup.tsx b/src/routes/_app/p/$projectId/brand-lookup.tsx
index ab25459e..d331a9d8 100644
--- a/src/routes/_app/p/$projectId/brand-lookup.tsx
+++ b/src/routes/_app/p/$projectId/brand-lookup.tsx
@@ -4,6 +4,8 @@ import { brandLookupSearchSchema } from "@/types/schemas/ai-search";
export const Route = createFileRoute("/_app/p/$projectId/brand-lookup")({
validateSearch: brandLookupSearchSchema,
+ // The project switcher keeps this page; filter drafts must not follow.
+ remountDeps: ({ params }) => params.projectId,
component: BrandLookupRoute,
});
diff --git a/src/routes/_app/p/$projectId/keywords.tsx b/src/routes/_app/p/$projectId/keywords.tsx
index 77acd10a..47e971d4 100644
--- a/src/routes/_app/p/$projectId/keywords.tsx
+++ b/src/routes/_app/p/$projectId/keywords.tsx
@@ -11,6 +11,8 @@ import { keywordsSearchSchema } from "@/types/schemas/keywords";
export const Route = createFileRoute("/_app/p/$projectId/keywords")({
validateSearch: keywordsSearchSchema,
+ // The project switcher keeps this page; filter drafts must not follow.
+ remountDeps: ({ params }) => params.projectId,
beforeLoad: ({ params, search }) => {
const { normalized, changed } = normalizeLegacyKeywordSearch(search);
if (!changed) return;
diff --git a/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx b/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx
index f2220b4d..a5382727 100644
--- a/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx
+++ b/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx
@@ -5,16 +5,19 @@ import { getRankTrackingConfigs } from "@/serverFunctions/rank-tracking";
import { RankTrackingDomainDetail } from "@/client/features/rank-tracking/RankTrackingDomainDetail";
import { PageLoading } from "@/client/components/Spinner";
import { RankTrackingConfigModal } from "@/client/features/rank-tracking/RankTrackingConfigModal";
+import { rankTrackingDetailSearchSchema } from "@/types/schemas/rank-tracking-search";
export const Route = createFileRoute(
"/_app/p/$projectId/rank-tracking/$configId",
)({
+ validateSearch: rankTrackingDetailSearchSchema,
component: RankTrackingConfigRoute,
});
function RankTrackingConfigRoute() {
const { projectId, configId } = Route.useParams();
const navigate = useNavigate();
+ const search = Route.useSearch();
const queryClient = useQueryClient();
const [showConfigModal, setShowConfigModal] = useState(false);
@@ -63,6 +66,14 @@ function RankTrackingConfigRoute() {
<RankTrackingDomainDetail
config={config}
projectId={projectId}
+ search={search}
+ onSearchChange={(update) => {
+ void navigate({
+ from: Route.fullPath,
+ search: (prev) => ({ ...prev, ...update }),
+ replace: true,
+ });
+ }}
onBack={handleBack}
onEdit={() => setShowConfigModal(true)}
/>
diff --git a/src/routes/_app/p/$projectId/rank-tracking/index.tsx b/src/routes/_app/p/$projectId/rank-tracking/index.tsx
index fb2167c8..514825f9 100644
--- a/src/routes/_app/p/$projectId/rank-tracking/index.tsx
+++ b/src/routes/_app/p/$projectId/rank-tracking/index.tsx
@@ -1,16 +1,28 @@
import { useState } from "react";
-import { createFileRoute, useNavigate } from "@tanstack/react-router";
+import {
+ createFileRoute,
+ stripSearchParams,
+ useNavigate,
+} from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { RankTrackingDomainList } from "@/client/features/rank-tracking/RankTrackingDomainList";
import { RankTrackingConfigModal } from "@/client/features/rank-tracking/RankTrackingConfigModal";
+import { rankTrackingListSearchSchema } from "@/types/schemas/rank-tracking-search";
export const Route = createFileRoute("/_app/p/$projectId/rank-tracking/")({
+ validateSearch: rankTrackingListSearchSchema,
+ // The project switcher keeps this page; a pending search must not follow.
+ remountDeps: ({ params }) => params.projectId,
+ search: {
+ middlewares: [stripSearchParams({ q: "" })],
+ },
component: RankTrackingIndex,
});
function RankTrackingIndex() {
const { projectId } = Route.useParams();
const navigate = useNavigate();
+ const search = Route.useSearch();
const queryClient = useQueryClient();
const [showConfigModal, setShowConfigModal] = useState(false);
@@ -27,6 +39,14 @@ function RankTrackingIndex() {
<>
<RankTrackingDomainList
projectId={projectId}
+ search={search}
+ onSearchChange={(next) => {
+ void navigate({
+ from: Route.fullPath,
+ search: next,
+ replace: true,
+ });
+ }}
onAddDomain={() => setShowConfigModal(true)}
/>
diff --git a/src/routes/_app/p/$projectId/saved.tsx b/src/routes/_app/p/$projectId/saved.tsx
index 011279a6..1f2afba4 100644
--- a/src/routes/_app/p/$projectId/saved.tsx
+++ b/src/routes/_app/p/$projectId/saved.tsx
@@ -1,4 +1,8 @@
-import { createFileRoute } from "@tanstack/react-router";
+import {
+ createFileRoute,
+ stripSearchParams,
+ useNavigate,
+} from "@tanstack/react-router";
// Aliased: `SavedKeywordsPage` has a local `sort` const (the saved-keyword
// sort key) that would otherwise shadow this import at the call site.
import { sort as sortArray } from "remeda";
@@ -13,7 +17,7 @@ import type {
RowSelectionState,
SortingState,
} from "@tanstack/react-table";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { TablePagination } from "@/client/components/table/TablePagination";
import { SavedKeywordsBulkActionBar } from "@/client/features/saved-keywords/SavedKeywordsBulkActionBar";
@@ -25,7 +29,10 @@ import {
RemoveSavedKeywordsError,
} from "@/client/features/saved-keywords/SavedKeywordsModals";
import { SavedKeywordsTable } from "@/client/features/saved-keywords/SavedKeywordsTable";
-import { compileSavedKeywordsFilters } from "@/client/features/saved-keywords/savedKeywordsFilterTypes";
+import {
+ compileSavedKeywordsFilters,
+ EMPTY_SAVED_KEYWORDS_FILTERS,
+} from "@/client/features/saved-keywords/savedKeywordsFilterTypes";
import {
SAVED_KEYWORD_PAGE_SIZES,
toSavedKeywordSort,
@@ -34,6 +41,11 @@ import { useSavedKeywordsExport } from "@/client/features/saved-keywords/useSave
import { useSavedKeywordsFilters } from "@/client/features/saved-keywords/useSavedKeywordsFilters";
import { useTagManage } from "@/client/features/saved-keywords/useTagManage";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
+import {
+ filterValuesFromSearch,
+ filterValuesToSearch,
+ normalizeFilterValues,
+} from "@/client/lib/filterSearchParams";
import { captureClientEvent } from "@/client/lib/posthog";
import {
getSavedKeywords,
@@ -42,45 +54,109 @@ import {
updateSavedKeywordTags,
} from "@/serverFunctions/keywords";
import type { SavedKeywordTag } from "@/types/keywords";
+import {
+ savedKeywordsSearchSchema,
+ type SavedKeywordsSearch,
+} from "@/types/schemas/keywords";
export const Route = createFileRoute("/_app/p/$projectId/saved")({
+ validateSearch: savedKeywordsSearchSchema,
+ // The project switcher keeps this page; filter drafts must not follow.
+ remountDeps: ({ params }) => params.projectId,
+ search: {
+ middlewares: [
+ stripSearchParams({
+ sort: "fetchedAt",
+ order: "desc",
+ page: 1,
+ size: 50,
+ }),
+ ],
+ },
component: SavedKeywordsPage,
});
const FILTER_DEBOUNCE_MS = 350;
+function sortingFromSearch(search: SavedKeywordsSearch): SortingState {
+ const sort = search.sort ?? "fetchedAt";
+ if (sort === "createdAt") return [];
+ return [{ id: sort, desc: (search.order ?? "desc") === "desc" }];
+}
+
function SavedKeywordsPage() {
const { projectId } = Route.useParams();
+ const search = Route.useSearch();
+ const navigate = useNavigate({ from: Route.fullPath });
const queryClient = useQueryClient();
- const [selectedTagIds, setSelectedTagIds] = useState<string[]>([]);
+ const setSearch = (update: Partial<SavedKeywordsSearch>) => {
+ void navigate({
+ search: (prev) => ({ ...prev, ...update }),
+ replace: true,
+ });
+ };
+ const selectedTagIds = useMemo(() => search.tags ?? [], [search.tags]);
+ const setSelectedTagIds = (tagIds: string[]) =>
+ setSearch({
+ tags: tagIds.length > 0 ? tagIds : undefined,
+ page: undefined,
+ });
const [showFilters, setShowFilters] = useState(false);
- const [page, setPage] = useState(1);
- const [pageSize, setPageSize] =
- useState<(typeof SAVED_KEYWORD_PAGE_SIZES)[number]>(50);
- const [sorting, setSorting] = useState<SortingState>([
- { id: "fetchedAt", desc: true },
- ]);
+ const page = search.page ?? 1;
+ const pageSize = search.size ?? 50;
+ const sorting = useMemo(() => sortingFromSearch(search), [search]);
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [removeError, setRemoveError] = useState<string | null>(null);
const [showConfirm, setShowConfirm] = useState(false);
const [showTagModal, setShowTagModal] = useState(false);
- const filters = useSavedKeywordsFilters();
- const [committedFilterValues, setCommittedFilterValues] = useState(
- filters.values,
+ const { include, exclude, minVol, maxVol, minCpc, maxCpc, minKd, maxKd } =
+ search;
+ // Keyed on the filter params only, so a tag, sort, or page change keeps
+ // the unapplied form draft.
+ const committedFilterValues = useMemo(
+ () =>
+ filterValuesFromSearch(
+ { include, exclude, minVol, maxVol, minCpc, maxCpc, minKd, maxKd },
+ EMPTY_SAVED_KEYWORDS_FILTERS,
+ ),
+ [include, exclude, minVol, maxVol, minCpc, maxCpc, minKd, maxKd],
);
- const [committedTagIds, setCommittedTagIds] = useState(selectedTagIds);
+ const filters = useSavedKeywordsFilters(committedFilterValues);
+ const committedFilterKey = JSON.stringify(committedFilterValues);
- // Field edits and tag toggles share one debounce, so a burst of changes
- // sends one query.
+ // True from a filter write until the URL changes. Any other URL change
+ // (a sidebar link, for example) resets the form to the URL.
+ const awaitingFilterWriteRef = useRef(false);
+ const { filtersForm } = filters;
useEffect(() => {
+ if (awaitingFilterWriteRef.current) {
+ awaitingFilterWriteRef.current = false;
+ return;
+ }
+ filtersForm.reset(committedFilterValues);
+ }, [committedFilterValues, filtersForm]);
+
+ // The form holds the typed draft; it reaches the URL after a pause.
+ useEffect(() => {
+ const next = normalizeFilterValues(
+ filters.values,
+ EMPTY_SAVED_KEYWORDS_FILTERS,
+ );
+ if (JSON.stringify(next) === committedFilterKey) return;
const timer = window.setTimeout(() => {
- setCommittedFilterValues(filters.values);
- setCommittedTagIds(selectedTagIds);
- setPage(1);
+ awaitingFilterWriteRef.current = true;
+ void navigate({
+ search: (prev) => ({
+ ...prev,
+ ...filterValuesToSearch<SavedKeywordsSearch>(next),
+ page: undefined,
+ }),
+ replace: true,
+ });
}, FILTER_DEBOUNCE_MS);
return () => window.clearTimeout(timer);
- }, [filters.values, selectedTagIds]);
+ }, [committedFilterKey, filters.values, navigate]);
const appliedFilters = useMemo(
() => compileSavedKeywordsFilters(committedFilterValues),
@@ -98,7 +174,7 @@ function SavedKeywordsPage() {
? "desc"
: "asc"
: "desc";
- const tagFilterKey = committedTagIds.join("|");
+ const tagFilterKey = selectedTagIds.join("|");
const hasActiveFilters =
filters.activeFilterCount > 0 || selectedTagIds.length > 0;
@@ -106,13 +182,13 @@ function SavedKeywordsPage() {
() => ({
projectId,
...appliedFilters,
- tagIds: committedTagIds.length > 0 ? committedTagIds : undefined,
+ tagIds: selectedTagIds.length > 0 ? selectedTagIds : undefined,
page,
pageSize,
sort,
order,
}),
- [appliedFilters, committedTagIds, order, page, pageSize, projectId, sort],
+ [appliedFilters, order, page, pageSize, projectId, selectedTagIds, sort],
);
const { data, isLoading, isFetching } = useQuery({
@@ -213,16 +289,20 @@ function SavedKeywordsPage() {
});
const handleSortingChange: OnChangeFn<SortingState> = (updater) => {
- setSorting((current) =>
- typeof updater === "function" ? updater(current) : updater,
- );
- setPage(1);
+ const next = (
+ typeof updater === "function" ? updater(sorting) : updater
+ )[0];
+ setSearch({
+ sort: next ? toSavedKeywordSort(next.id) : "createdAt",
+ order: next && !next.desc ? "asc" : undefined,
+ page: undefined,
+ });
};
const handleDeleteTag = async (tagId: string) => {
const ok = await tagManage.deleteTag(tagId);
if (ok) {
- setSelectedTagIds((current) => current.filter((id) => id !== tagId));
+ setSelectedTagIds(selectedTagIds.filter((id) => id !== tagId));
}
};
@@ -249,10 +329,10 @@ function SavedKeywordsPage() {
selectedTagIds={selectedTagIds}
busyTagIds={tagManage.busyTagIds}
onToggleTagFilter={(tagId) => {
- setSelectedTagIds((current) =>
- current.includes(tagId)
- ? current.filter((id) => id !== tagId)
- : [...current, tagId],
+ setSelectedTagIds(
+ selectedTagIds.includes(tagId)
+ ? selectedTagIds.filter((id) => id !== tagId)
+ : [...selectedTagIds, tagId],
);
}}
onClearTagSelection={() => setSelectedTagIds([])}
@@ -281,11 +361,10 @@ function SavedKeywordsPage() {
pageSizes={SAVED_KEYWORD_PAGE_SIZES}
totalCount={totalCount}
isLoading={isFetching}
- onPageChange={setPage}
- onPageSizeChange={(nextPageSize) => {
- setPageSize(nextPageSize);
- setPage(1);
- }}
+ onPageChange={(nextPage) => setSearch({ page: nextPage })}
+ onPageSizeChange={(nextPageSize) =>
+ setSearch({ size: nextPageSize, page: undefined })
+ }
/>
</div>
diff --git a/src/routes/_app/p/$projectId/search-performance.tsx b/src/routes/_app/p/$projectId/search-performance.tsx
index edbb4a5f..7b81f787 100644
--- a/src/routes/_app/p/$projectId/search-performance.tsx
+++ b/src/routes/_app/p/$projectId/search-performance.tsx
@@ -1,11 +1,43 @@
-import { createFileRoute } from "@tanstack/react-router";
+import {
+ createFileRoute,
+ stripSearchParams,
+ useNavigate,
+} from "@tanstack/react-router";
import { SearchPerformancePage } from "@/client/features/search-performance/SearchPerformancePage";
+import {
+ SEARCH_PERFORMANCE_DEFAULT_PAGE_SIZE,
+ searchPerformanceSearchSchema,
+} from "@/types/schemas/search-performance";
export const Route = createFileRoute("/_app/p/$projectId/search-performance")({
+ validateSearch: searchPerformanceSearchSchema,
+ search: {
+ middlewares: [
+ stripSearchParams({
+ tab: "striking",
+ range: "last_28_days",
+ page: 1,
+ size: SEARCH_PERFORMANCE_DEFAULT_PAGE_SIZE,
+ }),
+ ],
+ },
component: SearchPerformanceRoute,
});
function SearchPerformanceRoute() {
const { projectId } = Route.useParams();
- return <SearchPerformancePage projectId={projectId} />;
+ const navigate = useNavigate({ from: Route.fullPath });
+ const search = Route.useSearch();
+ return (
+ <SearchPerformancePage
+ projectId={projectId}
+ search={search}
+ onSearchChange={(update) => {
+ void navigate({
+ search: (prev) => ({ ...prev, ...update }),
+ replace: true,
+ });
+ }}
+ />
+ );
}
diff --git a/src/server/features/rank-tracking/services/rankTrackingResults.ts b/src/server/features/rank-tracking/services/rankTrackingResults.ts
index 7824479e..31eac617 100644
--- a/src/server/features/rank-tracking/services/rankTrackingResults.ts
+++ b/src/server/features/rank-tracking/services/rankTrackingResults.ts
@@ -1,7 +1,7 @@
import { RankTrackingRepository } from "@/server/features/rank-tracking/repositories/RankTrackingRepository";
import { toSqliteTimestamp } from "@/server/features/rank-tracking/rankTrackingTimestamps";
import { AppError } from "@/server/lib/errors";
-import type { ComparePeriod } from "@/types/schemas/rank-tracking";
+import type { ComparePeriod } from "@/types/schemas/rank-tracking-search";
import type {
RankTrackingDeviceResult,
RankTrackingRow,
diff --git a/src/types/schemas/ai-search.ts b/src/types/schemas/ai-search.ts
index cf81c69d..65695ed7 100644
--- a/src/types/schemas/ai-search.ts
+++ b/src/types/schemas/ai-search.ts
@@ -299,13 +299,15 @@ export const promptExplorerSearchSchema = z.object({
.optional()
.transform((value) =>
value === undefined ? undefined : Array.isArray(value) ? value : [value],
- ),
+ )
+ .catch(undefined),
web: z
.union([z.boolean(), z.enum(["true", "false"])])
.optional()
.transform((value) =>
value === undefined ? undefined : value === true || value === "true",
- ),
- cc: webSearchCountryCodeSchema.optional(),
+ )
+ .catch(undefined),
+ cc: webSearchCountryCodeSchema.optional().catch(undefined),
hb: z.string().optional(),
});
diff --git a/src/types/schemas/backlinks.ts b/src/types/schemas/backlinks.ts
index 643c33c2..3121bf09 100644
--- a/src/types/schemas/backlinks.ts
+++ b/src/types/schemas/backlinks.ts
@@ -200,7 +200,7 @@ export const backlinksSearchSchema = z.object({
includeSpam: z.boolean().optional().catch(undefined),
target: z.string().optional(),
scope: backlinksScopeParamSchema.optional().catch(undefined),
- tab: backlinksTabSchema.optional(),
+ tab: backlinksTabSchema.optional().catch(undefined),
page: z.coerce.number().int().positive().optional().catch(undefined),
size: z.coerce
.number()
diff --git a/src/types/schemas/domain.ts b/src/types/schemas/domain.ts
index e848b807..fe29cad7 100644
--- a/src/types/schemas/domain.ts
+++ b/src/types/schemas/domain.ts
@@ -145,14 +145,27 @@ export const domainPagesPageRequestSchema = z.object({
search: z.string().optional(),
});
-const optionalSearchNumberParam = z.coerce.number().optional().catch(undefined);
-const optionalSearchPositiveIntParam = z.coerce
+export const optionalSearchNumberParam = z.coerce
+ .number()
+ .optional()
+ .catch(undefined);
+export const optionalSearchPositiveIntParam = z.coerce
.number()
.int()
.positive()
.optional()
.catch(undefined);
const filterStringParam = z.string().optional();
+
+/**
+ * Free-text filter param. The router parses `?minVol=100` as a number, so
+ * numbers are kept as text instead of being dropped.
+ */
+export const searchTextParam = z
+ .union([z.string(), z.number()])
+ .transform(String)
+ .optional()
+ .catch(undefined);
const filterNumberParam = optionalSearchNumberParam;
export const domainSearchSchema = z.object({
diff --git a/src/types/schemas/keywords.ts b/src/types/schemas/keywords.ts
index 037f957f..8c3d28ef 100644
--- a/src/types/schemas/keywords.ts
+++ b/src/types/schemas/keywords.ts
@@ -1,6 +1,11 @@
import { z } from "zod";
import { TAG_COLOR_KEYS } from "@/shared/tag-colors";
-import { booleanSearchParamSchema } from "@/types/schemas/domain";
+import {
+ booleanSearchParamSchema,
+ optionalSearchNumberParam,
+ optionalSearchPositiveIntParam,
+ searchTextParam,
+} from "@/types/schemas/domain";
const savedKeywordTagSchema = z.string().trim().min(1).max(64);
const tagColorSchema = z.enum(TAG_COLOR_KEYS);
@@ -14,6 +19,11 @@ const savedKeywordSortFields = [
"fetchedAt",
] as const;
const sortDirs = ["asc", "desc"] as const;
+const savedKeywordPageSizeSchema = z.union([
+ z.literal(50),
+ z.literal(100),
+ z.literal(250),
+]);
export const researchKeywordsSchema = z.object({
projectId: z.string().min(1),
@@ -96,13 +106,37 @@ export const getSavedKeywordsSchema = z.object({
tagIds: z.array(z.string().min(1)).max(50).optional(),
tagNames: z.array(savedKeywordTagSchema).max(50).optional(),
page: z.number().int().positive().default(1),
- pageSize: z
- .union([z.literal(50), z.literal(100), z.literal(250)])
- .default(50),
+ pageSize: savedKeywordPageSizeSchema.default(50),
sort: z.enum(savedKeywordSortFields).default("createdAt"),
order: z.enum(sortDirs).default("desc"),
});
+/**
+ * /p/$projectId/saved query params. `sort=createdAt` is the unsorted table:
+ * the server's insertion order.
+ */
+export const savedKeywordsSearchSchema = z.object({
+ include: searchTextParam,
+ exclude: searchTextParam,
+ minVol: optionalSearchNumberParam,
+ maxVol: optionalSearchNumberParam,
+ minCpc: optionalSearchNumberParam,
+ maxCpc: optionalSearchNumberParam,
+ minKd: optionalSearchNumberParam,
+ maxKd: optionalSearchNumberParam,
+ tags: z.array(z.string()).optional().catch(undefined),
+ sort: z.enum(savedKeywordSortFields).optional().catch(undefined),
+ order: z.enum(sortDirs).optional().catch(undefined),
+ page: optionalSearchPositiveIntParam,
+ size: z.coerce
+ .number()
+ .pipe(savedKeywordPageSizeSchema)
+ .optional()
+ .catch(undefined),
+});
+
+export type SavedKeywordsSearch = z.infer<typeof savedKeywordsSearchSchema>;
+
export const exportSavedKeywordsSchema = getSavedKeywordsSchema.omit({
page: true,
pageSize: true,
diff --git a/src/types/schemas/rank-tracking-search.ts b/src/types/schemas/rank-tracking-search.ts
new file mode 100644
index 00000000..9c536d3e
--- /dev/null
+++ b/src/types/schemas/rank-tracking-search.ts
@@ -0,0 +1,58 @@
+import { z } from "zod";
+import {
+ optionalSearchNumberParam,
+ optionalSearchPositiveIntParam,
+ searchTextParam,
+} from "@/types/schemas/domain";
+
+// Kept apart from rank-tracking.ts, which reads enums off the Drizzle table
+// and would pull the database schema into the client route bundle.
+
+export const comparePeriodSchema = z.enum(["1d", "7d", "30d", "90d"]);
+export type ComparePeriod = z.infer<typeof comparePeriodSchema>;
+
+/** /p/$projectId/rank-tracking query params: the domain list filters. */
+export const rankTrackingListSearchSchema = z.object({
+ q: searchTextParam,
+ device: z.enum(["both", "desktop", "mobile"]).optional().catch(undefined),
+ loc: optionalSearchPositiveIntParam,
+});
+
+export type RankTrackingListSearch = z.infer<
+ typeof rankTrackingListSearchSchema
+>;
+
+/** /p/$projectId/rank-tracking/$configId query params. */
+export const rankTrackingDetailSearchSchema = z.object({
+ view: z.literal("history").optional().catch(undefined),
+ device: z.enum(["desktop", "mobile"]).optional().catch(undefined),
+ compare: comparePeriodSchema.optional().catch(undefined),
+ sort: z
+ .enum([
+ "keyword",
+ "desktopPosition",
+ "mobilePosition",
+ "volume",
+ "kd",
+ "cpc",
+ ])
+ .optional()
+ .catch(undefined),
+ order: z.enum(["asc", "desc"]).optional().catch(undefined),
+ include: searchTextParam,
+ exclude: searchTextParam,
+ minDesktopPos: optionalSearchNumberParam,
+ maxDesktopPos: optionalSearchNumberParam,
+ minMobilePos: optionalSearchNumberParam,
+ maxMobilePos: optionalSearchNumberParam,
+ minVolume: optionalSearchNumberParam,
+ maxVolume: optionalSearchNumberParam,
+ minKd: optionalSearchNumberParam,
+ maxKd: optionalSearchNumberParam,
+ minCpc: optionalSearchNumberParam,
+ maxCpc: optionalSearchNumberParam,
+});
+
+export type RankTrackingDetailSearch = z.infer<
+ typeof rankTrackingDetailSearchSchema
+>;
diff --git a/src/types/schemas/rank-tracking.ts b/src/types/schemas/rank-tracking.ts
index e1ac49cd..e1792e5a 100644
--- a/src/types/schemas/rank-tracking.ts
+++ b/src/types/schemas/rank-tracking.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { rankTrackingConfigs } from "@/db/schema";
import { isSupportedLanguageCode } from "@/shared/keyword-locations";
import { MAX_TRACKED_KEYWORD_LENGTH } from "@/shared/rank-tracking";
+import { comparePeriodSchema } from "@/types/schemas/rank-tracking-search";
import { domainField } from "@/types/schemas/domain";
// ---------------------------------------------------------------------------
@@ -128,9 +129,6 @@ export const triggerCheckSchema = z.object({
keywordIds: z.array(z.string().uuid()).max(2000).optional(),
});
-export const comparePeriodSchema = z.enum(["1d", "7d", "30d", "90d"]);
-export type ComparePeriod = z.infer<typeof comparePeriodSchema>;
-
export const getLatestResultsSchema = z.object({
projectId: z.string().uuid(),
configId: z.string().uuid(),
diff --git a/src/types/schemas/search-params.test.ts b/src/types/schemas/search-params.test.ts
index b90e20cb..ea081d20 100644
--- a/src/types/schemas/search-params.test.ts
+++ b/src/types/schemas/search-params.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
+import { promptExplorerSearchSchema } from "@/types/schemas/ai-search";
+import { backlinksSearchSchema } from "@/types/schemas/backlinks";
import { domainSearchSchema } from "@/types/schemas/domain";
+import { rankTrackingDetailSearchSchema } from "@/types/schemas/rank-tracking-search";
describe("search param boolean parsing", () => {
it("parses explicit false values for domain search params", () => {
@@ -26,3 +29,23 @@ describe("search param boolean parsing", () => {
});
});
});
+
+describe("table view search params", () => {
+ it("drops unknown values instead of failing the route", () => {
+ expect(backlinksSearchSchema.parse({ tab: "nope" }).tab).toBeUndefined();
+ expect(
+ promptExplorerSearchSchema.parse({
+ models: ["not-a-model"],
+ cc: "??",
+ web: "maybe",
+ }),
+ ).toEqual({ models: undefined, cc: undefined, web: undefined });
+ });
+
+ it("keeps a text filter that the router parsed as a number", () => {
+ // The router reads `?include=42` as the number 42.
+ expect(rankTrackingDetailSearchSchema.parse({ include: 42 }).include).toBe(
+ "42",
+ );
+ });
+});
diff --git a/src/types/schemas/search-performance.ts b/src/types/schemas/search-performance.ts
index 37822ed9..8fba399f 100644
--- a/src/types/schemas/search-performance.ts
+++ b/src/types/schemas/search-performance.ts
@@ -1,4 +1,8 @@
import { z } from "zod";
+import {
+ optionalSearchPositiveIntParam,
+ searchTextParam,
+} from "@/types/schemas/domain";
/** Date ranges offered by the Search Performance page. A deliberate subset of
* the GSC agent ranges (GSC_DATE_RANGES in searchAnalytics.ts); assignability
@@ -73,3 +77,39 @@ export const searchPerformanceTableExportInputSchema = z.object({
...searchPerformanceFilterShape,
dimension: z.enum(SEARCH_PERFORMANCE_TABLE_DIMENSIONS),
});
+
+export const SEARCH_PERFORMANCE_TABS = [
+ "striking",
+ "queries",
+ "pages",
+] as const;
+export type SearchPerformanceTab = (typeof SEARCH_PERFORMANCE_TABS)[number];
+
+const textMatchParam = z
+ .enum(["contains", "equals"])
+ .optional()
+ .catch(undefined);
+
+/** /p/$projectId/search-performance query params. */
+export const searchPerformanceSearchSchema = z.object({
+ tab: z.enum(SEARCH_PERFORMANCE_TABS).optional().catch(undefined),
+ range: z.enum(SEARCH_PERFORMANCE_RANGES).optional().catch(undefined),
+ device: z.enum(GSC_DEVICES).optional().catch(undefined),
+ country: z.string().length(3).optional().catch(undefined),
+ pageText: searchTextParam,
+ pageMatch: textMatchParam,
+ queryText: searchTextParam,
+ queryMatch: textMatchParam,
+ page: optionalSearchPositiveIntParam,
+ size: z.coerce
+ .number()
+ .refine((value) =>
+ (SEARCH_PERFORMANCE_PAGE_SIZES as readonly number[]).includes(value),
+ )
+ .optional()
+ .catch(undefined),
+});
+
+export type SearchPerformanceSearch = z.infer<
+ typeof searchPerformanceSearchSchema
+>;