Skip to content

Open source alternative to Semrush and Ahrefs

Select multiple prompts on Prompt Research with the bulk-action pill (EVE-391) (#885)

Carter Smith41bc550a7dc7
diff --git a/src/client/components/table/DataTable.tsx b/src/client/components/table/DataTable.tsx
index 417b6d34..069f224a 100644
--- a/src/client/components/table/DataTable.tsx
+++ b/src/client/components/table/DataTable.tsx
@@ -11,6 +11,7 @@ import {
type TableOptions,
} from "@tanstack/react-table";
import {
+ Fragment,
useRef,
type ComponentProps,
type MouseEvent,
@@ -75,6 +76,8 @@ export function useSelectionAnchor(): MutableRefObject<SelectionAnchor | null> {
export function makeSelectionColumn<TData>(
anchorRef: MutableRefObject<SelectionAnchor | null>,
+ /** Names each row checkbox for screen readers. */
+ rowLabel: (row: Row<TData>) => string = () => "Select row",
): ColumnDef<TData> {
return {
id: "select",
@@ -83,14 +86,22 @@ export function makeSelectionColumn<TData>(
header: ({ table }) => (
<Checkbox
checked={table.getIsAllRowsSelected()}
- indeterminate={table.getIsSomeRowsSelected()}
- disabled={table.getRowModel().rows.length === 0}
+ // Some-selected also counts rows that can't be selected.
+ indeterminate={
+ table.getIsSomeRowsSelected() && !table.getIsAllRowsSelected()
+ }
+ disabled={!table.getRowModel().rows.some((row) => row.getCanSelect())}
onCheckedChange={(checked) => table.toggleAllRowsSelected(checked)}
aria-label="Select all rows"
/>
),
cell: ({ row, table }) => (
- <SelectionCheckbox row={row} table={table} anchorRef={anchorRef} />
+ <SelectionCheckbox
+ row={row}
+ table={table}
+ anchorRef={anchorRef}
+ label={rowLabel(row)}
+ />
),
};
}
@@ -99,15 +110,18 @@ function SelectionCheckbox<TData>({
row,
table,
anchorRef,
+ label,
}: {
row: Row<TData>;
table: TanStackTable<TData>;
anchorRef: MutableRefObject<SelectionAnchor | null>;
+ label: string;
}) {
return (
<Checkbox
checked={row.getIsSelected()}
- aria-label="Select row"
+ disabled={!row.getCanSelect()}
+ aria-label={label}
// The checkbox is a span, so a shift+click would also select page text.
onMouseDown={(event) => {
if (event.shiftKey) event.preventDefault();
@@ -160,6 +174,7 @@ export function DataTable<TData>({
onRowClick,
activeRowId,
scrollClassName,
+ renderExpandedRow,
}: DataTableFrameProps & {
table: TanStackTable<TData>;
/** Shown when there are no rows and no filters. */
@@ -176,6 +191,8 @@ export function DataTable<TData>({
activeRowId?: string;
/** Caps the table height, for example `max-h-96`. The header stays in view while the rows scroll. */
scrollClassName?: string;
+ /** Details shown in a full-width row under an expanded row. */
+ renderExpandedRow?: (row: Row<TData>) => ReactNode;
}) {
const columns = table.getVisibleLeafColumns();
const rows = table.getRowModel().rows;
@@ -252,36 +269,44 @@ export function DataTable<TData>({
</TableRow>
) : (
rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() ? "selected" : undefined}
- data-active={row.id === activeRowId ? "" : undefined}
- className={
- onRowClick
- ? "cursor-pointer data-active:bg-primary/5 data-active:shadow-[inset_2px_0_0_var(--color-primary)]"
- : undefined
- }
- onClick={
- onRowClick ? (event) => onRowClick(row, event) : undefined
- }
- >
- {row.getVisibleCells().map((cell) => {
- const meta = cell.column.columnDef.meta?.cellClassName;
- return (
- <TableCell
- key={cell.id}
- className={
- typeof meta === "function" ? meta(row) : meta
- }
- >
- {flexRender(
- cell.column.columnDef.cell,
- cell.getContext(),
- )}
+ <Fragment key={row.id}>
+ <TableRow
+ data-state={row.getIsSelected() ? "selected" : undefined}
+ data-active={row.id === activeRowId ? "" : undefined}
+ className={
+ onRowClick
+ ? "cursor-pointer data-active:bg-primary/5 data-active:shadow-[inset_2px_0_0_var(--color-primary)]"
+ : undefined
+ }
+ onClick={
+ onRowClick ? (event) => onRowClick(row, event) : undefined
+ }
+ >
+ {row.getVisibleCells().map((cell) => {
+ const meta = cell.column.columnDef.meta?.cellClassName;
+ return (
+ <TableCell
+ key={cell.id}
+ className={
+ typeof meta === "function" ? meta(row) : meta
+ }
+ >
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+ </TableCell>
+ );
+ })}
+ </TableRow>
+ {renderExpandedRow && row.getIsExpanded() ? (
+ <TableRow className="hover:bg-transparent">
+ <TableCell colSpan={columns.length}>
+ {renderExpandedRow(row)}
</TableCell>
- );
- })}
- </TableRow>
+ </TableRow>
+ ) : null}
+ </Fragment>
))
)}
</TableBody>
diff --git a/src/client/components/table/tableSelection.ts b/src/client/components/table/tableSelection.ts
index cfb732e1..f330a64f 100644
--- a/src/client/components/table/tableSelection.ts
+++ b/src/client/components/table/tableSelection.ts
@@ -6,7 +6,7 @@ export type SelectionAnchor = {
selected: boolean;
};
-type SelectionRow<T> = Pick<Row<T>, "id" | "getIsSelected">;
+type SelectionRow<T> = Pick<Row<T>, "id" | "getIsSelected" | "getCanSelect">;
type SelectionTable<T> = Pick<Table<T>, "setRowSelection"> & {
getRowModel: () => {
@@ -55,7 +55,7 @@ export function applyShiftRangeSelection<T>(
for (let index = from; index <= to; index++) {
const rangeRow = rows[index];
- if (!rangeRow) continue;
+ if (!rangeRow?.getCanSelect()) continue;
if (selected) {
nextSelection[rangeRow.id] = true;
diff --git a/src/client/components/ui/checkbox.tsx b/src/client/components/ui/checkbox.tsx
index 4a56b20b..70a9dca8 100644
--- a/src/client/components/ui/checkbox.tsx
+++ b/src/client/components/ui/checkbox.tsx
@@ -7,7 +7,7 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
- "group/checkbox peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground data-indeterminate:border-primary data-indeterminate:bg-primary data-indeterminate:text-primary-foreground dark:data-indeterminate:bg-primary group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",
+ "group/checkbox peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-disabled:cursor-not-allowed data-disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground data-indeterminate:border-primary data-indeterminate:bg-primary data-indeterminate:text-primary-foreground dark:data-indeterminate:bg-primary group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",
className,
)}
{...props}
diff --git a/src/client/features/ai-visibility/PromptResearchKeyword.tsx b/src/client/features/ai-visibility/PromptResearchKeyword.tsx
index 660b4304..35dbba67 100644
--- a/src/client/features/ai-visibility/PromptResearchKeyword.tsx
+++ b/src/client/features/ai-visibility/PromptResearchKeyword.tsx
@@ -1,7 +1,11 @@
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { SkeletonTableRows } from "@/client/components/SkeletonPresets";
-import { Button } from "@/client/components/ui/button";
+import type { RowSelectionState } from "@tanstack/react-table";
+import { Plus } from "lucide-react";
+import {
+ TableBulkActionBar,
+ TableBulkActionButton,
+} from "@/client/components/table/TableBulkActionBar";
import { researchAiVisibilityPrompts } from "@/serverFunctions/ai-visibility";
import { normalizeAiSuggestion } from "@/shared/ai-prompt-suggestions";
import type { AiTrackerState } from "@/shared/ai-visibility";
@@ -20,7 +24,7 @@ export function PromptResearchKeyword({
keyword: string;
}) {
const queryClient = useQueryClient();
- const [selected, setSelected] = useState<Set<string>>(new Set());
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [change, setChange] = useState<{
patch: AiTrackerPatch;
description: string;
@@ -40,6 +44,10 @@ export function PromptResearchKeyword({
staleTime: 60 * 60 * 1000,
refetchOnWindowFocus: false,
});
+ // Table order, so the review lists prompts as the user sees them.
+ const selected = (research.data?.prompts ?? [])
+ .filter((prompt) => rowSelection[prompt.text])
+ .map((prompt) => prompt.text);
const track = () => {
const topic =
state.topics.find(
@@ -47,44 +55,51 @@ export function PromptResearchKeyword({
normalizeAiSuggestion(name) === normalizeAiSuggestion(keyword),
) ?? keyword;
setChange({
- description: `Track ${selected.size} researched ${selected.size === 1 ? "prompt" : "prompts"} in the ${topic} topic.`,
- patch: { prompts: [...selected].map((text) => ({ text, topic })) },
+ description: `Track ${selected.length} researched ${selected.length === 1 ? "prompt" : "prompts"} in the ${topic} topic.`,
+ patch: { prompts: selected.map((text) => ({ text, topic })) },
});
};
return (
<>
- <div className="overflow-hidden rounded-lg border bg-card border-border">
- <div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 py-3 border-border">
- <h2 className="font-medium">Prompts about “{keyword}”</h2>
- <Button size="sm" disabled={!selected.size} onClick={track}>
- Track selected{selected.size ? ` (${selected.size})` : ""}
- </Button>
- </div>
- {research.isPending ? (
- <SkeletonTableRows rows={8} columns={4} className="p-4" />
- ) : research.isError ? (
- <AiQueryError
- error={research.error}
- retry={() => {
- void research.refetch();
- }}
- />
- ) : !research.data.prompts.length ? (
- <p className="p-10 text-center text-sm text-muted-foreground">
- No prompts found for “{keyword}”. Try a shorter, broader term.
- </p>
- ) : (
- <PromptResearchTable
- prompts={research.data.prompts}
- selected={selected}
- onToggle={(text) => {
- const next = new Set(selected);
- if (!next.delete(text)) next.add(text);
- setSelected(next);
- }}
- />
- )}
- </div>
+ <TableBulkActionBar
+ selectedCount={selected.length}
+ onClear={() => setRowSelection({})}
+ actions={
+ <div className="flex items-center px-1.5">
+ <TableBulkActionButton
+ icon={<Plus className="size-3.5" />}
+ onClick={track}
+ >
+ Track prompts
+ </TableBulkActionButton>
+ </div>
+ }
+ />
+ <PromptResearchTable
+ prompts={research.data?.prompts ?? []}
+ rowSelection={rowSelection}
+ onRowSelectionChange={setRowSelection}
+ isLoading={research.isPending}
+ error={
+ research.isError ? (
+ <AiQueryError
+ error={research.error}
+ retry={() => {
+ void research.refetch();
+ }}
+ />
+ ) : undefined
+ }
+ empty={{
+ title: `No prompts found for “${keyword}”`,
+ description: "Try a shorter, broader term.",
+ }}
+ toolbar={
+ <div className="border-b px-4 py-3 border-border">
+ <h2 className="font-medium">Prompts about “{keyword}”</h2>
+ </div>
+ }
+ />
{change && (
<TrackerPatchReview
projectId={projectId}
@@ -98,7 +113,7 @@ export function PromptResearchKeyword({
next,
);
setChange(null);
- setSelected(new Set());
+ setRowSelection({});
}}
/>
)}
diff --git a/src/client/features/ai-visibility/PromptResearchTable.tsx b/src/client/features/ai-visibility/PromptResearchTable.tsx
index c8241f9c..c19473c4 100644
--- a/src/client/features/ai-visibility/PromptResearchTable.tsx
+++ b/src/client/features/ai-visibility/PromptResearchTable.tsx
@@ -1,131 +1,123 @@
-import { useState } from "react";
+import { useMemo, type ComponentProps } from "react";
+import type {
+ ColumnDef,
+ OnChangeFn,
+ RowSelectionState,
+} from "@tanstack/react-table";
import { ChevronDown, ChevronRight } from "lucide-react";
import { SafeExternalLink } from "@/client/components/SafeExternalLink";
+import {
+ DataTable,
+ type DataTableFrameProps,
+ makeSelectionColumn,
+ useDataTable,
+ useSelectionAnchor,
+} from "@/client/components/table/DataTable";
import { Badge } from "@/client/components/ui/badge";
import { Button } from "@/client/components/ui/button";
-import { Checkbox } from "@/client/components/ui/checkbox";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/client/components/ui/table";
import type { AiResearchedPrompt } from "@/shared/ai-visibility";
import { DomainFavicon } from "./DomainFavicon";
+const promptColumns: ColumnDef<AiResearchedPrompt>[] = [
+ {
+ id: "prompt",
+ header: "Prompt",
+ cell: ({ row: { original: prompt } }) => (
+ <>
+ <span>{prompt.text}</span>
+ {prompt.tracked && (
+ <Badge variant="secondary" className="ml-2">
+ Tracked
+ </Badge>
+ )}
+ {prompt.variants.length > 0 && (
+ <p
+ className="text-xs text-muted-foreground"
+ title={prompt.variants.join("\n")}
+ >
+ +{prompt.variants.length} similar{" "}
+ {prompt.variants.length === 1 ? "prompt" : "prompts"} merged
+ </p>
+ )}
+ </>
+ ),
+ },
+ {
+ id: "sources",
+ header: "Sources",
+ meta: { headerClassName: "w-40" },
+ cell: ({ row: { original: prompt } }) => (
+ <>
+ <span className="text-sm">
+ {prompt.sources.length
+ ? `${prompt.sources.length} ${prompt.sources.length === 1 ? "source" : "sources"}`
+ : "No sources"}
+ </span>
+ {prompt.ownDomainCited && (
+ <Badge variant="success" size="sm" className="ml-2">
+ You
+ </Badge>
+ )}
+ </>
+ ),
+ },
+ {
+ id: "expand",
+ header: () => <span className="sr-only">Details</span>,
+ meta: { headerClassName: "w-10" },
+ cell: ({ row }) => (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-expanded={row.getIsExpanded()}
+ aria-label={`Show sources for ${row.original.text}`}
+ onClick={() => row.toggleExpanded()}
+ >
+ {row.getIsExpanded() ? <ChevronDown /> : <ChevronRight />}
+ </Button>
+ ),
+ },
+];
+
+/** Tracked prompts can't be selected; a selection only adds new prompts. */
export function PromptResearchTable({
prompts,
- selected,
- onToggle,
-}: {
+ rowSelection,
+ onRowSelectionChange,
+ empty,
+ ...frame
+}: DataTableFrameProps & {
prompts: AiResearchedPrompt[];
- selected: Set<string>;
- onToggle: (text: string) => void;
+ rowSelection: RowSelectionState;
+ onRowSelectionChange: OnChangeFn<RowSelectionState>;
+ empty: ComponentProps<typeof DataTable>["empty"];
}) {
- const [expanded, setExpanded] = useState<string | null>(null);
- return (
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10" />
- <TableHead>Prompt</TableHead>
- <TableHead className="w-40">Sources</TableHead>
- <TableHead className="w-10" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {prompts.map((prompt) => (
- <PromptRow
- key={prompt.text}
- prompt={prompt}
- selected={selected.has(prompt.text)}
- expanded={expanded === prompt.text}
- onToggle={() => onToggle(prompt.text)}
- onExpand={() =>
- setExpanded(expanded === prompt.text ? null : prompt.text)
- }
- />
- ))}
- </TableBody>
- </Table>
+ const selectAnchorRef = useSelectionAnchor();
+ const columns = useMemo(
+ () => [
+ makeSelectionColumn<AiResearchedPrompt>(
+ selectAnchorRef,
+ (row) => `Select ${row.original.text}`,
+ ),
+ ...promptColumns,
+ ],
+ [selectAnchorRef],
);
-}
-
-function PromptRow({
- prompt,
- selected,
- expanded,
- onToggle,
- onExpand,
-}: {
- prompt: AiResearchedPrompt;
- selected: boolean;
- expanded: boolean;
- onToggle: () => void;
- onExpand: () => void;
-}) {
+ const table = useDataTable({
+ data: prompts,
+ columns,
+ state: { rowSelection },
+ onRowSelectionChange,
+ getRowId: (prompt) => prompt.text,
+ enableRowSelection: (row) => !row.original.tracked,
+ });
return (
- <>
- <TableRow data-state={selected ? "selected" : undefined}>
- <TableCell>
- <Checkbox
- checked={selected || prompt.tracked}
- disabled={prompt.tracked}
- onCheckedChange={onToggle}
- aria-label={`Select ${prompt.text}`}
- />
- </TableCell>
- <TableCell className="whitespace-normal">
- <span>{prompt.text}</span>
- {prompt.tracked && (
- <Badge variant="secondary" className="ml-2">
- Tracked
- </Badge>
- )}
- {prompt.variants.length > 0 && (
- <p
- className="text-xs text-muted-foreground"
- title={prompt.variants.join("\n")}
- >
- +{prompt.variants.length} similar{" "}
- {prompt.variants.length === 1 ? "prompt" : "prompts"} merged
- </p>
- )}
- </TableCell>
- <TableCell className="whitespace-normal">
- <span className="text-sm">
- {prompt.sources.length
- ? `${prompt.sources.length} ${prompt.sources.length === 1 ? "source" : "sources"}`
- : "No sources"}
- </span>
- {prompt.ownDomainCited && (
- <Badge variant="success" size="sm" className="ml-2">
- You
- </Badge>
- )}
- </TableCell>
- <TableCell>
- <Button
- variant="ghost"
- size="icon-sm"
- aria-expanded={expanded}
- aria-label={`Show sources for ${prompt.text}`}
- onClick={onExpand}
- >
- {expanded ? <ChevronDown /> : <ChevronRight />}
- </Button>
- </TableCell>
- </TableRow>
- {expanded && (
- <TableRow className="hover:bg-transparent">
- <TableCell colSpan={4} className="whitespace-normal">
- <PromptSources prompt={prompt} />
- </TableCell>
- </TableRow>
- )}
- </>
+ <DataTable
+ {...frame}
+ table={table}
+ empty={empty}
+ renderExpandedRow={(row) => <PromptSources prompt={row.original} />}
+ />
);
}
diff --git a/src/client/features/rank-tracking/tableSelection.test.ts b/src/client/features/rank-tracking/tableSelection.test.ts
index 0a398e97..6b892ab9 100644
--- a/src/client/features/rank-tracking/tableSelection.test.ts
+++ b/src/client/features/rank-tracking/tableSelection.test.ts
@@ -10,6 +10,7 @@ function makeRow(id: string, selectedIds: Set<string>) {
return {
id,
getIsSelected: () => selectedIds.has(id),
+ getCanSelect: () => id !== "locked",
};
}
@@ -98,4 +99,21 @@ describe("applyShiftRangeSelection", () => {
expect(Array.from(selectedIds)).toEqual(["a"]);
expect(anchorRef.current).toEqual({ id: "d", selected: false });
});
+
+ it("skips rows that can't be selected", () => {
+ const selectedIds = new Set<string>();
+ const table = makeTable(["a", "locked", "c"], selectedIds);
+ const anchorRef: MutableRefObject<SelectionAnchor | null> = {
+ current: { id: "a", selected: true },
+ };
+
+ applyShiftRangeSelection(
+ makeEvent(true),
+ makeRow("c", selectedIds),
+ table,
+ anchorRef,
+ );
+
+ expect(Array.from(selectedIds)).toEqual(["a", "c"]);
+ });
});