Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Port Brand Lookup and Prompt Explorer to shadcn, with one shared page shell (EVE-314) (#758)
Carter Smith18e4a4a1371d
diff --git a/src/client/components/SearchCard.tsx b/src/client/components/SearchCard.tsxindex 9f8f8732..5a184fc6 100644--- a/src/client/components/SearchCard.tsx+++ b/src/client/components/SearchCard.tsx@@ -19,6 +19,7 @@ export function SearchCard({error,errorId,children,+ secondRow,}: {onSubmit: (event: FormEvent<HTMLFormElement>) => void;/** Shows a spinner in the submit button while the search runs. */@@ -28,27 +29,28 @@ export function SearchCard({errorId?: string;/** The fields, laid out in one row on wide screens. */children: ReactNode;+ /** More fields below the row, still inside the form so Enter submits. */+ secondRow?: ReactNode;}) {return (// ResearchScopeSelect opens an absolute menu below the row, so the card// must not clip it.<Card className="overflow-visible"><CardContent className="space-y-3">- <form- noValidate- className="flex flex-col gap-3 lg:flex-row lg:items-center"- onSubmit={onSubmit}- >- {children}- {/* 40px, to match the DaisyUI selects that still sit in the row. */}- <Button- type="submit"- size="lg"- className="h-10 px-6"- pending={pending}- >- Search- </Button>+ <form noValidate className="space-y-3" onSubmit={onSubmit}>+ <div className="flex flex-col gap-3 lg:flex-row lg:items-center">+ {children}+ {/* 40px, to match the DaisyUI selects that still sit in the row. */}+ <Button+ type="submit"+ size="lg"+ className="h-10 px-6"+ pending={pending}+ >+ Search+ </Button>+ </div>+ {secondRow}</form>{error ? (<p id={errorId} role="alert" className="text-sm text-destructive">diff --git a/src/client/features/ai-search/BrandLookupPage.tsx b/src/client/features/ai-search/BrandLookupPage.tsxindex 9de5d94f..3455610e 100644--- a/src/client/features/ai-search/BrandLookupPage.tsx+++ b/src/client/features/ai-search/BrandLookupPage.tsx@@ -1,20 +1,16 @@-import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";+import { useMemo, useState, type FormEvent } from "react";import { useQuery } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";import { BarChart3, Quote, Sparkles, TrendingUp } from "lucide-react";import { lookupBrand } from "@/serverFunctions/ai-search";import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";-import { PageLoading } from "@/client/components/Spinner";-import { getStandardErrorMessage } from "@/client/lib/error-messages";-import { QueryError } from "@/client/components/QueryState";+import { ResearchPageShell } from "@/client/features/ai-search/ResearchPageShell";import { BrandLookupResults } from "@/client/features/ai-search/components/BrandLookupResults";import { BrandLookupSearchCard } from "@/client/features/ai-search/components/BrandLookupSearchCard";import {RecentSearches,RecentSearchesBackLink,} from "@/client/components/RecentSearches";-import { AiSearchLoadingState } from "@/client/features/ai-search/components/AiSearchLoadingState";-import { AiSearchPaidPlanGate } from "@/client/features/ai-search/components/AiSearchPaidPlanGate";import { Badge } from "@/client/components/ui/badge";import { useBrandLookupSearchHistory } from "@/client/hooks/useBrandLookupSearchHistory";import {@@ -140,29 +136,6 @@ export function BrandLookupPage({removeHistoryItem,} = useBrandLookupSearchHistory(projectId);- // Dedup ref prevents repeat adds — `addSearch` identity is not stable- // across renders, so we'd otherwise re-write the same item every render.- // Key on query + competitors so changing competitors records a fresh entry.- const lastAddedKeyRef = useRef<string | null>(null);- useEffect(() => {- if (!hasActiveQuery || !lookupQuery.isSuccess) return;- const addedKey = `${trimmedInitialQuery}::${competitorKey}::${initialScope ?? ""}`;- if (lastAddedKeyRef.current === addedKey) return;- lastAddedKeyRef.current = addedKey;- addSearch({- query: trimmedInitialQuery,- competitors: competitorKey ? competitorKey.split(",") : [],- scope: initialScope,- });- }, [- hasActiveQuery,- lookupQuery.isSuccess,- trimmedInitialQuery,- competitorKey,- initialScope,- addSearch,- ]);-const handleSubmit = (event: FormEvent) => {event.preventDefault();const trimmed = query.trim();@@ -227,144 +200,122 @@ export function BrandLookupPage({onSearchChange(trimmed, competitors, explicitScope);};- // The form inputs are reset whenever the URL `q`/`c` changes — including the- // browser-back path and Cmd+click navigation. This keeps local form state in- // sync with the URL source-of-truth. Depend on the stable `competitorKey`- // string (not the fresh-each-render `initialCompetitors` array) so typing in- // the competitor field isn't clobbered on every render.- useEffect(() => {- setQuery(initialQuery);- setCompetitorsInput(competitorKey.split(",").join(", "));- setScopeChoice(initialScope);- setValidationError(null);- }, [initialQuery, competitorKey, initialScope]);-- const isLoading = hasActiveQuery && lookupQuery.isPending;- const errorMessage =- hasActiveQuery && lookupQuery.isError- ? getStandardErrorMessage(- lookupQuery.error,- "Failed to load brand lookup",- )- : null;- const resultData = hasActiveQuery ? lookupQuery.data : undefined;+ // The project is part of both keys, so switching projects resets the form+ // and records the search in the new project's history.+ const historyKey = `${projectId}::${trimmedInitialQuery}::${competitorKey}::${initialScope ?? ""}`;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">Brand Lookup</h1>- <p className="text-sm text-base-content/70">- See how AI search cites any brand name or domain.- </p>- </div>-- {planStatus === "loading" ? (- <PageLoading />- ) : planStatus === "free" ? (- <AiSearchPaidPlanGate- feature="Brand Lookup"- description="See how ChatGPT and Google AI Overview cite any brand or domain — total mentions, sample prompts where it appears, and the pages cited alongside it."- bullets={BRAND_LOOKUP_BULLETS}- />- ) : (- <>- <BrandLookupSearchCard- query={query}- onQueryChange={(next) => {- setQuery(next);- if (validationError) setValidationError(null);- }}- scope={selectedScope}- onScopeChange={setScopeChoice}- scopeDisabledReason={scopeDisabledReason}- competitors={competitorsInput}- onCompetitorsChange={(next) => {- setCompetitorsInput(next);- if (validationError) setValidationError(null);- }}- onSubmit={handleSubmit}- isLoading={isLoading}- validationError={validationError}+ <ResearchPageShell+ title="Brand Lookup"+ description="See how AI search cites any brand name or domain."+ planStatus={planStatus}+ gate={{+ feature: "Brand Lookup",+ description:+ "See how ChatGPT and Google AI Overview cite any brand or domain — total mentions, sample prompts where it appears, and the pages cited alongside it.",+ bullets: BRAND_LOOKUP_BULLETS,+ }}+ form={+ <BrandLookupSearchCard+ query={query}+ onQueryChange={(next) => {+ setQuery(next);+ if (validationError) setValidationError(null);+ }}+ scope={selectedScope}+ onScopeChange={setScopeChoice}+ scopeDisabledReason={scopeDisabledReason}+ competitors={competitorsInput}+ onCompetitorsChange={(next) => {+ setCompetitorsInput(next);+ if (validationError) setValidationError(null);+ }}+ onSubmit={handleSubmit}+ isLoading={hasActiveQuery && lookupQuery.isPending}+ validationError={validationError}+ />+ }+ query={lookupQuery}+ hasActiveQuery={hasActiveQuery}+ errorFallback="Failed to load brand lookup"+ // The form resets whenever the URL `q`/`c`/`scope` changes, including+ // browser back and history links. `competitorKey` is a stable string,+ // unlike the fresh-each-render `initialCompetitors` array.+ urlKey={`${initialQuery}::${historyKey}`}+ onUrlChange={() => {+ setQuery(initialQuery);+ setCompetitorsInput(competitorKey.split(",").join(", "));+ setScopeChoice(initialScope);+ setValidationError(null);+ }}+ historyKey={historyKey}+ onSuccess={() =>+ addSearch({+ query: trimmedInitialQuery,+ competitors: competitorKey ? competitorKey.split(",") : [],+ scope: initialScope,+ })+ }+ backLink={+ <RecentSearchesBackLink+ render={(props) => (+ <Link+ from="/p/$projectId/brand-lookup"+ to="/p/$projectId/brand-lookup"+ params={{ projectId }}+ search={{ q: undefined, c: undefined, scope: undefined }}+ replace+ {...props}/>-- {errorMessage ? (- <QueryError- cause={lookupQuery.error}- fallback={- resultData- ? `${errorMessage} Showing earlier results.`- : errorMessage- }- onRetry={() => void lookupQuery.refetch()}- isRetrying={lookupQuery.isFetching}- />- ) : null}-- {isLoading ? (- <AiSearchLoadingState />- ) : resultData ? (- <>- <RecentSearchesBackLink- render={(props) => (- <Link- from="/p/$projectId/brand-lookup"- to="/p/$projectId/brand-lookup"- params={{ projectId }}- search={{ q: undefined, c: undefined, scope: undefined }}- replace- {...props}- />- )}- />- <BrandLookupResults result={resultData} projectId={projectId} />- </>- ) : !errorMessage ? (- <RecentSearches- items={history}- loaded={historyLoaded}- onRemove={removeHistoryItem}- emptyIcon={Sparkles}- emptyTitle="Search a brand name or domain to see how AI cites it"- getTitle={(item) => (- <>- {item.query}- {/* Only non-default scopes are stored, so this badge always- adds information the query string doesn't carry. */}- {item.scope ? (- <Badge variant="secondary" className="ml-2">- {RESEARCH_SCOPE_LABELS[item.scope]}- </Badge>- ) : null}- </>- )}- getSubtitle={(item) =>+ )}+ />+ }+ renderResults={(result) => (+ <BrandLookupResults result={result} projectId={projectId} />+ )}+ history={+ <RecentSearches+ items={history}+ loaded={historyLoaded}+ onRemove={removeHistoryItem}+ emptyIcon={Sparkles}+ emptyTitle="Search a brand name or domain to see how AI cites it"+ getTitle={(item) => (+ <>+ {item.query}+ {/* Only non-default scopes are stored, so this badge always+ adds information the query string doesn't carry. */}+ {item.scope ? (+ <Badge variant="secondary" className="ml-2">+ {RESEARCH_SCOPE_LABELS[item.scope]}+ </Badge>+ ) : null}+ </>+ )}+ getSubtitle={(item) =>+ item.competitors.length > 0+ ? `vs ${item.competitors.join(", ")}`+ : null+ }+ renderLink={(item, props) => (+ <Link+ from="/p/$projectId/brand-lookup"+ to="/p/$projectId/brand-lookup"+ params={{ projectId }}+ search={{+ q: item.query,+ c:item.competitors.length > 0- ? `vs ${item.competitors.join(", ")}`- : null- }- renderLink={(item, props) => (- <Link- from="/p/$projectId/brand-lookup"- to="/p/$projectId/brand-lookup"- params={{ projectId }}- search={{- q: item.query,- c:- item.competitors.length > 0- ? item.competitors.join(",")- : undefined,- scope: item.scope,- }}- replace- {...props}- />- )}- />- ) : null}- </>- )}- </div>- </div>+ ? item.competitors.join(",")+ : undefined,+ scope: item.scope,+ }}+ replace+ {...props}+ />+ )}+ />+ }+ />);}diff --git a/src/client/features/ai-search/PromptExplorerPage.tsx b/src/client/features/ai-search/PromptExplorerPage.tsxindex 170daa99..b2ae0693 100644--- a/src/client/features/ai-search/PromptExplorerPage.tsx+++ b/src/client/features/ai-search/PromptExplorerPage.tsx@@ -1,24 +1,21 @@-import { useEffect, useRef, useState, type FormEvent } from "react";+import { useState, type FormEvent } from "react";import { useQuery } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";import { identity, sortBy } from "remeda";import { Columns3, MessageSquare, SearchCheck, Sparkles } from "lucide-react";import { explorePrompt } from "@/serverFunctions/ai-search";import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";-import { PageLoading } from "@/client/components/Spinner";-import { getStandardErrorMessage } from "@/client/lib/error-messages";-import { QueryError } from "@/client/components/QueryState";+import { ResearchPageShell } from "@/client/features/ai-search/ResearchPageShell";import { PromptExplorerForm } from "@/client/features/ai-search/components/PromptExplorerForm";import { PromptExplorerResults } from "@/client/features/ai-search/components/PromptExplorerResults";-import { PromptExplorerLoadingState } from "@/client/features/ai-search/components/PromptExplorerLoadingState";import {RecentSearches,RecentSearchesBackLink,} from "@/client/components/RecentSearches";-import { AiSearchPaidPlanGate } from "@/client/features/ai-search/components/AiSearchPaidPlanGate";import { formatModelLabel } from "@/client/features/ai-search/platformLabels";import { usePromptExplorerSearchHistory } from "@/client/hooks/usePromptExplorerSearchHistory";import {+ BRAND_LOOKUP_MAX_INPUT_LENGTH,PROMPT_EXPLORER_MAX_PROMPT_LENGTH,type PromptExplorerModel,type WebSearchCountryCode,@@ -100,47 +97,6 @@ export function PromptExplorerPage({ projectId, urlState, onSubmit }: Props) {retry: false,});- // Sync form to URL state — covers initial mount, browser back/forward, and- // cmd+click history navigation (in the originating tab nothing changes; in- // a new tab the form mounts populated from the URL).- useEffect(() => {- setForm(urlState);- setValidationError(null);- }, [urlState]);-- // Persist successful searches to history. Run on isSuccess so failed- // requests don't pollute recent searches. The dedup ref prevents repeat- // adds when downstream renders create new urlState references.- const lastAddedKeyRef = useRef<string | null>(null);- useEffect(() => {- if (!hasActivePrompt || !exploreQuery.isSuccess) return;- const key = [- trimmedPrompt,- urlState.highlightBrand.trim(),- sortBy(urlState.models, identity()).join(","),- urlState.webSearch,- urlState.webSearchCountryCode,- ].join("|");- if (lastAddedKeyRef.current === key) return;- lastAddedKeyRef.current = key;- addSearch({- prompt: trimmedPrompt,- highlightBrand: urlState.highlightBrand.trim(),- models: urlState.models,- webSearch: urlState.webSearch,- webSearchCountryCode: urlState.webSearchCountryCode,- });- }, [- hasActivePrompt,- exploreQuery.isSuccess,- trimmedPrompt,- urlState.highlightBrand,- urlState.models,- urlState.webSearch,- urlState.webSearchCountryCode,- addSearch,- ]);-const handleSubmit = (event: FormEvent) => {event.preventDefault();const trimmed = form.prompt.trim();@@ -154,6 +110,12 @@ export function PromptExplorerPage({ projectId, urlState, onSubmit }: Props) {);return;}+ if (form.highlightBrand.trim().length > BRAND_LOOKUP_MAX_INPUT_LENGTH) {+ setValidationError(+ `Keep the brand under ${BRAND_LOOKUP_MAX_INPUT_LENGTH} characters`,+ );+ return;+ }if (form.models.length === 0) {setValidationError("Select at least one model");return;@@ -166,15 +128,6 @@ export function PromptExplorerPage({ projectId, urlState, onSubmit }: Props) {});};- const errorMessage = exploreQuery.isError- ? getStandardErrorMessage(- exploreQuery.error,- "Failed to load prompt results",- )- : null;- const isLoading = hasActivePrompt && exploreQuery.isPending;- const resultData = hasActivePrompt ? exploreQuery.data : undefined;-const updateForm = <K extends keyof PromptExplorerFormValues>(key: K,value: PromptExplorerFormValues[K],@@ -183,109 +136,108 @@ export function PromptExplorerPage({ projectId, urlState, onSubmit }: Props) {if (validationError) setValidationError(null);};- 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">Prompt Explorer</h1>- <p className="text-sm text-base-content/70">- Ask any prompt across ChatGPT, Claude, Gemini, and Perplexity- side-by-side.- </p>- </div>+ // The project is part of both keys, so switching projects resets the form+ // and records the search in the new project's history.+ const historyKey = [+ projectId,+ trimmedPrompt,+ urlState.highlightBrand.trim(),+ sortBy(urlState.models, identity()).join(","),+ urlState.webSearch,+ urlState.webSearchCountryCode,+ ].join("|");- {planStatus === "loading" ? (- <PageLoading />- ) : planStatus === "free" ? (- <AiSearchPaidPlanGate- feature="Prompt Explorer"- description="Ask one prompt across ChatGPT, Claude, Gemini, and Perplexity at the same time and compare their answers — including which sources each model cites."- bullets={PROMPT_EXPLORER_BULLETS}- />- ) : (- <>- <PromptExplorerForm- form={form}- onPromptChange={(value) => updateForm("prompt", value)}- onHighlightBrandChange={(value) =>- updateForm("highlightBrand", value)- }- onModelsChange={(value) => updateForm("models", value)}- onWebSearchChange={(value) => updateForm("webSearch", value)}- onCountryChange={(value) =>- updateForm("webSearchCountryCode", value)- }- onSubmit={handleSubmit}- isLoading={isLoading}- validationError={validationError}+ return (+ <ResearchPageShell+ title="Prompt Explorer"+ description="Ask any prompt across ChatGPT, Claude, Gemini, and Perplexity side-by-side."+ planStatus={planStatus}+ gate={{+ feature: "Prompt Explorer",+ description:+ "Ask one prompt across ChatGPT, Claude, Gemini, and Perplexity at the same time and compare their answers — including which sources each model cites.",+ bullets: PROMPT_EXPLORER_BULLETS,+ }}+ form={+ <PromptExplorerForm+ form={form}+ onPromptChange={(value) => updateForm("prompt", value)}+ onHighlightBrandChange={(value) =>+ updateForm("highlightBrand", value)+ }+ onModelsChange={(value) => updateForm("models", value)}+ onWebSearchChange={(value) => updateForm("webSearch", value)}+ onCountryChange={(value) => updateForm("webSearchCountryCode", value)}+ onSubmit={handleSubmit}+ isLoading={hasActivePrompt && exploreQuery.isPending}+ validationError={validationError}+ />+ }+ query={exploreQuery}+ hasActiveQuery={hasActivePrompt}+ errorFallback="Failed to load prompt results"+ // Covers browser back/forward and history links. The route builds a+ // fresh `urlState` object on every render, so compare by value.+ urlKey={`${projectId}:${JSON.stringify(urlState)}`}+ onUrlChange={() => {+ setForm(urlState);+ setValidationError(null);+ }}+ historyKey={historyKey}+ onSuccess={() =>+ addSearch({+ prompt: trimmedPrompt,+ highlightBrand: urlState.highlightBrand.trim(),+ models: urlState.models,+ webSearch: urlState.webSearch,+ webSearchCountryCode: urlState.webSearchCountryCode,+ })+ }+ backLink={+ <RecentSearchesBackLink+ render={(props) => (+ <Link+ from="/p/$projectId/prompt-explorer"+ to="/p/$projectId/prompt-explorer"+ params={{ projectId }}+ search={{}}+ replace+ {...props}/>-- {errorMessage ? (- <QueryError- cause={exploreQuery.error}- fallback={- resultData- ? `${errorMessage} Showing earlier results.`- : errorMessage- }- onRetry={() => void exploreQuery.refetch()}- isRetrying={exploreQuery.isFetching}- />- ) : null}-- {isLoading ? (- <PromptExplorerLoadingState modelCount={form.models.length} />- ) : resultData ? (- <>- <RecentSearchesBackLink- render={(props) => (- <Link- from="/p/$projectId/prompt-explorer"- to="/p/$projectId/prompt-explorer"- params={{ projectId }}- search={{}}- replace- {...props}- />- )}- />- <PromptExplorerResults result={resultData} />- </>- ) : !errorMessage ? (- <RecentSearches- items={history}- loaded={historyLoaded}- onRemove={removeHistoryItem}- emptyIcon={MessageSquare}- emptyTitle="Enter a prompt to compare model answers"- getTitle={(item) => item.prompt}- getSubtitle={(item) =>- item.models.map(formatModelLabel).join(", ")- }- renderLink={(item, props) => (- <Link- from="/p/$projectId/prompt-explorer"- to="/p/$projectId/prompt-explorer"- params={{ projectId }}- search={{- q: item.prompt,- models: item.models,- web: item.webSearch ? undefined : false,- cc:- item.webSearchCountryCode === "US"- ? undefined- : item.webSearchCountryCode,- hb: item.highlightBrand || undefined,- }}- replace- {...props}- />- )}- />- ) : null}- </>- )}- </div>- </div>+ )}+ />+ }+ renderResults={(result) => <PromptExplorerResults result={result} />}+ history={+ <RecentSearches+ items={history}+ loaded={historyLoaded}+ onRemove={removeHistoryItem}+ emptyIcon={MessageSquare}+ emptyTitle="Enter a prompt to compare model answers"+ getTitle={(item) => item.prompt}+ getSubtitle={(item) => item.models.map(formatModelLabel).join(", ")}+ renderLink={(item, props) => (+ <Link+ from="/p/$projectId/prompt-explorer"+ to="/p/$projectId/prompt-explorer"+ params={{ projectId }}+ search={{+ q: item.prompt,+ models: item.models,+ web: item.webSearch ? undefined : false,+ cc:+ item.webSearchCountryCode === "US"+ ? undefined+ : item.webSearchCountryCode,+ hb: item.highlightBrand || undefined,+ }}+ replace+ {...props}+ />+ )}+ />+ }+ />);}diff --git a/src/client/features/ai-search/ResearchPageShell.tsx b/src/client/features/ai-search/ResearchPageShell.tsxnew file mode 100644index 00000000..e818fd1b--- /dev/null+++ b/src/client/features/ai-search/ResearchPageShell.tsx@@ -0,0 +1,160 @@+import { useEffect, useRef, type ReactNode } from "react";+import type { UseQueryResult } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { Sparkles, type LucideIcon } from "lucide-react";+import { SUBSCRIBE_ROUTE } from "@/shared/billing";+import type { PlanStatus } from "@/client/features/billing/plan-detection";+import { GateCard } from "@/client/components/GateCard";+import { PageHeader } from "@/client/components/PageHeader";+import { QueryError } from "@/client/components/QueryState";+import {+ SkeletonStatGrid,+ SkeletonTableRows,+} from "@/client/components/SkeletonPresets";+import { PageLoading } from "@/client/components/Spinner";+import { Badge } from "@/client/components/ui/badge";+import { Button } from "@/client/components/ui/button";+import { Card, CardContent } from "@/client/components/ui/card";+import { getStandardErrorMessage } from "@/client/lib/error-messages";++/**+ * The frame of Brand Lookup and Prompt Explorer: header, paid-plan gate,+ * search form, error, then the loading skeleton, the results or the recent+ * searches. The URL holds the active search; the page holds the form state.+ */+export function ResearchPageShell<TData>({+ title,+ description,+ planStatus,+ gate,+ form,+ query,+ hasActiveQuery,+ errorFallback,+ urlKey,+ onUrlChange,+ historyKey,+ onSuccess,+ backLink,+ renderResults,+ history,+}: {+ title: string;+ description: string;+ planStatus: "loading" | PlanStatus;+ gate: {+ feature: string;+ description: string;+ bullets: { icon: LucideIcon; title: string; body: string }[];+ };+ form: ReactNode;+ query: UseQueryResult<TData>;+ hasActiveQuery: boolean;+ errorFallback: string;+ /** Changes with the URL search. The page resets its form in `onUrlChange`. */+ urlKey: string;+ onUrlChange: () => void;+ /** Identifies the active search. `onSuccess` runs once per key. */+ historyKey: string;+ onSuccess: () => void;+ backLink: ReactNode;+ renderResults: (data: TData) => ReactNode;+ history: ReactNode;+}) {+ // Browser back/forward and history links change the URL, not the form.+ // Keep the latest callback in a ref so only a URL change resets the form.+ const onUrlChangeRef = useRef(onUrlChange);+ onUrlChangeRef.current = onUrlChange;+ useEffect(() => {+ onUrlChangeRef.current();+ }, [urlKey]);++ // Record each successful search once. Failed searches stay out of history.+ const lastAddedKeyRef = useRef<string | null>(null);+ const onSuccessRef = useRef(onSuccess);+ onSuccessRef.current = onSuccess;+ useEffect(() => {+ if (!hasActiveQuery || !query.isSuccess) return;+ if (lastAddedKeyRef.current === historyKey) return;+ lastAddedKeyRef.current = historyKey;+ onSuccessRef.current();+ }, [hasActiveQuery, query.isSuccess, historyKey]);++ const isLoading = hasActiveQuery && query.isPending;+ const errorMessage =+ hasActiveQuery && query.isError+ ? getStandardErrorMessage(query.error, errorFallback)+ : null;+ const resultData = hasActiveQuery ? query.data : undefined;++ return (+ <div className="overflow-auto px-4 py-4 pb-24 md:px-6 md:py-6 md:pb-8">+ <div className="mx-auto max-w-7xl space-y-4">+ <PageHeader title={title} description={description} />++ {planStatus === "loading" ? (+ <PageLoading />+ ) : planStatus === "free" ? (+ <GateCard+ className="mx-auto max-w-3xl"+ badge={+ <Badge variant="soft">+ <Sparkles data-icon="inline-start" />+ Paid plan+ </Badge>+ }+ title={`Unlock ${gate.feature}`}+ description={<p className="max-w-xl">{gate.description}</p>}+ actions={+ <Button+ size="lg"+ nativeButton={false}+ render={+ <Link to={SUBSCRIBE_ROUTE} search={{ upgrade: true }} />+ }+ >+ Upgrade+ </Button>+ }+ features={gate.bullets}+ />+ ) : (+ <>+ {form}++ {errorMessage ? (+ <QueryError+ cause={query.error}+ fallback={+ resultData+ ? `${errorMessage} Showing earlier results.`+ : errorMessage+ }+ onRetry={() => void query.refetch()}+ isRetrying={query.isFetching}+ />+ ) : null}++ {isLoading ? (+ <div className="space-y-4">+ <SkeletonStatGrid count={3} className="lg:grid-cols-3" />+ <Card>+ <CardContent>+ <SkeletonTableRows rows={6} columns={3} />+ </CardContent>+ </Card>+ </div>+ ) : resultData ? (+ <>+ {backLink}+ {renderResults(resultData)}+ </>+ ) : !errorMessage ? (+ history+ ) : null}+ </>+ )}+ </div>+ </div>+ );+}diff --git a/src/client/features/ai-search/components/AiSearchLoadingState.tsx b/src/client/features/ai-search/components/AiSearchLoadingState.tsxdeleted file mode 100644index 8c6a8d37..00000000--- a/src/client/features/ai-search/components/AiSearchLoadingState.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { Skeleton } from "@/client/components/ui/skeleton";--export function AiSearchLoadingState() {- return (- <div className="space-y-8" aria-busy>- <div className="grid grid-cols-1 gap-px overflow-hidden rounded-xl border border-base-300 bg-base-300 sm:grid-cols-3">- {Array.from({ length: 3 }).map((_, index) => (- <div key={index} className="space-y-2 bg-base-100 p-5">- <Skeleton className="h-3 w-24" />- <Skeleton className="h-8 w-32" />- <Skeleton className="h-3 w-40" />- </div>- ))}- </div>-- <div className="space-y-3">- <Skeleton className="h-4 w-32" />- <div className="space-y-2 rounded-lg border border-base-300 p-4">- {Array.from({ length: 6 }).map((_, index) => (- <div key={index} className="grid grid-cols-6 gap-3">- <Skeleton className="col-span-3 h-4" />- <Skeleton className="h-4" />- <Skeleton className="h-4" />- <Skeleton className="h-4" />- </div>- ))}- </div>- </div>- </div>- );-}diff --git a/src/client/features/ai-search/components/AiSearchPaidPlanGate.tsx b/src/client/features/ai-search/components/AiSearchPaidPlanGate.tsxdeleted file mode 100644index 4ab3c7fa..00000000--- a/src/client/features/ai-search/components/AiSearchPaidPlanGate.tsx+++ /dev/null@@ -1,38 +0,0 @@-import { Link } from "@tanstack/react-router";-import { Sparkles, type LucideIcon } from "lucide-react";-import { SUBSCRIBE_ROUTE } from "@/shared/billing";-import { GateCard } from "@/client/components/GateCard";-import { Badge } from "@/client/components/ui/badge";-import { Button } from "@/client/components/ui/button";--type Props = {- feature: string;- description: string;- bullets: Array<{ icon: LucideIcon; title: string; body: string }>;-};--export function AiSearchPaidPlanGate({ feature, description, bullets }: Props) {- return (- <GateCard- className="mx-auto max-w-3xl"- badge={- <Badge variant="soft">- <Sparkles data-icon="inline-start" />- Paid plan- </Badge>- }- title={`Unlock ${feature}`}- description={<p className="max-w-xl">{description}</p>}- actions={- <Button- size="lg"- nativeButton={false}- render={<Link to={SUBSCRIBE_ROUTE} search={{ upgrade: true }} />}- >- Upgrade- </Button>- }- features={bullets}- />- );-}diff --git a/src/client/features/ai-search/components/BrandLookupCitationTables.tsx b/src/client/features/ai-search/components/BrandLookupCitationTables.tsxindex d47b547f..8171bee1 100644--- a/src/client/features/ai-search/components/BrandLookupCitationTables.tsx+++ b/src/client/features/ai-search/components/BrandLookupCitationTables.tsx@@ -1,10 +1,16 @@-import { createColumnHelper, type Table } from "@tanstack/react-table";+import { createColumnHelper } from "@tanstack/react-table";import { Link } from "@tanstack/react-router";import { ExternalLink, Sparkles } from "lucide-react";-import { AppDataTable } from "@/client/components/table/AppDataTable";import { SortableHeader } from "@/client/components/table/SortableHeader";import { HelpLabel } from "@/client/components/HelpLabel";import { ExpandableList } from "@/client/components/ExpandableList";+import { Badge } from "@/client/components/ui/badge";+import { buttonVariants } from "@/client/components/ui/button";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/client/components/ui/tooltip";import { numericNullsLast } from "@/client/components/table/nullSafeSort";import {formatCount,@@ -27,7 +33,7 @@ function HeaderWithHelp({helpText: string;}) {return (- <span className="uppercase tracking-wider">+ <span className="tracking-wider uppercase"><HelpLabel label={label} helpText={helpText} /></span>);@@ -43,7 +49,7 @@ const PLATFORM_HELP =*/function PlatformCell({ platform }: { platform: PlatformKey }) {return (- <span className="inline-flex items-center gap-1.5 text-xs text-base-content/70">+ <span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground"><spanclassName={`size-1.5 rounded-full ${PLATFORM_DOT_CLASS[platform]}`}/>@@ -99,16 +105,14 @@ function PageUrlCell({className="group block max-w-xl"><span className="inline-flex items-center gap-1.5">- <span className="font-medium text-base-content group-hover:underline">+ <span className="font-medium text-foreground group-hover:underline">{row.domain ?? formatUrlForDisplay(row.url)}</span>- {isOwn ? (- <span className="badge badge-primary badge-xs border-0">You</span>- ) : null}- <ExternalLink className="size-3 shrink-0 text-base-content/40" />+ {isOwn ? <Badge size="sm">You</Badge> : null}+ <ExternalLink className="size-3 shrink-0 text-muted-foreground" /></span>{path ? (- <span className="block truncate text-xs text-base-content/50">+ <span className="block truncate text-xs text-muted-foreground">{path}</span>) : null}@@ -163,6 +167,9 @@ function KeywordsCell({);}+const TEXT_CELL = "min-w-80 max-w-2xl align-top";+const NUMBER_CELL = "whitespace-nowrap text-right align-top";+const pagesHelper = createColumnHelper<TopPageRow>();const queriesHelper = createColumnHelper<TopQueryRow>();@@ -180,6 +187,7 @@ export function buildTopPagesColumns({return [pagesHelper.accessor("url", {id: "url",+ meta: { cellClassName: TEXT_CELL },header: () => (<HeaderWithHelplabel="Source"@@ -195,6 +203,7 @@ export function buildTopPagesColumns({? [pagesHelper.accessor("platform", {id: "platform",+ meta: { cellClassName: "whitespace-nowrap align-top" },header: () => (<HeaderWithHelp label="Platform" helpText={PLATFORM_HELP} />),@@ -205,6 +214,7 @@ export function buildTopPagesColumns({: []),pagesHelper.display({id: "keywords",+ meta: { cellClassName: "max-w-lg align-top" },header: () => (<HeaderWithHelplabel="Cited for"@@ -221,6 +231,7 @@ export function buildTopPagesColumns({}),pagesHelper.accessor("capturedVolume", {id: "capturedVolume",+ meta: { cellClassName: NUMBER_CELL },header: ({ column }) => (<SortableHeadercolumn={column}@@ -250,6 +261,7 @@ export function buildTopQueriesColumns({return [queriesHelper.accessor("question", {id: "question",+ meta: { cellClassName: TEXT_CELL },header: () => (<HeaderWithHelplabel="Query"@@ -261,7 +273,7 @@ export function buildTopQueriesColumns({<><p className="break-words font-medium">{row.original.question}</p>{row.original.brandsMentioned.length > 0 ? (- <p className="mt-0.5 text-xs text-base-content/50">+ <p className="mt-0.5 text-xs text-muted-foreground">Brands: {row.original.brandsMentioned.slice(0, 5).join(", ")}</p>) : null}@@ -272,6 +284,7 @@ export function buildTopQueriesColumns({? [queriesHelper.accessor("platform", {id: "platform",+ meta: { cellClassName: "whitespace-nowrap align-top" },header: () => (<HeaderWithHelp label="Platform" helpText={PLATFORM_HELP} />),@@ -282,6 +295,7 @@ export function buildTopQueriesColumns({: []),queriesHelper.accessor("aiSearchVolume", {id: "aiSearchVolume",+ meta: { cellClassName: NUMBER_CELL },header: ({ column }) => (<SortableHeadercolumn={column}@@ -301,96 +315,30 @@ export function buildTopQueriesColumns({header: () => <span className="sr-only">Actions</span>,meta: { cellClassName: "w-px whitespace-nowrap text-right align-top" },cell: ({ row }) => (- <span- className="tooltip tooltip-left reveal-on-hover"- data-tip="Run this prompt in Prompt Explorer"- >- <Link- to="/p/$projectId/prompt-explorer"- params={{ projectId }}- search={{ q: row.original.question, hb: brand || undefined }}- className="btn btn-ghost btn-xs gap-1"- aria-label="Run this prompt in Prompt Explorer"+ <Tooltip>+ <TooltipTrigger+ delay={150}+ render={+ <Link+ to="/p/$projectId/prompt-explorer"+ params={{ projectId }}+ search={{ q: row.original.question, hb: brand || undefined }}+ className={buttonVariants({+ variant: "ghost",+ size: "icon-xs",+ className: "text-muted-foreground",+ })}+ aria-label="Run this prompt in Prompt Explorer"+ />+ }>- <Sparkles className="size-3.5" />- </Link>- </span>+ <Sparkles />+ </TooltipTrigger>+ <TooltipContent side="left">+ Run this prompt in Prompt Explorer+ </TooltipContent>+ </Tooltip>),}),];}--export function TopPagesTable({- table,- emptyMessage = "No cited sources to show.",-}: {- table: Table<TopPageRow>;- emptyMessage?: string;-}) {- if (table.getRowModel().rows.length === 0) {- return (- <p className="p-6 text-center text-sm text-base-content/60">- {emptyMessage}- </p>- );- }-- return <BrandLookupTable table={table} urlLikeColumnId="url" />;-}--export function TopQueriesTable({- table,- emptyMessage = "No matching queries found.",-}: {- table: Table<TopQueryRow>;- emptyMessage?: string;-}) {- if (table.getRowModel().rows.length === 0) {- return (- <p className="p-6 text-center text-sm text-base-content/60">- {emptyMessage}- </p>- );- }-- return <BrandLookupTable table={table} urlLikeColumnId="question" />;-}--function BrandLookupTable<T>({- table,- urlLikeColumnId,-}: {- table: Table<T>;- urlLikeColumnId: string;-}) {- return (- <AppDataTable- table={table}- getRowClassName={() => "group transition-colors hover:bg-base-200/40"}- getCellClassName={(_, columnId) =>- cellClassName(- columnId,- urlLikeColumnId,- table.getColumn(columnId)?.getCanSort() ?? false,- )- }- />- );-}--function cellClassName(- columnId: string,- urlLikeColumnId: string,- isNumeric: boolean,-): string {- if (columnId === urlLikeColumnId) {- return "min-w-80 max-w-2xl align-top";- }- if (columnId === "keywords") {- return "max-w-lg align-top";- }- if (isNumeric) {- return "whitespace-nowrap text-right align-top";- }- return "whitespace-nowrap align-top";-}diff --git a/src/client/features/ai-search/components/BrandLookupCitationsCard.tsx b/src/client/features/ai-search/components/BrandLookupCitationsCard.tsxindex 0879667c..f24aaaf8 100644--- a/src/client/features/ai-search/components/BrandLookupCitationsCard.tsx+++ b/src/client/features/ai-search/components/BrandLookupCitationsCard.tsx@@ -1,7 +1,12 @@import { useMemo, useState } from "react";import { type SortingState } from "@tanstack/react-table";-import { ChevronDown, Download, Sheet, SlidersHorizontal } from "lucide-react";-import { useDataTable } from "@/client/components/table/DataTable";+import { ExportMenu } from "@/client/components/ExportMenu";+import { DataTable, useDataTable } from "@/client/components/table/DataTable";+import {+ DataTableFilterToggle,+ DataTableToolbar,+} from "@/client/components/table/DataTableToolbar";+import { Tabs, TabsList, TabsTrigger } from "@/client/components/ui/tabs";import { exportRows } from "@/client/lib/exportRows";import {buildBrandLookupExport,@@ -9,8 +14,6 @@ import {} from "@/client/features/ai-search/components/brandLookupExport";import { BrandLookupFilterPanel } from "@/client/features/ai-search/components/BrandLookupFilterPanel";import {- TopPagesTable,- TopQueriesTable,buildTopPagesColumns,buildTopQueriesColumns,} from "@/client/features/ai-search/components/BrandLookupCitationTables";@@ -31,12 +34,6 @@ const DEFAULT_QUERIES_SORT: SortingState = [{ id: "aiSearchVolume", desc: true },];-// DaisyUI focus-dropdowns stay open until the active element blurs.-function closeExportMenu(): void {- const active = document.activeElement;- if (active instanceof HTMLElement) active.blur();-}-export function CitationTabsCard({result,projectId,@@ -135,13 +132,11 @@ export function CitationTabsCard({...exportTable,filename: brandLookupExportFilename(activeTab, result.resolvedTarget),});- closeExportMenu();};const canExport = exportTable.rows.length > 0;const currentFilterCount = filters[activeTab].activeFilterCount;- const queriesActive = activeTab === "queries";const pagesActive = activeTab === "pages";// When the active tab's platform column is hidden, surface the lone platform@@ -150,91 +145,41 @@ export function CitationTabsCard({const captionPlatform =activePlatforms.length === 1 ? activePlatforms[0] : null;- return (- <section className="overflow-hidden rounded-xl border border-base-300 bg-base-100">- <div className="flex items-center justify-between gap-3 border-b border-base-300 px-4 py-3">- <div role="tablist" className="tabs tabs-border w-fit">- <button- type="button"- role="tab"- aria-selected={queriesActive}- className={`tab ${queriesActive ? "tab-active" : ""}`}- onClick={() => setActiveTab("queries")}- >- Queries- </button>- <button- type="button"- role="tab"- aria-selected={pagesActive}- className={`tab ${pagesActive ? "tab-active" : ""}`}- onClick={() => setActiveTab("pages")}- >- Cited sources- </button>- </div>-- <div className="dropdown dropdown-end">- <div- tabIndex={0}- role="button"- className={`btn btn-ghost btn-sm gap-1.5 ${canExport ? "" : "btn-disabled"}`}- >- <Download className="size-3.5" />- Export- <ChevronDown className="size-3.5" />- </div>- <ul- tabIndex={0}- className="menu dropdown-content z-10 mt-1 w-48 rounded-box border border-base-300 bg-base-100 p-1 shadow"- >- <li>- <button- type="button"- onClick={() => handleExport("sheets")}- disabled={!canExport}- >- <Sheet className="size-4" />- Google Sheets- </button>- </li>- <li>- <button- type="button"- onClick={() => handleExport("csv")}- disabled={!canExport}- >- <Download className="size-4" />- CSV- </button>- </li>- </ul>- </div>- </div>-- <div className="flex items-center gap-2 border-b border-base-300 px-4 py-2">- <button- type="button"- className={`btn btn-ghost btn-sm gap-1.5 ${filters.showFilters ? "btn-active" : ""}`}- onClick={() => filters.setShowFilters((current) => !current)}- title="Toggle table filters"+ const toolbar = (+ <>+ <DataTableToolbar+ actions={+ <ExportMenu+ actions={["sheets", "csv"]}+ onExport={handleExport}+ disabled={!canExport}+ />+ }+ >+ <Tabs+ value={activeTab}+ onValueChange={(value) =>+ setActiveTab(value === "pages" ? "pages" : "queries")+ }>- <SlidersHorizontal className="size-3.5" />- Filters- {currentFilterCount > 0 ? (- <span className="badge badge-xs badge-primary border-0 text-primary-content">- {currentFilterCount}- </span>- ) : null}- </button>- </div>+ <TabsList variant="line">+ <TabsTrigger value="queries">Queries</TabsTrigger>+ <TabsTrigger value="pages">Cited sources</TabsTrigger>+ </TabsList>+ </Tabs>+ <DataTableFilterToggle+ open={filters.showFilters}+ activeCount={currentFilterCount}+ onToggle={() => filters.setShowFilters((current) => !current)}+ />+ </DataTableToolbar>- <div className="flex items-center justify-between gap-3 border-b border-base-300 px-4 py-2 text-xs text-base-content/60">+ <div className="flex items-center justify-between gap-3 border-b border-border px-4 py-2 text-xs text-muted-foreground"><span>- {activeTab === "pages" ? (+ {pagesActive ? (<>{isUrlScoped ? "Cited pages within " : "Pages cited alongside "}- <strong className="text-base-content/80">+ <strong className="text-foreground">{result.resolvedTarget}</strong>{isUrlScoped ? "." : " in AI answers."} Prompt examples come from@@ -244,7 +189,7 @@ export function CitationTabsCard({<>Fetched sample of prompts whose AI answer cited{" "}{isUrlScoped ? "a page within " : null}- <strong className="text-base-content/80">+ <strong className="text-foreground">{result.resolvedTarget}</strong>{isUrlScoped ? "." : " in its text or sources."}@@ -252,7 +197,7 @@ export function CitationTabsCard({)}</span>{captionPlatform ? (- <span className="inline-flex shrink-0 items-center gap-1.5 text-base-content/70">+ <span className="inline-flex shrink-0 items-center gap-1.5"><spanclassName={`size-1.5 rounded-full ${PLATFORM_DOT_CLASS[captionPlatform]}`}/>@@ -264,29 +209,43 @@ export function CitationTabsCard({{filters.showFilters ? (<BrandLookupFilterPanel activeTab={activeTab} filters={filters} />) : null}+ </>+ );- {activeTab === "pages" ? (- <TopPagesTable- table={pagesTable}- // The provider only returns the domain's top cited pages, so a URL- // scope can filter every sampled row away without meaning zero- // citations exist for that section.- emptyMessage={- isUrlScoped- ? `None of this domain's top cited pages fall under ${result.resolvedTarget}. Broaden the scope to see domain-level citations.`- : undefined- }- />- ) : (- <TopQueriesTable- table={queriesTable}- emptyMessage={- isUrlScoped- ? `No sampled prompts cited a page under ${result.resolvedTarget}. Broaden the scope to see domain-level prompts.`- : undefined- }- />- )}- </section>+ const tableProps = {+ toolbar,+ isFiltered: currentFilterCount > 0,+ onClearFilters: filters[activeTab].reset,+ };++ // The provider only returns the domain's top cited pages, so a URL scope can+ // filter every sampled row away without meaning zero citations exist for+ // that section.+ return pagesActive ? (+ <DataTable+ table={pagesTable}+ empty={{+ title: isUrlScoped+ ? `None of this domain's top cited pages fall under ${result.resolvedTarget}.`+ : "No cited sources to show.",+ description: isUrlScoped+ ? "Broaden the scope to see domain-level citations."+ : undefined,+ }}+ {...tableProps}+ />+ ) : (+ <DataTable+ table={queriesTable}+ empty={{+ title: isUrlScoped+ ? `No sampled prompts cited a page under ${result.resolvedTarget}.`+ : "No matching queries found.",+ description: isUrlScoped+ ? "Broaden the scope to see domain-level prompts."+ : undefined,+ }}+ {...tableProps}+ />);}diff --git a/src/client/features/ai-search/components/BrandLookupFilterPanel.tsx b/src/client/features/ai-search/components/BrandLookupFilterPanel.tsxindex faccaf60..f783c03e 100644--- a/src/client/features/ai-search/components/BrandLookupFilterPanel.tsx+++ b/src/client/features/ai-search/components/BrandLookupFilterPanel.tsx@@ -1,4 +1,10 @@-import { RotateCcw } from "lucide-react";+import { SegmentedToggle } from "@/client/components/SegmentedToggle";+import {+ DataTableFilterGroup,+ DataTableFilterPanel,+ DataTableRangeFilter,+} from "@/client/components/table/DataTableToolbar";+import { Input } from "@/client/components/ui/input";import type { CitationTab } from "@/client/features/ai-search/brandLookupFilterTypes";import { formatPlatformLabel } from "@/client/features/ai-search/platformLabels";import type { BrandLookupFiltersState } from "@/client/features/ai-search/useBrandLookupFilters";@@ -6,6 +12,11 @@ import type { BrandLookupFiltersState } from "@/client/features/ai-search/useBra// eslint-disable-next-line @typescript-eslint/no-explicit-anytype AnyForm = { Field: React.ComponentType<any> };+type StringField = {+ state: { value: string };+ handleChange: (v: string) => void;+};+function FilterTextInput({form,name,@@ -18,24 +29,19 @@ function FilterTextInput({placeholder: string;}) {return (- <label className="form-control gap-1.5">- <span className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">- {label}- </span>+ <DataTableFilterGroup label={label}><form.Field name={name}>- {(field: {- state: { value: string };- handleChange: (v: string) => void;- }) => (- <input- className="input input-bordered input-sm w-full bg-base-100"+ {(field: StringField) => (+ <Input+ className="h-7"+ aria-label={label}placeholder={placeholder}value={field.state.value}onChange={(event) => field.handleChange(event.target.value)}/>)}</form.Field>- </label>+ </DataTableFilterGroup>);}@@ -51,71 +57,51 @@ function FilterRangeInputs({maxName: string;}) {return (- <div className="rounded-lg border border-base-300 bg-base-100 p-2.5 space-y-2">- <p className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">- {title}- </p>- <div className="grid grid-cols-2 gap-2">- <CompactRangeInput form={form} name={minName} placeholder="Min" />- <CompactRangeInput form={form} name={maxName} placeholder="Max" />- </div>- </div>- );-}--function CompactRangeInput({- form,- name,- placeholder,-}: {- form: AnyForm;- name: string;- placeholder: string;-}) {- return (- <form.Field name={name}>- {(field: {- state: { value: string };- handleChange: (v: string) => void;- }) => (- <input- className="input input-bordered input-xs bg-base-100"- placeholder={placeholder}- type="number"- value={field.state.value}- onChange={(event) => field.handleChange(event.target.value)}- />+ <form.Field name={minName}>+ {(minField: StringField) => (+ <form.Field name={maxName}>+ {(maxField: StringField) => (+ <DataTableRangeFilter+ label={title}+ min={{+ value: minField.state.value,+ onChange: (event) => minField.handleChange(event.target.value),+ }}+ max={{+ value: maxField.state.value,+ onChange: (event) => maxField.handleChange(event.target.value),+ }}+ />+ )}+ </form.Field>)}</form.Field>);}+const PLATFORM_ITEMS = [+ { value: "all", icon: null, label: "All" },+ { value: "chat_gpt", icon: null, label: formatPlatformLabel("chat_gpt") },+ { value: "google", icon: null, label: formatPlatformLabel("google") },+];+function PlatformToggle({ form }: { form: AnyForm }) {return (- <div className="space-y-1.5">- <p className="text-[11px] font-semibold uppercase tracking-wide text-base-content/60">- Platform- </p>+ <DataTableFilterGroup label="Platform"><form.Field name="platform">- {(field: {- state: { value: string };- handleChange: (v: string) => void;- }) => (- <div className="flex flex-wrap items-center gap-1">- {(["", "chat_gpt", "google"] as const).map((value) => (- <button- key={value || "all"}- type="button"- className={`btn btn-xs ${field.state.value === value ? "btn-soft" : "btn-ghost"}`}- onClick={() => field.handleChange(value)}- >- {value === "" ? "All" : formatPlatformLabel(value)}- </button>- ))}- </div>+ {(field: StringField) => (+ <SegmentedToggle+ showLabels+ items={PLATFORM_ITEMS}+ // The stored value for "All" is the empty string.+ value={field.state.value || "all"}+ onChange={(value) =>+ field.handleChange(value === "all" ? "" : value)+ }+ />)}</form.Field>- </div>+ </DataTableFilterGroup>);}@@ -126,7 +112,7 @@ function TopPagesFilters({}) {return (<>- <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">+ <div className="grid grid-cols-1 gap-2 lg:grid-cols-2"><FilterTextInputform={form}name="include"@@ -141,7 +127,7 @@ function TopPagesFilters({/></div>- <div className="flex flex-wrap items-end gap-4">+ <div className="flex flex-wrap items-stretch gap-2"><PlatformToggle form={form} /><div className="min-w-[220px]"><FilterRangeInputs@@ -163,7 +149,7 @@ function QueriesFilters({}) {return (<>- <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">+ <div className="grid grid-cols-1 gap-2 lg:grid-cols-2"><FilterTextInputform={form}name="include"@@ -178,7 +164,7 @@ function QueriesFilters({/></div>- <div className="flex flex-wrap items-end gap-4">+ <div className="flex flex-wrap items-stretch gap-2"><PlatformToggle form={form} /><div className="min-w-[220px]"><FilterRangeInputs@@ -203,33 +189,15 @@ export function BrandLookupFilterPanel({const current = filters[activeTab];return (- <div className="shrink-0 border-b border-base-300 bg-gradient-to-b from-base-100 to-base-200/30 px-4 py-3 space-y-3">- <div className="flex flex-wrap items-center justify-between gap-2">- <div className="flex items-center gap-2">- <p className="text-sm font-semibold">Refine results</p>- {current.activeFilterCount > 0 ? (- <span className="badge badge-xs badge-primary border-0 text-primary-content">- {current.activeFilterCount} active- </span>- ) : null}- </div>- <button- type="button"- className="btn btn-xs btn-ghost gap-1"- onClick={current.reset}- disabled={current.activeFilterCount === 0}- >- <RotateCcw className="size-3" />- Clear all- </button>- </div>-+ <DataTableFilterPanel+ activeCount={current.activeFilterCount}+ onReset={current.reset}+ >{activeTab === "pages" ? (<TopPagesFilters form={filters.pages.form} />- ) : null}- {activeTab === "queries" ? (+ ) : (<QueriesFilters form={filters.queries.form} />- ) : null}- </div>+ )}+ </DataTableFilterPanel>);}diff --git a/src/client/features/ai-search/components/BrandLookupResults.tsx b/src/client/features/ai-search/components/BrandLookupResults.tsxindex 207bfb21..d147f289 100644--- a/src/client/features/ai-search/components/BrandLookupResults.tsx+++ b/src/client/features/ai-search/components/BrandLookupResults.tsx@@ -1,4 +1,19 @@-import { Info } from "lucide-react";+import { Info, TriangleAlert } from "lucide-react";+import { Alert, AlertTitle } from "@/client/components/ui/alert";+import { Badge } from "@/client/components/ui/badge";+import {+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+} from "@/client/components/ui/card";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/client/components/ui/tooltip";+import { DomainLevelBadge } from "@/client/features/ai-search/components/DomainLevelBadge";import { BrandLookupMentionTrendCard } from "@/client/features/ai-search/components/BrandLookupMentionTrendCard";import { BrandLookupShareOfVoice } from "@/client/features/ai-search/components/BrandLookupShareOfVoice";import { CitationTabsCard } from "@/client/features/ai-search/components/BrandLookupCitationsCard";@@ -21,21 +36,6 @@ type MetricKey = "mentions" | "aiSearchVolume";const DOMAIN_LEVEL_TIP ="AI search providers report mentions per domain, not per page. This number covers the whole domain — the cited pages below are limited to your scope.";-/**- * Marks a metric that could not be narrowed to a URL scope, so a page-scoped- * lookup never reads as if the number belonged to that page.- */-function DomainLevelBadge() {- return (- <span- className="tooltip badge badge-ghost badge-sm shrink-0 normal-case"- data-tip={DOMAIN_LEVEL_TIP}- >- Domain-level- </span>- );-}-export function BrandLookupResults({ result, projectId }: Props) {if (!result.hasData) {const erroredPlatforms = result.perPlatform.filter(@@ -47,19 +47,25 @@ export function BrandLookupResults({ result, projectId }: Props) {if (allPlatformsErrored) {return (- <div className="rounded-lg border border-warning/30 bg-warning/10 p-4 text-sm">- AI mention data is temporarily unavailable for{" "}- <strong>{result.resolvedTarget}</strong>. Please try again shortly.- </div>+ <Alert variant="warning">+ <TriangleAlert aria-hidden />+ <AlertTitle className="font-normal">+ AI mention data is temporarily unavailable for{" "}+ <strong>{result.resolvedTarget}</strong>. Please try again shortly.+ </AlertTitle>+ </Alert>);}return (<div className="space-y-3">- <div className="rounded-lg border border-info/30 bg-info/10 p-4 text-sm">- No AI mentions found for <strong>{result.resolvedTarget}</strong>.- </div>+ <Alert variant="info">+ <Info aria-hidden />+ <AlertTitle className="font-normal">+ No AI mentions found for <strong>{result.resolvedTarget}</strong>.+ </AlertTitle>+ </Alert>{erroredPlatforms.length > 0 ? (- <p className="text-xs text-base-content/60">+ <p className="text-xs text-muted-foreground">Note:{" "}{erroredPlatforms.map((p) => formatPlatformLabel(p.platform))@@ -110,16 +116,14 @@ function BrandHeader({ result }: { result: BrandLookupResult }) {<h2 className="text-3xl font-semibold tracking-tight">{result.resolvedTarget}</h2>- <span className="badge badge-ghost badge-sm">- {result.detectedTargetType}- </span>+ <Badge variant="secondary">{result.detectedTargetType}</Badge>{result.scope ? (- <span className="badge badge-ghost badge-sm">+ <Badge variant="secondary">{RESEARCH_SCOPE_LABELS[result.scope]}- </span>+ </Badge>) : null}</div>- <p className="text-xs text-base-content/50">+ <p className="text-xs text-muted-foreground">Updated {formatRelative(result.fetchedAt)}</p></section>@@ -128,8 +132,8 @@ function BrandHeader({ result }: { result: BrandLookupResult }) {function StatsCard({ result }: { result: BrandLookupResult }) {return (- <section className="rounded-xl border border-base-300 bg-base-100">- <div className="flex h-full flex-col divide-y divide-base-200">+ <Card className="py-0">+ <div className="flex h-full flex-col divide-y divide-border"><StatBlocklabel="Mentions"tooltip="Estimated count of AI answers where the searched brand or domain appeared in the answer text or cited sources."@@ -147,7 +151,7 @@ function StatsCard({ result }: { result: BrandLookupResult }) {isDomainLevel={result.aggregatesAreDomainLevel}/></div>- </section>+ </Card>);}@@ -168,17 +172,15 @@ function StatBlock({}) {return (<div className="flex flex-1 flex-col justify-center p-4">- <p className="inline-flex items-center gap-1 text-xs font-medium uppercase tracking-wider text-base-content/50">+ <div className="inline-flex items-center gap-1 text-xs font-medium tracking-wider text-muted-foreground uppercase">{label}- <span className="tooltip inline-flex normal-case" data-tip={tooltip}>- <Info className="size-3 text-base-content/40" />- </span>- {isDomainLevel ? <DomainLevelBadge /> : null}- </p>+ <InfoTooltip text={tooltip} />+ {isDomainLevel ? <DomainLevelBadge tooltip={DOMAIN_LEVEL_TIP} /> : null}+ </div><p className="mt-1 text-3xl font-semibold tabular-nums">{formatCount(value)}</p>- <div className="mt-3 space-y-1 border-t border-base-200 pt-2.5">+ <div className="mt-3 space-y-1 border-t border-border pt-2.5">{perPlatform.map((row) => (<PlatformStatRow key={row.platform} row={row} metric={metric} />))}@@ -198,24 +200,19 @@ function PlatformStatRow({return (<div className="flex items-center justify-between text-xs">- <span className="inline-flex items-center gap-1.5 text-base-content/70">+ <span className="inline-flex items-center gap-1.5 text-muted-foreground"><spanclassName={`size-1.5 rounded-full ${PLATFORM_DOT_CLASS[row.platform]}`}/>{formatPlatformLabel(row.platform)}{row.platform === "chat_gpt" ? (- <span- className="tooltip z-20 inline-flex"- data-tip="DataForSEO indexes ChatGPT mentions for US English only — country selection is not available for this platform."- >- <Info className="size-3 text-base-content/40" />- </span>+ <InfoTooltip text="DataForSEO indexes ChatGPT mentions for US English only — country selection is not available for this platform." />) : null}{row.status === "error" ? (- <span className="text-error">unavailable</span>+ <span className="text-destructive">unavailable</span>) : null}</span>- <span className="font-medium tabular-nums text-base-content/90">+ <span className="font-medium text-foreground tabular-nums">{formatCount(value)}</span></div>@@ -224,17 +221,38 @@ function PlatformStatRow({function MentionTrendCard({ result }: { result: BrandLookupResult }) {return (- <section className="overflow-hidden rounded-xl border border-base-300 bg-base-100">- <div className="flex items-center justify-between gap-2 border-b border-base-300 px-4 py-3">- <h3 className="text-sm font-semibold">- Mention trend (last 12 months)- </h3>- {result.aggregatesAreDomainLevel ? <DomainLevelBadge /> : null}- </div>- <div className="p-4">+ <Card>+ <CardHeader className="border-b">+ <CardTitle>+ <h3 className="text-sm">Mention trend (last 12 months)</h3>+ </CardTitle>+ {result.aggregatesAreDomainLevel ? (+ <CardAction>+ <DomainLevelBadge tooltip={DOMAIN_LEVEL_TIP} />+ </CardAction>+ ) : null}+ </CardHeader>+ <CardContent><BrandLookupMentionTrendCard result={result} />- </div>- </section>+ </CardContent>+ </Card>+ );+}++function InfoTooltip({ text }: { text: string }) {+ return (+ <Tooltip>+ <TooltipTrigger+ delay={150}+ aria-label="More info"+ className="inline-flex rounded-sm text-muted-foreground/70 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"+ >+ <Info className="size-3" />+ </TooltipTrigger>+ <TooltipContent className="normal-case tracking-normal font-normal">+ {text}+ </TooltipContent>+ </Tooltip>);}diff --git a/src/client/features/ai-search/components/BrandLookupSearchCard.tsx b/src/client/features/ai-search/components/BrandLookupSearchCard.tsxindex f15b75c8..f0498100 100644--- a/src/client/features/ai-search/components/BrandLookupSearchCard.tsx+++ b/src/client/features/ai-search/components/BrandLookupSearchCard.tsx@@ -1,8 +1,10 @@import type { FormEvent } from "react";-import { Search } from "lucide-react";import { isHostedClientAuthMode } from "@/lib/auth-mode";import { applyBillingMarkupUsd } from "@/shared/billing";import { ResearchScopeSelect } from "@/client/components/ResearchScopeSelect";+import { SearchCard, SearchInput } from "@/client/components/SearchCard";+import { Field, FieldDescription } from "@/client/components/ui/field";+import { Input } from "@/client/components/ui/input";import type { ResearchScope } from "@/shared/researchScope";import { BRAND_LOOKUP_MAX_INPUT_LENGTH } from "@/types/schemas/ai-search";@@ -61,81 +63,35 @@ export function BrandLookupSearchCard({const competitorsError = validationError?.field === "competitors";return (- <div className="card border border-base-300 bg-base-100">- <div className="card-body gap-4">- <form onSubmit={onSubmit} className="flex flex-col gap-3">- <div className="flex flex-col gap-3 lg:flex-row lg:items-center">- <label- className={`input input-bordered flex flex-1 items-center gap-2 ${- queryError ? "input-error" : ""- }`}- >- <Search className="size-4 text-base-content/60" />- <input- type="text"- placeholder="Enter a brand name or domain"- value={query}- maxLength={BRAND_LOOKUP_MAX_INPUT_LENGTH}- onChange={(event) => onQueryChange(event.target.value)}- aria-invalid={queryError || undefined}- aria-describedby={- queryError ? "brand-lookup-input-error" : undefined- }- autoComplete="off"- spellCheck={false}- className="grow"- />- </label>-- <ResearchScopeSelect- value={scope}- onChange={onScopeChange}- disabledReason={scopeDisabledReason}- />-- <button- type="submit"- className="btn btn-primary shrink-0 px-6"- disabled={isLoading}- >- {isLoading ? "Looking up..." : "Look up"}- </button>- </div>-- <div className="flex flex-col gap-1">- <input- type="text"+ <SearchCard+ onSubmit={onSubmit}+ pending={isLoading}+ error={validationError?.message}+ errorId="brand-lookup-input-error"+ secondRow={+ <>+ <Field>+ <Inputplaceholder="Add competitors (comma-separated)"value={competitors}onChange={(event) => onCompetitorsChange(event.target.value)}autoComplete="off"spellCheck={false}- className={`input input-bordered w-full ${- competitorsError ? "input-error" : ""- }`}+ className="h-10"aria-label="Competitors"aria-invalid={competitorsError || undefined}aria-describedby={competitorsError ? "brand-lookup-input-error" : undefined}/>- <p className="text-xs text-base-content/60">+ <FieldDescription>Add up to 5 competitor brands or domains to see your Share ofVoice.- </p>- </div>- </form>-- {validationError ? (- <p id="brand-lookup-input-error" className="text-sm text-error">- {validationError.message}- </p>- ) : null}-- <div className="flex flex-wrap items-center gap-3 text-xs text-base-content/60">- <p className="tabular-nums">+ </FieldDescription>+ </Field>+ <p className="text-xs text-muted-foreground tabular-nums">Est.{" "}- <span className="font-medium text-base-content/80">+ <span className="font-medium text-foreground">${BRAND_LOOKUP_DISPLAYED_COST_USD.toFixed(2)}</span>{hasCompetitors ? (@@ -147,8 +103,27 @@ export function BrandLookupSearchCard({</span>) : null}</p>- </div>- </div>- </div>+ </>+ }+ >+ <SearchInput+ placeholder="Enter a brand name or domain"+ aria-label="Brand name or domain"+ value={query}+ maxLength={BRAND_LOOKUP_MAX_INPUT_LENGTH}+ onChange={(event) => onQueryChange(event.target.value)}+ aria-invalid={queryError || undefined}+ aria-describedby={queryError ? "brand-lookup-input-error" : undefined}+ autoComplete="off"+ spellCheck={false}+ />++ <ResearchScopeSelect+ value={scope}+ className="w-full lg:w-40"+ onChange={onScopeChange}+ disabledReason={scopeDisabledReason}+ />+ </SearchCard>);}diff --git a/src/client/features/ai-search/components/BrandLookupShareOfVoice.tsx b/src/client/features/ai-search/components/BrandLookupShareOfVoice.tsxindex 1d33486c..be256c96 100644--- a/src/client/features/ai-search/components/BrandLookupShareOfVoice.tsx+++ b/src/client/features/ai-search/components/BrandLookupShareOfVoice.tsx@@ -1,3 +1,13 @@+import { cn } from "cn";+import { Badge } from "@/client/components/ui/badge";+import {+ Card,+ CardAction,+ CardHeader,+ CardTitle,+} from "@/client/components/ui/card";+import { Progress } from "@/client/components/ui/progress";+import { DomainLevelBadge } from "@/client/features/ai-search/components/DomainLevelBadge";import {formatCount,formatPlatformLabel,@@ -28,32 +38,25 @@ export function BrandLookupShareOfVoice({);return (- <section className="flex h-full flex-col overflow-hidden rounded-xl border border-base-300 bg-base-100">- <div className="flex items-baseline justify-between gap-2 border-b border-base-300 px-4 py-3">- <h3 className="flex items-center gap-2 text-sm font-semibold">- Share of Voice+ <Card className="h-full gap-0 py-0">+ <CardHeader className="border-b py-3">+ <CardTitle className="flex items-center gap-2">+ <h3 className="text-sm">Share of Voice</h3>{isDomainLevel ? (- <span- className="tooltip badge badge-ghost badge-sm shrink-0 font-normal"- data-tip="Share of Voice compares whole domains — it is not narrowed to the page or folder you searched."- >- Domain-level- </span>+ <DomainLevelBadge tooltip="Share of Voice compares whole domains — it is not narrowed to the page or folder you searched." />) : null}- </h3>+ </CardTitle>{target ? (- <span className="text-xs text-base-content/50">- <span className="font-medium text-base-content/80">- {target.label}- </span>{" "}+ <CardAction className="self-center text-xs text-muted-foreground">+ <span className="font-medium text-foreground">{target.label}</span>{" "}{target.sharePct == null? "· no comparable data": `· ${Math.round(target.sharePct)}%`}- </span>+ </CardAction>) : null}- </div>+ </CardHeader>- <ul className="flex-1 divide-y divide-base-200">+ <ul className="flex-1 divide-y divide-border">{shareOfVoice.entries.map((entry, index) => (<LeaderboardRowkey={entry.label}@@ -66,12 +69,12 @@ export function BrandLookupShareOfVoice({{/* Captions only the platforms actually summed — when one platform'scross_aggregated call failed, the leaderboard must not claim both. */}- <p className="border-t border-base-200 px-4 py-2 text-[11px] text-base-content/50">+ <p className="border-t border-border px-4 py-2 text-[11px] text-muted-foreground">Mentions share across{" "}{shareOfVoice.platforms.map(formatPlatformLabel).join(" and ")} · barsrelative to the leader.</p>- </section>+ </Card>);}@@ -90,30 +93,30 @@ function LeaderboardRow({return (<li- className={`grid grid-cols-[1.25rem_minmax(0,1fr)_2.75rem] items-center gap-3 px-4 py-2.5 ${- entry.isTarget ? "bg-primary/5" : ""- }`}+ className={cn(+ "grid grid-cols-[1.25rem_minmax(0,1fr)_2.75rem] items-center gap-3 px-4 py-2.5",+ entry.isTarget && "bg-primary/5",+ )}>- <span className="text-xs tabular-nums text-base-content/40">{rank}</span>+ <span className="text-xs text-muted-foreground tabular-nums">{rank}</span><div className="min-w-0"><div className="flex items-center gap-2"><span className="truncate text-sm">{entry.label}</span>- {entry.isTarget ? (- <span className="badge badge-primary badge-xs border-0">You</span>- ) : null}- <span className="ml-auto shrink-0 text-xs tabular-nums text-base-content/50">+ {entry.isTarget ? <Badge size="sm">You</Badge> : null}+ <span className="ml-auto shrink-0 text-xs text-muted-foreground tabular-nums">{/* Null mentions = "no data"; render a dash, not zero. */}{entry.mentions == null ? "—" : formatCount(entry.mentions)}</span></div>- <div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-base-200">- <div- className={`h-full rounded-full ${- entry.isTarget ? "bg-primary" : "bg-base-content/25"- }`}- style={{ width: `${barWidth}%` }}- />- </div>+ <Progress+ value={barWidth}+ aria-label={`${entry.label} share of the leader`}+ className={cn(+ "mt-1.5 **:data-[slot=progress-track]:h-1.5",+ !entry.isTarget &&+ "**:data-[slot=progress-indicator]:bg-foreground/25",+ )}+ /></div><span className="text-right text-sm font-medium tabular-nums">{hasData ? `${Math.round(entry.sharePct ?? 0)}%` : "—"}diff --git a/src/client/features/ai-search/components/DomainLevelBadge.tsx b/src/client/features/ai-search/components/DomainLevelBadge.tsxnew file mode 100644index 00000000..33e5b0cd--- /dev/null+++ b/src/client/features/ai-search/components/DomainLevelBadge.tsx@@ -0,0 +1,30 @@+import { Badge } from "@/client/components/ui/badge";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/client/components/ui/tooltip";++/**+ * Marks a number that covers the whole domain under a URL scope, so a+ * page-scoped lookup never reads as if the number belonged to that page.+ */+export function DomainLevelBadge({ tooltip }: { tooltip: string }) {+ return (+ <Tooltip>+ <TooltipTrigger+ delay={150}+ render={+ <Badge+ variant="outline"+ size="sm"+ className="font-normal tracking-normal normal-case"+ />+ }+ >+ Domain-level+ </TooltipTrigger>+ <TooltipContent>{tooltip}</TooltipContent>+ </Tooltip>+ );+}diff --git a/src/client/features/ai-search/components/MarkdownAnswer.tsx b/src/client/features/ai-search/components/MarkdownAnswer.tsxindex dc86fd13..2f2e520b 100644--- a/src/client/features/ai-search/components/MarkdownAnswer.tsx+++ b/src/client/features/ai-search/components/MarkdownAnswer.tsx@@ -3,6 +3,12 @@ import { ChevronDown, ChevronUp } from "lucide-react";import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import { MARKDOWN_COMPONENTS } from "@/client/components/Markdown";+import { Button } from "@/client/components/ui/button";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/client/components/ui/collapsible";type Props = {text: string;@@ -43,7 +49,7 @@ export function MarkdownAnswer({ text }: Props) {if (normalized.trim().length === 0 && thinking.length === 0) {return (- <p className="text-sm text-base-content/60 italic">+ <p className="text-sm text-muted-foreground italic">Model returned an empty response.</p>);@@ -77,31 +83,32 @@ export function MarkdownAnswer({ text }: Props) {{isCollapsed ? (<divaria-hidden- className="pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-t from-base-100 to-transparent"+ className="pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-t from-card to-transparent"/>) : null}</div>) : null}{needsCollapse ? (- <button- type="button"+ <Button+ variant="link"+ size="xs"onClick={() => setExpanded((prev) => !prev)}- className="mt-2 inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"+ className="mt-2 h-auto px-0"aria-expanded={expanded}>{expanded ? (<>- <ChevronUp className="size-3.5" />+ <ChevronUp data-icon="inline-start" />Show less</>) : (<>- <ChevronDown className="size-3.5" />+ <ChevronDown data-icon="inline-start" />Read more</>)}- </button>+ </Button>) : null}</div>);@@ -109,18 +116,20 @@ export function MarkdownAnswer({ text }: Props) {function ThinkingBlock({ text }: { text: string }) {return (- <details- open- className="group mb-3 rounded-lg border border-base-300 bg-base-200/40"+ <Collapsible+ defaultOpen+ className="mb-3 rounded-lg border border-border bg-muted/40">- <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 text-xs font-medium text-base-content/70 hover:text-base-content">- <ChevronDown className="size-3.5 transition-transform group-open:rotate-180" />+ <CollapsibleTrigger className="group flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-xs font-medium text-muted-foreground outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50">+ <ChevronDown className="size-3.5 transition-transform group-data-panel-open:rotate-180" />Model Thinking- </summary>- <pre className="overflow-x-auto whitespace-pre-wrap break-words rounded-b-lg border-t border-base-300 bg-base-200/60 px-3 py-2.5 text-xs font-mono text-base-content/80">- {text}- </pre>- </details>+ </CollapsibleTrigger>+ <CollapsibleContent>+ <pre className="overflow-x-auto rounded-b-lg border-t border-border bg-muted/60 px-3 py-2.5 font-mono text-xs break-words whitespace-pre-wrap text-foreground/80">+ {text}+ </pre>+ </CollapsibleContent>+ </Collapsible>);}diff --git a/src/client/features/ai-search/components/PromptExplorerForm.tsx b/src/client/features/ai-search/components/PromptExplorerForm.tsxindex 36316570..fc82d98c 100644--- a/src/client/features/ai-search/components/PromptExplorerForm.tsx+++ b/src/client/features/ai-search/components/PromptExplorerForm.tsx@@ -1,4 +1,24 @@import type { FormEvent } from "react";+import { cn } from "cn";+import { Button } from "@/client/components/ui/button";+import { Card, CardContent } from "@/client/components/ui/card";+import { Checkbox } from "@/client/components/ui/checkbox";+import {+ Field,+ FieldDescription,+ FieldLabel,+ FieldTitle,+} from "@/client/components/ui/field";+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 { Textarea } from "@/client/components/ui/textarea";import {formatCountryLabel,formatModelLabel,@@ -31,6 +51,11 @@ type Props = {validationError: string | null;};+const COUNTRY_ITEMS = WEB_SEARCH_COUNTRY_CODES.map((code) => ({+ value: code,+ label: formatCountryLabel(code),+}));+function isCountryCode(value: string): value is WebSearchCountryCode {return (WEB_SEARCH_COUNTRY_CODES as readonly string[]).includes(value);}@@ -62,129 +87,117 @@ export function PromptExplorerForm({const promptOverLimit = promptCharCount > PROMPT_EXPLORER_MAX_PROMPT_LENGTH;return (- <form- onSubmit={onSubmit}- className="card border border-base-300 bg-base-100"- >- <div className="card-body gap-5">- <div className="space-y-1.5">- <label- className="block text-sm font-medium"- htmlFor="prompt-explorer-prompt"- >- Prompt- </label>- <textarea- id="prompt-explorer-prompt"- className={`textarea textarea-bordered w-full resize-none ${- promptOverLimit ? "textarea-error" : ""- }`}- rows={3}- value={form.prompt}- maxLength={PROMPT_EXPLORER_MAX_PROMPT_LENGTH + 50}- onChange={(event) => onPromptChange(event.target.value)}- aria-invalid={promptOverLimit ? true : undefined}- autoFocus- />- <div className="flex items-center justify-between text-xs text-base-content/60">- <span>What your customers might ask AI.</span>- <span- className={`tabular-nums ${promptOverLimit ? "font-medium text-error" : ""}`}- >- {promptCharCount}/{PROMPT_EXPLORER_MAX_PROMPT_LENGTH}- </span>- </div>- </div>-- <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">- <div className="space-y-1.5">- <label- className="block text-sm font-medium"- htmlFor="prompt-explorer-brand"- >- Highlight brand (optional)- </label>- <input- id="prompt-explorer-brand"- type="text"- className="input input-bordered w-full"- value={form.highlightBrand}- onChange={(event) => onHighlightBrandChange(event.target.value)}- autoComplete="off"- spellCheck={false}+ <Card>+ <CardContent>+ <form onSubmit={onSubmit} noValidate className="space-y-5">+ <Field>+ <FieldLabel htmlFor="prompt-explorer-prompt">Prompt</FieldLabel>+ <Textarea+ id="prompt-explorer-prompt"+ className="resize-none"+ rows={3}+ value={form.prompt}+ maxLength={PROMPT_EXPLORER_MAX_PROMPT_LENGTH + 50}+ onChange={(event) => onPromptChange(event.target.value)}+ aria-invalid={promptOverLimit ? true : undefined}+ autoFocus/>- <p className="text-xs text-base-content/60">- We'll flag whether each model mentions this brand.- </p>- </div>+ <FieldDescription className="flex items-center justify-between">+ <span>What your customers might ask AI.</span>+ <span+ className={cn(+ "tabular-nums",+ promptOverLimit && "font-medium text-destructive",+ )}+ >+ {promptCharCount}/{PROMPT_EXPLORER_MAX_PROMPT_LENGTH}+ </span>+ </FieldDescription>+ </Field>++ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">+ <Field>+ <FieldLabel htmlFor="prompt-explorer-brand">+ Highlight brand (optional)+ </FieldLabel>+ <Input+ id="prompt-explorer-brand"+ value={form.highlightBrand}+ onChange={(event) => onHighlightBrandChange(event.target.value)}+ autoComplete="off"+ spellCheck={false}+ />+ <FieldDescription>+ We'll flag whether each model mentions this brand.+ </FieldDescription>+ </Field>- <div className="space-y-1.5">- <span className="block text-sm font-medium">Models</span>- <div className="flex flex-wrap items-center gap-x-5 gap-y-2 pt-1.5">- {PROMPT_EXPLORER_MODELS.map((model) => {- const isActive = form.models.includes(model);- return (- <label- key={model}- className="flex cursor-pointer items-center gap-2"- >- <input- type="checkbox"- className="checkbox checkbox-sm"- checked={isActive}- onChange={() => toggleModel(model)}+ <Field>+ <FieldTitle>Models</FieldTitle>+ <div className="flex flex-wrap items-center gap-x-5 gap-y-2 pt-1.5">+ {PROMPT_EXPLORER_MODELS.map((model) => (+ <Label key={model} className="font-normal">+ <Checkbox+ checked={form.models.includes(model)}+ onCheckedChange={() => toggleModel(model)}/>- <span className="text-sm">{formatModelLabel(model)}</span>- </label>- );- })}- </div>+ {formatModelLabel(model)}+ </Label>+ ))}+ </div>+ </Field></div>- </div>- <div className="flex flex-wrap items-center justify-between gap-3 border-t border-base-300 pt-4">- <div className="flex flex-wrap items-center gap-3">- <label className="flex cursor-pointer items-center gap-2">- <input- type="checkbox"- className="checkbox checkbox-sm"- checked={form.webSearch}- onChange={(event) => onWebSearchChange(event.target.checked)}- />- <span className="text-sm">+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4">+ <div className="flex flex-wrap items-center gap-3">+ <Label className="font-normal">+ <Checkbox+ checked={form.webSearch}+ onCheckedChange={onWebSearchChange}+ />Allow web search (more current answers)- </span>- </label>- <select- id="prompt-explorer-country"- aria-label="Web search location"- className="select select-bordered select-sm min-w-0 sm:max-w-xs"- value={form.webSearchCountryCode}- onChange={(event) =>- onCountryChange(parseCountryCode(event.target.value))- }- disabled={!form.webSearch}+ </Label>+ <Select+ items={COUNTRY_ITEMS}+ value={form.webSearchCountryCode}+ onValueChange={(value) =>+ onCountryChange(parseCountryCode(value ?? ""))+ }+ disabled={!form.webSearch}+ >+ <SelectTrigger+ aria-label="Web search location"+ className="min-w-0 sm:max-w-xs"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {COUNTRY_ITEMS.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <Button+ type="submit"+ size="lg"+ className="px-6"+ pending={isLoading}+ disabled={form.models.length === 0}>- {WEB_SEARCH_COUNTRY_CODES.map((code) => (- <option key={code} value={code}>- {formatCountryLabel(code)}- </option>- ))}- </select>+ Run+ </Button></div>- <button- type="submit"- className="btn btn-primary shrink-0 px-6"- disabled={isLoading || form.models.length === 0}- >- {isLoading ? "Running…" : "Run"}- </button>- </div>- {validationError ? (- <p className="text-sm text-error">{validationError}</p>- ) : null}- </div>- </form>+ {validationError ? (+ <p role="alert" className="text-sm text-destructive">+ {validationError}+ </p>+ ) : null}+ </form>+ </CardContent>+ </Card>);}diff --git a/src/client/features/ai-search/components/PromptExplorerLoadingState.tsx b/src/client/features/ai-search/components/PromptExplorerLoadingState.tsxdeleted file mode 100644index 2ba2e804..00000000--- a/src/client/features/ai-search/components/PromptExplorerLoadingState.tsx+++ /dev/null@@ -1,34 +0,0 @@-import { Skeleton } from "@/client/components/ui/skeleton";--type Props = {- modelCount: number;-};--export function PromptExplorerLoadingState({ modelCount }: Props) {- const count = Math.max(1, modelCount);- return (- <div className="space-y-5" aria-busy>- {Array.from({ length: count }).map((_, index) => (- <article- key={index}- className="overflow-hidden rounded-r-lg border border-base-300 border-l-4 border-l-base-300 bg-base-100"- >- <header className="flex items-center justify-between border-b border-base-200 bg-base-200/40 px-5 py-3">- <div className="flex items-center gap-2">- <Skeleton className="size-2 rounded-full" />- <Skeleton className="h-4 w-20" />- <Skeleton className="h-3 w-32" />- </div>- <Skeleton className="h-3 w-16" />- </header>- <div className="space-y-2 px-5 py-5">- <Skeleton className="h-3 w-full" />- <Skeleton className="h-3 w-11/12" />- <Skeleton className="h-3 w-10/12" />- <Skeleton className="h-3 w-9/12" />- </div>- </article>- ))}- </div>- );-}diff --git a/src/client/features/ai-search/components/PromptExplorerResults.tsx b/src/client/features/ai-search/components/PromptExplorerResults.tsxindex 24ca23ba..b11e285c 100644--- a/src/client/features/ai-search/components/PromptExplorerResults.tsx+++ b/src/client/features/ai-search/components/PromptExplorerResults.tsx@@ -5,6 +5,7 @@ import {Globe,XCircle,} from "lucide-react";+import { cn } from "cn";import { MarkdownAnswer } from "@/client/features/ai-search/components/MarkdownAnswer";import {formatModelLabel,@@ -23,6 +24,9 @@ type Props = {result: PromptExplorerResult;};+const ARTICLE_CLASS =+ "overflow-hidden rounded-r-lg border border-l-4 border-border bg-card";+export function PromptExplorerResults({ result }: Props) {return (<div className="space-y-5">@@ -48,9 +52,7 @@ function ModelResultCard({if (modelResult.status === "error") {return (- <article- className={`overflow-hidden rounded-r-lg border border-base-300 border-l-4 ${accent.border} bg-base-100`}- >+ <article className={cn(ARTICLE_CLASS, accent.border)}><ModelHeadermodel={modelResult.model}modelName={null}@@ -60,7 +62,7 @@ function ModelResultCard({highlightBrand={null}status="error"/>- <div className="flex items-start gap-2 px-5 py-4 text-sm text-error">+ <div className="flex items-start gap-2 px-5 py-4 text-sm text-destructive"><AlertCircle className="mt-0.5 size-4 shrink-0" /><span>{modelResult.message}</span></div>@@ -69,9 +71,7 @@ function ModelResultCard({}return (- <article- className={`overflow-hidden rounded-r-lg border border-base-300 border-l-4 ${accent.border} bg-base-100`}- >+ <article className={cn(ARTICLE_CLASS, accent.border)}><ModelHeadermodel={modelResult.model}modelName={modelResult.modelName}@@ -94,18 +94,19 @@ function ModelResultCard({) : null}{modelResult.fanOutQueries.length > 0 ? (- <div className="border-t border-base-200 px-5 py-3">- <p className="mb-2 text-xs font-medium uppercase tracking-wider text-base-content/50">+ <div className="border-t border-border px-5 py-3">+ <p className="mb-2 text-xs font-medium tracking-wider text-muted-foreground uppercase">Related queries the model considered</p><div className="flex flex-wrap gap-1.5">{modelResult.fanOutQueries.map((query, index) => (- <span+ <Badgekey={`${query}-${index}`}- className="rounded-full border border-base-300 px-2.5 py-0.5 text-xs text-base-content/70"+ variant="outline"+ className="font-normal text-muted-foreground">{query}- </span>+ </Badge>))}</div></div>@@ -177,29 +178,27 @@ function ModelHeader({}) {const accent = getModelAccent(model);return (- <header className="flex flex-wrap items-center justify-between gap-2 border-b border-base-200 bg-base-200/40 px-5 py-3">+ <header className="flex flex-wrap items-center justify-between gap-2 border-b border-border bg-muted/40 px-5 py-3"><div className="flex flex-wrap items-center gap-2"><span className={`size-2 rounded-full ${accent.dot}`} /><h3 className="text-sm font-semibold">{formatModelLabel(model)}</h3>{modelName ? (- <code className="text-xs text-base-content/50">{modelName}</code>- ) : null}- {status === "error" ? (- <span className="badge badge-error badge-sm">Error</span>+ <code className="text-xs text-muted-foreground">{modelName}</code>) : null}+ {status === "error" ? <Badge variant="destructive">Error</Badge> : null}<BrandMentionBadgementioned={brandMentioned}highlightBrand={highlightBrand}/>{webSearch ? (- <span className="inline-flex items-center gap-1 text-xs text-base-content/60">+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground"><Globe className="size-3" />web search</span>) : null}</div>{tokens != null ? (- <span className="text-xs tabular-nums text-base-content/50">+ <span className="text-xs text-muted-foreground tabular-nums">{tokens.toLocaleString()} tokens</span>) : null}@@ -217,16 +216,16 @@ function BrandMentionBadge({if (mentioned == null || !highlightBrand) return null;if (mentioned) {return (- <span className="inline-flex items-center gap-1 rounded-full bg-success/15 px-2 py-0.5 text-xs font-medium text-success">- <CheckCircle2 className="size-3" />+ <Badge variant="success">+ <CheckCircle2 data-icon="inline-start" />{highlightBrand}- </span>+ </Badge>);}return (- <span className="inline-flex items-center gap-1 rounded-full bg-base-200 px-2 py-0.5 text-xs text-base-content/60">- <XCircle className="size-3" />+ <Badge variant="secondary" className="font-normal text-muted-foreground">+ <XCircle data-icon="inline-start" />no {highlightBrand}- </span>+ </Badge>);}