Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(prompts): sortable columns on All Prompts with URL deep-link (#322)
Gökhan Geyika331c8dda373
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex fe22ceac4..ea0d48008 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -39,6 +39,8 @@ import {Pencil,Settings2,Download,+ ChevronUp,+ ChevronDown,} from 'lucide-react';import { cn } from '@/lib/utils';import { useBrandStore } from '@/stores/use-brand-store';@@ -54,6 +56,7 @@ import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';import type { PromptVolume, Prompt } from '@/types';import { toast } from 'sonner';import { toCsv } from '@/lib/csv';+import { compareNullsLast, type SortDir } from './prompt-sort';// ─── Info Tooltip ─────────────────────────────────────────────────────────────@@ -109,6 +112,68 @@ function ColHead({);}+// ─── Sortable column header (All Prompts) ─────────────────────────────────────++type AllPromptsSortKey = 'visibility' | 'mentions' | 'volume' | 'lastRun';++const ALL_PROMPTS_SORT_KEYS: AllPromptsSortKey[] = ['visibility', 'mentions', 'volume', 'lastRun'];++function isAllPromptsSortKey(value: string | null): value is AllPromptsSortKey {+ return value !== null && (ALL_PROMPTS_SORT_KEYS as string[]).includes(value);+}++/**+ * Clickable header that toggles asc⇄desc for its column and marks the active+ * sort with a chevron. The InfoTip lives outside the button so hovering /+ * clicking the help icon doesn't trigger a sort.+ */+function SortableHead({+ children,+ tooltip,+ className,+ sortKey,+ activeSort,+ dir,+ onSort,+}: {+ children: React.ReactNode;+ tooltip: string;+ className?: string;+ sortKey: AllPromptsSortKey;+ activeSort: AllPromptsSortKey | null;+ dir: SortDir;+ onSort: (key: AllPromptsSortKey) => void;+}) {+ const active = activeSort === sortKey;+ return (+ <TableHead+ className={className}+ aria-sort={active ? (dir === 'asc' ? 'ascending' : 'descending') : 'none'}+ >+ <span className="inline-flex items-center gap-1">+ <button+ type="button"+ onClick={() => onSort(sortKey)}+ aria-label={`Sort by ${typeof children === 'string' ? children : sortKey}`}+ className={cn(+ 'inline-flex items-center gap-1 transition-colors hover:text-foreground',+ active ? 'text-foreground' : 'text-muted-foreground',+ )}+ >+ {children}+ {active &&+ (dir === 'asc' ? (+ <ChevronUp className="h-3.5 w-3.5" />+ ) : (+ <ChevronDown className="h-3.5 w-3.5" />+ ))}+ </button>+ <InfoTip content={tooltip} />+ </span>+ </TableHead>+ );+}+// ─── Intent labels ───────────────────────────────────────────────────────────const INTENT_LABELS: Record<string, string> = {@@ -953,17 +1018,59 @@ function AllPromptsTab({visibility: Record<string, PromptVisibilitySummary>;}) {const [search, setSearch] = useState('');+ const router = useRouter();+ const searchParams = useSearchParams();++ const rawSort = searchParams.get('sort');+ const activeSort: AllPromptsSortKey | null = isAllPromptsSortKey(rawSort) ? rawSort : null;+ const dir: SortDir = searchParams.get('dir') === 'asc' ? 'asc' : 'desc';++ // Click a header to sort: a new column starts at desc ("show me the extremes");+ // re-clicking the active column toggles desc⇄asc. Persisted to the URL so the+ // sort survives reloads and is shareable (matches the existing `tab` sync).+ const handleSort = useCallback(+ (key: AllPromptsSortKey) => {+ const params = new URLSearchParams(Array.from(searchParams.entries()));+ const nextDir: SortDir = activeSort === key && dir === 'desc' ? 'asc' : 'desc';+ params.set('tab', 'all');+ params.set('sort', key);+ params.set('dir', nextDir);+ router.replace(`/dashboard/prompts?${params.toString()}`, { scroll: false });+ },+ [searchParams, router, activeSort, dir],+ );const filtered = useMemo(() => {const q = search.trim().toLowerCase();- const sorted = [...prompts].sort(- (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),- );- if (!q) return sorted;- return sorted.filter(- (p) => p.text.toLowerCase().includes(q) || (p.category ?? '').toLowerCase().includes(q),- );- }, [prompts, search]);+ let list = [...prompts];+ if (q) {+ list = list.filter(+ (p) => p.text.toLowerCase().includes(q) || (p.category ?? '').toLowerCase().includes(q),+ );+ }++ if (!activeSort) {+ // Default ordering: newest first.+ return list.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());+ }++ const valueOf = (p: Prompt): number | null => {+ const vis = visibility[p.id];+ const vol = volumeByPromptId.get(p.id);+ switch (activeSort) {+ case 'visibility':+ return vis ? vis.avgVisibility : null;+ case 'mentions':+ return vis ? vis.totalMentions : null;+ case 'volume':+ return vol ? vol.estAiVolume : null;+ case 'lastRun':+ return vis?.lastRunAt ? new Date(vis.lastRunAt).getTime() : null;+ }+ };++ return list.sort((a, b) => compareNullsLast(valueOf(a), valueOf(b), dir));+ }, [prompts, search, activeSort, dir, visibility, volumeByPromptId]);if (loading) {return (@@ -1023,33 +1130,52 @@ function AllPromptsTab({<TableHead className="pl-6">Prompt</TableHead><TableHead>Topic</TableHead><TableHead className="text-center">Status</TableHead>- <ColHead+ <SortableHeadclassName="text-right"tooltip="Average brand visibility score in AI answers for this prompt over the last 30 days."+ sortKey="visibility"+ activeSort={activeSort}+ dir={dir}+ onSort={handleSort}>Visibility- </ColHead>- <ColHead+ </SortableHead>+ <SortableHeadclassName="text-right"tooltip="Total times the brand was mentioned across AI answers for this prompt over the last 30 days."+ sortKey="mentions"+ activeSort={activeSort}+ dir={dir}+ onSort={handleSort}>Mentions- </ColHead>- <ColHead+ </SortableHead>+ <SortableHeadclassName="text-right"tooltip="Estimated monthly AI prompt volume, from keyword analysis. Empty until analysed."+ sortKey="volume"+ activeSort={activeSort}+ dir={dir}+ onSort={handleSort}>Volume- </ColHead>+ </SortableHead><ColHeadclassName="text-center"tooltip="Based on Google Ads competition for related keywords (LOW / MEDIUM / HIGH). A proxy for topic difficulty.">Competition</ColHead>- <ColHead className="text-right" tooltip="Most recent tracking run for this prompt.">+ <SortableHead+ className="text-right"+ tooltip="Most recent tracking run for this prompt."+ sortKey="lastRun"+ activeSort={activeSort}+ dir={dir}+ onSort={handleSort}+ >Last run- </ColHead>+ </SortableHead><TableHead className="text-right pr-6 w-[60px]">Edit</TableHead></TableRow></TableHeader>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.test.tsnew file mode 100644index 000000000..295ee507f--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { compareNullsLast } from './prompt-sort';++describe('compareNullsLast', () => {+ it('sorts non-null values ascending', () => {+ expect([5, 1, 3].sort((a, b) => compareNullsLast(a, b, 'asc'))).toEqual([1, 3, 5]);+ });++ it('sorts non-null values descending', () => {+ expect([5, 1, 3].sort((a, b) => compareNullsLast(a, b, 'desc'))).toEqual([5, 3, 1]);+ });++ it('keeps nulls last in ascending order', () => {+ const sorted = [3, null, 1, null, 2].sort((a, b) => compareNullsLast(a, b, 'asc'));+ expect(sorted).toEqual([1, 2, 3, null, null]);+ });++ it('keeps nulls last in descending order too', () => {+ const sorted = [3, null, 1, null, 2].sort((a, b) => compareNullsLast(a, b, 'desc'));+ expect(sorted).toEqual([3, 2, 1, null, null]);+ });++ it('treats equal values and two nulls as ties', () => {+ expect(compareNullsLast(4, 4, 'asc')).toBe(0);+ expect(compareNullsLast(null, null, 'desc')).toBe(0);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.ts b/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.tsnew file mode 100644index 000000000..b58151124--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/prompt-sort.ts@@ -0,0 +1,18 @@+export type SortDir = 'asc' | 'desc';++/**+ * Compare two numeric (or null) column values for the All Prompts table.+ *+ * Missing values (`null` — e.g. an unanalysed prompt with no volume/visibility)+ * always sort to the bottom in BOTH directions, so ascending ("weakest first")+ * doesn't push empty rows to the top. Non-null values sort ascending/descending+ * per `dir`.+ */+export function compareNullsLast(av: number | null, bv: number | null, dir: SortDir): number {+ if (av === null && bv === null) return 0;+ if (av === null) return 1;+ if (bv === null) return -1;+ if (av === bv) return 0;+ const factor = dir === 'asc' ? 1 : -1;+ return av < bv ? -factor : factor;+}