Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: optimize perf (#20388)

ecmadao48b4422b8b0f
diff --git a/frontend/src/react/components/AuditLogTable.tsx b/frontend/src/react/components/AuditLogTable.tsx
index 9735735301..3b95648033 100644
--- a/frontend/src/react/components/AuditLogTable.tsx
+++ b/frontend/src/react/components/AuditLogTable.tsx
@@ -3,7 +3,7 @@ import { AnySchema } from "@bufbuild/protobuf/wkt";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import { Download, ExternalLink, Maximize2, X } from "lucide-react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { auditLogServiceClientConnect } from "@/connect";
import { ALL_METHODS_WITH_AUDIT } from "@/connect/methods";
@@ -445,6 +445,26 @@ function useColumnDefs(): ColumnDef[] {
);
}
+interface AuditLogRowProps {
+ log: AuditLog;
+ columns: ColumnDef[];
+}
+
+const AuditLogRowView = memo(function AuditLogRowView({
+ log,
+ columns,
+}: AuditLogRowProps) {
+ return (
+ <TableRow>
+ {columns.map((col) => (
+ <TableCell key={col.key} className="align-top overflow-hidden">
+ {col.render(log)}
+ </TableCell>
+ ))}
+ </TableRow>
+ );
+});
+
// ============================================================
// AuditLogTable — shared component
// ============================================================
@@ -775,16 +795,11 @@ export function AuditLogTable({
</TableRow>
) : (
auditLogs.map((log, idx) => (
- <TableRow key={log.name || idx}>
- {columns.map((col) => (
- <TableCell
- key={col.key}
- className="align-top overflow-hidden"
- >
- {col.render(log)}
- </TableCell>
- ))}
- </TableRow>
+ <AuditLogRowView
+ key={log.name || idx}
+ log={log}
+ columns={columns}
+ />
))
)}
</TableBody>
diff --git a/frontend/src/react/components/EnvironmentLabel.tsx b/frontend/src/react/components/EnvironmentLabel.tsx
index b39910a2c2..0adfca402c 100644
--- a/frontend/src/react/components/EnvironmentLabel.tsx
+++ b/frontend/src/react/components/EnvironmentLabel.tsx
@@ -1,4 +1,5 @@
import { ShieldAlert } from "lucide-react";
+import { memo } from "react";
import { useTranslation } from "react-i18next";
import { useEnvironment, usePlanFeature } from "@/react/hooks/useAppState";
import { cn } from "@/react/lib/utils";
@@ -8,39 +9,30 @@ import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { hexToRgb } from "@/utils";
/**
- * Renders an environment as a colored pill with optional shield icon
- * for protected environments.
+ * Pure-presentational environment badge — no hooks, no store reads.
*
- * Two usage modes:
- * - Pass `environment` object directly (avoids store lookup)
- * - Pass `environmentName` string (looks up from environment store)
+ * Use this in row-heavy contexts (e.g. DatabaseTableView with hundreds of
+ * rows) where the caller can hoist `useEnvironmentList()` + the env-tier
+ * feature check to the table level and pass the resolved `environment` and
+ * `hasEnvTierFeature` flag down. That avoids N Zustand subscriptions and
+ * N redundant `loadSubscription` effects per row.
*/
-export function EnvironmentLabel({
- environment: envProp,
- environmentName,
+export const EnvironmentBadge = memo(function EnvironmentBadge({
+ environment,
+ hasEnvTierFeature,
className,
}: {
- environment?: Environment;
- environmentName?: string;
+ environment: Environment;
+ hasEnvTierFeature: boolean;
className?: string;
}) {
const { t } = useTranslation();
- // Always called (rules of hooks); result ignored when envProp is provided.
- const envFromStore = useEnvironment(environmentName || NULL_ENVIRONMENT_NAME);
-
- const environment = envProp ?? envFromStore;
-
const isUnset =
environment.name === UNKNOWN_ENVIRONMENT_NAME ||
environment.name === NULL_ENVIRONMENT_NAME;
-
- const hasEnvTierFeature = usePlanFeature(
- PlanFeature.FEATURE_ENVIRONMENT_TIERS
- );
const isProtected =
hasEnvTierFeature && environment.tags?.protected === "protected";
-
const bgColorRgb = environment.color ? hexToRgb(environment.color) : null;
return (
@@ -72,4 +64,39 @@ export function EnvironmentLabel({
)}
</span>
);
+});
+
+/**
+ * Renders an environment as a colored pill with optional shield icon
+ * for protected environments. Smart wrapper that looks up the environment
+ * by name and checks the env-tier feature gate.
+ *
+ * Two usage modes:
+ * - Pass `environment` object directly (avoids env store lookup)
+ * - Pass `environmentName` string (looks up from environment store)
+ *
+ * For high-row use, prefer `EnvironmentBadge` directly with hoisted data.
+ */
+export function EnvironmentLabel({
+ environment: envProp,
+ environmentName,
+ className,
+}: {
+ environment?: Environment;
+ environmentName?: string;
+ className?: string;
+}) {
+ // Always called (rules of hooks); result ignored when envProp is provided.
+ const envFromStore = useEnvironment(environmentName || NULL_ENVIRONMENT_NAME);
+ const environment = envProp ?? envFromStore;
+ const hasEnvTierFeature = usePlanFeature(
+ PlanFeature.FEATURE_ENVIRONMENT_TIERS
+ );
+ return (
+ <EnvironmentBadge
+ environment={environment}
+ hasEnvTierFeature={hasEnvTierFeature}
+ className={className}
+ />
+ );
}
diff --git a/frontend/src/react/components/IssueTable.tsx b/frontend/src/react/components/IssueTable.tsx
index e9f9f43767..1af301449c 100644
--- a/frontend/src/react/components/IssueTable.tsx
+++ b/frontend/src/react/components/IssueTable.tsx
@@ -1,6 +1,6 @@
import { create } from "@bufbuild/protobuf";
import { ArrowUpDown, Check, Loader2 } from "lucide-react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { issueServiceClientConnect } from "@/connect";
import {
@@ -558,7 +558,7 @@ export function useIssueSearchScopeOptions(
// IssueListItem
// ===========================================================================
-export function IssueListItem({
+export const IssueListItem = memo(function IssueListItem({
issue,
selected,
onToggleSelection,
@@ -567,7 +567,8 @@ export function IssueListItem({
}: {
issue: Issue;
selected: boolean;
- onToggleSelection: () => void;
+ /** Called with the issue's name; pass a stable callback from the parent. */
+ onToggleSelection: (name: string) => void;
highlightText?: string;
showProject?: boolean;
}) {
@@ -634,12 +635,12 @@ export function IssueListItem({
className="shrink-0 self-stretch cursor-pointer"
onClick={(e) => {
e.stopPropagation();
- onToggleSelection();
+ onToggleSelection(issue.name);
}}
>
<Checkbox
checked={selected}
- onCheckedChange={() => onToggleSelection()}
+ onCheckedChange={() => onToggleSelection(issue.name)}
onClick={(e) => e.stopPropagation()}
/>
</div>
@@ -744,7 +745,7 @@ export function IssueListItem({
</div>
</div>
);
-}
+});
// ===========================================================================
// IssueStatusIcon
diff --git a/frontend/src/react/components/ProjectTable.tsx b/frontend/src/react/components/ProjectTable.tsx
index 2e3a8a71fd..7c12fcc19c 100644
--- a/frontend/src/react/components/ProjectTable.tsx
+++ b/frontend/src/react/components/ProjectTable.tsx
@@ -1,5 +1,6 @@
import { Check } from "lucide-react";
import type { MouseEvent as ReactMouseEvent, ReactNode } from "react";
+import { memo, useCallback, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { HighlightLabelText } from "@/react/components/HighlightLabelText";
import { Badge } from "@/react/components/ui/badge";
@@ -109,14 +110,22 @@ export function ProjectTable({
}: ProjectTableProps) {
const { t } = useTranslation();
const showLeadingCheck = !!currentProject && !showSelection;
- const selectableProjects = projectList.filter(
- (p) => getProjectName(p.name) !== "default"
+ const currentProjectName = currentProject?.name;
+ const allSelectableNames = useMemo(
+ () =>
+ projectList
+ .filter((p) => getProjectName(p.name) !== "default")
+ .map((p) => p.name),
+ [projectList]
+ );
+ const selectedNameSet = useMemo(
+ () => new Set(selectedProjectNames),
+ [selectedProjectNames]
);
- const allSelectableNames = selectableProjects.map((p) => p.name);
const allSelected =
showSelection &&
allSelectableNames.length > 0 &&
- allSelectableNames.every((name) => selectedProjectNames.includes(name));
+ allSelectableNames.every((name) => selectedNameSet.has(name));
const totalColumns =
(showSelection || showLeadingCheck ? 1 : 0) +
@@ -125,18 +134,48 @@ export function ProjectTable({
(showLabels ? 1 : 0) +
(showActions ? 1 : 0);
- const handleSelectAll = () => {
- if (!onSelectedChange) return;
- onSelectedChange(allSelected ? [] : allSelectableNames);
- };
+ // Use refs so per-row handlers stay stable across selection changes.
+ const selectedNameSetRef = useRef(selectedNameSet);
+ selectedNameSetRef.current = selectedNameSet;
+ const selectedProjectNamesRef = useRef(selectedProjectNames);
+ selectedProjectNamesRef.current = selectedProjectNames;
+ const onSelectedChangeRef = useRef(onSelectedChange);
+ onSelectedChangeRef.current = onSelectedChange;
+ const onRowClickRef = useRef(onRowClick);
+ onRowClickRef.current = onRowClick;
+ const renderActionsRef = useRef(renderActions);
+ renderActionsRef.current = renderActions;
+
+ const handleSelectAll = useCallback(() => {
+ const cb = onSelectedChangeRef.current;
+ if (!cb) return;
+ const everyCurrentlySelected =
+ allSelectableNames.length > 0 &&
+ allSelectableNames.every((name) => selectedNameSetRef.current.has(name));
+ cb(everyCurrentlySelected ? [] : [...allSelectableNames]);
+ }, [allSelectableNames]);
+
+ const handleToggleRow = useCallback((name: string) => {
+ const cb = onSelectedChangeRef.current;
+ if (!cb) return;
+ const current = selectedProjectNamesRef.current;
+ const next = selectedNameSetRef.current.has(name)
+ ? current.filter((n) => n !== name)
+ : [...current, name];
+ cb(next as string[]);
+ }, []);
- const handleToggleRow = (name: string) => {
- if (!onSelectedChange) return;
- const next = selectedProjectNames.includes(name)
- ? selectedProjectNames.filter((n) => n !== name)
- : [...selectedProjectNames, name];
- onSelectedChange(next as string[]);
- };
+ const handleRowClick = useCallback(
+ (project: Project, event: ReactMouseEvent<HTMLTableRowElement>) => {
+ onRowClickRef.current?.(project, event);
+ },
+ []
+ );
+
+ const renderActionsStable = useCallback(
+ (project: Project) => renderActionsRef.current?.(project) ?? null,
+ []
+ );
return (
<Table className={className}>
@@ -201,89 +240,124 @@ export function ProjectTable({
</TableCell>
</TableRow>
) : (
- projectList.map((project) => {
- const resourceId = getProjectName(project.name);
- const isDefault = resourceId === "default";
- const isCurrent = currentProject?.name === project.name;
- const isSelected = selectedProjectNames.includes(project.name);
- return (
- <TableRow
- key={project.name}
- className={cn(onRowClick && "cursor-pointer")}
- onClick={(event) => onRowClick?.(project, event)}
- >
- {showSelection ? (
- <TableCell
- className={cn("w-12", !isDefault && "cursor-pointer")}
- onClick={(e) => {
- e.stopPropagation();
- if (isDefault) return;
- handleToggleRow(project.name);
- }}
- >
- <Checkbox
- checked={isSelected}
- aria-label={t("common.select")}
- disabled={isDefault}
- onCheckedChange={() => handleToggleRow(project.name)}
- onClick={(e) => e.stopPropagation()}
- className="disabled:opacity-50"
- />
- </TableCell>
- ) : showLeadingCheck ? (
- <TableCell className="w-8 px-2">
- {isCurrent ? (
- <Check className="size-4 text-accent" />
- ) : null}
- </TableCell>
- ) : null}
- <TableCell>
- <EllipsisText text={resourceId}>
- <HighlightLabelText text={resourceId} keyword={keyword} />
- </EllipsisText>
- </TableCell>
- <TableCell>
- <div className="flex items-center gap-x-2 min-w-0">
- <EllipsisText
- text={project.title || resourceId}
- className="min-w-0"
- >
- <HighlightLabelText
- text={project.title || resourceId}
- keyword={keyword}
- />
- </EllipsisText>
- {project.state === State.DELETED ? (
- <Badge variant="warning" className="text-xs shrink-0">
- {t("common.archived")}
- </Badge>
- ) : null}
- </div>
- </TableCell>
- {showLabels ? (
- <TableCell className="hidden md:table-cell">
- <LabelsCell labels={project.labels ?? {}} />
- </TableCell>
- ) : null}
- {showActions ? (
- <TableCell
- className="w-[50px]"
- onClick={(e) => e.stopPropagation()}
- >
- <div className="flex justify-end">
- {renderActions?.(project)}
- </div>
- </TableCell>
- ) : null}
- </TableRow>
- );
- })
+ projectList.map((project) => (
+ <ProjectRowView
+ key={project.name}
+ project={project}
+ isCurrent={currentProjectName === project.name}
+ isSelected={selectedNameSet.has(project.name)}
+ showSelection={showSelection}
+ showLeadingCheck={showLeadingCheck}
+ showLabels={showLabels}
+ showActions={showActions}
+ clickable={!!onRowClick}
+ keyword={keyword}
+ onToggleRow={handleToggleRow}
+ onRowClick={handleRowClick}
+ renderActions={renderActionsStable}
+ />
+ ))
)}
</TableBody>
</Table>
);
}
+interface ProjectRowViewProps {
+ project: Project;
+ isCurrent: boolean;
+ isSelected: boolean;
+ showSelection: boolean;
+ showLeadingCheck: boolean;
+ showLabels: boolean;
+ showActions: boolean;
+ clickable: boolean;
+ keyword: string;
+ onToggleRow: (name: string) => void;
+ onRowClick: (
+ project: Project,
+ event: ReactMouseEvent<HTMLTableRowElement>
+ ) => void;
+ renderActions: (project: Project) => ReactNode;
+}
+
+const ProjectRowView = memo(function ProjectRowView({
+ project,
+ isCurrent,
+ isSelected,
+ showSelection,
+ showLeadingCheck,
+ showLabels,
+ showActions,
+ clickable,
+ keyword,
+ onToggleRow,
+ onRowClick,
+ renderActions,
+}: ProjectRowViewProps) {
+ const { t } = useTranslation();
+ const resourceId = getProjectName(project.name);
+ const isDefault = resourceId === "default";
+ const titleText = project.title || resourceId;
+ return (
+ <TableRow
+ className={cn(clickable && "cursor-pointer")}
+ onClick={(event) => onRowClick(project, event)}
+ >
+ {showSelection ? (
+ <TableCell
+ className={cn("w-12", !isDefault && "cursor-pointer")}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (isDefault) return;
+ onToggleRow(project.name);
+ }}
+ >
+ <Checkbox
+ checked={isSelected}
+ aria-label={t("common.select")}
+ disabled={isDefault}
+ onCheckedChange={() => onToggleRow(project.name)}
+ onClick={(e) => e.stopPropagation()}
+ className="disabled:opacity-50"
+ />
+ </TableCell>
+ ) : showLeadingCheck ? (
+ <TableCell className="w-8 px-2">
+ {isCurrent ? <Check className="size-4 text-accent" /> : null}
+ </TableCell>
+ ) : null}
+ <TableCell>
+ <EllipsisText text={resourceId}>
+ <HighlightLabelText text={resourceId} keyword={keyword} />
+ </EllipsisText>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-x-2 min-w-0">
+ <EllipsisText text={titleText} className="min-w-0">
+ <HighlightLabelText text={titleText} keyword={keyword} />
+ </EllipsisText>
+ {project.state === State.DELETED ? (
+ <Badge variant="warning" className="text-xs shrink-0">
+ {t("common.archived")}
+ </Badge>
+ ) : null}
+ </div>
+ </TableCell>
+ {showLabels ? (
+ <TableCell className="hidden md:table-cell">
+ <LabelsCell labels={project.labels ?? {}} />
+ </TableCell>
+ ) : null}
+ {showActions ? (
+ <TableCell className="w-[50px]" onClick={(e) => e.stopPropagation()}>
+ <div className="flex justify-end">{renderActions(project)}</div>
+ </TableCell>
+ ) : null}
+ </TableRow>
+ );
+});
+
/**
* Mirrors Vue's `LabelsCell` — show up to N labels inline, "..." for
* the rest, and a tooltip on hover that lists all of them.
diff --git a/frontend/src/react/components/database/DatabaseTableView.tsx b/frontend/src/react/components/database/DatabaseTableView.tsx
index 5cad42ceab..49ad6b575a 100644
--- a/frontend/src/react/components/database/DatabaseTableView.tsx
+++ b/frontend/src/react/components/database/DatabaseTableView.tsx
@@ -1,8 +1,8 @@
import { CheckCircle, XCircle } from "lucide-react";
-import { useMemo } from "react";
+import { memo, useCallback, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { EngineIcon } from "@/react/components/EngineIcon";
-import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
+import { EnvironmentBadge } from "@/react/components/EnvironmentLabel";
import { LabelsDisplay } from "@/react/components/LabelsDisplay";
import { Checkbox } from "@/react/components/ui/checkbox";
import { EllipsisText } from "@/react/components/ui/ellipsis-text";
@@ -14,14 +14,21 @@ import {
TableHeader,
TableRow,
} from "@/react/components/ui/table";
+import { useEnvironmentList, usePlanFeature } from "@/react/hooks/useAppState";
import { useColumnWidths } from "@/react/hooks/useColumnWidths";
import { cn } from "@/react/lib/utils";
+import type { Environment } from "@/types";
+import {
+ isValidEnvironmentName,
+ nullEnvironment,
+ unknownEnvironment,
+} from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { SyncStatus } from "@/types/proto-es/v1/database_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import {
extractDatabaseResourceName,
extractProjectResourceName,
- getDatabaseEnvironment,
getDatabaseProject,
getInstanceResource,
hostPortOfInstanceV1,
@@ -91,6 +98,34 @@ export function DatabaseTableView({
}: DatabaseTableViewProps) {
const { t } = useTranslation();
+ // Lift environment + feature lookups to the table level so the per-row
+ // env cell doesn't subscribe to Zustand or run a `.find()` per render.
+ // Without this, a 500-row table registers 500 redundant subscriptions
+ // to `environmentList` + `hasFeature` and re-runs `loadSubscription`
+ // 500 times. The Map below collapses lookups to O(1) per row.
+ const environmentList = useEnvironmentList();
+ const environmentByName = useMemo(() => {
+ const map = new Map<string, Environment>();
+ for (const env of environmentList) {
+ map.set(env.name, env);
+ }
+ return map;
+ }, [environmentList]);
+ const hasEnvTierFeature = usePlanFeature(
+ PlanFeature.FEATURE_ENVIRONMENT_TIERS
+ );
+ const resolveEnvironment = useCallback(
+ (name: string | undefined): Environment => {
+ if (!name) return nullEnvironment();
+ const env = environmentByName.get(name);
+ if (env) return env;
+ if (!isValidEnvironmentName(name)) return unknownEnvironment();
+ const id = name.replace(/^environments\//, "");
+ return { ...unknownEnvironment(), id, name, title: id };
+ },
+ [environmentByName]
+ );
+
const showSelection = !!selectedNames && !!onSelectedNamesChange;
const showProjectColumn = mode === "ALL";
const sortable = !!onSortChange;
@@ -108,58 +143,52 @@ export function DatabaseTableView({
}
};
- const toggleSelection = (name: string) => {
- if (!selectedNames || !onSelectedNamesChange) return;
- const next = new Set(selectedNames);
+ // Refs so per-row handlers stay referentially stable across selection
+ // changes — without this, every selection toggle re-creates the closure
+ // and `React.memo` on `DatabaseRowView` is defeated for every row.
+ const selectedNamesRef = useRef(selectedNames);
+ selectedNamesRef.current = selectedNames;
+ const onSelectedNamesChangeRef = useRef(onSelectedNamesChange);
+ onSelectedNamesChangeRef.current = onSelectedNamesChange;
+ const databasesRef = useRef(databases);
+ databasesRef.current = databases;
+
+ const toggleSelection = useCallback((name: string) => {
+ const current = selectedNamesRef.current;
+ const cb = onSelectedNamesChangeRef.current;
+ if (!current || !cb) return;
+ const next = new Set(current);
if (next.has(name)) next.delete(name);
else next.add(name);
- onSelectedNamesChange(next);
- };
+ cb(next);
+ }, []);
- const toggleSelectAll = () => {
- if (!selectedNames || !onSelectedNamesChange) return;
- if (selectedNames.size === databases.length) {
- onSelectedNamesChange(new Set());
+ const toggleSelectAll = useCallback(() => {
+ const current = selectedNamesRef.current;
+ const cb = onSelectedNamesChangeRef.current;
+ const dbs = databasesRef.current;
+ if (!current || !cb) return;
+ if (current.size === dbs.length) {
+ cb(new Set());
} else {
- onSelectedNamesChange(new Set(databases.map((db) => db.name)));
+ cb(new Set(dbs.map((db) => db.name)));
}
- };
+ }, []);
const allSelected =
databases.length > 0 && (selectedNames?.size ?? 0) === databases.length;
const someSelected =
(selectedNames?.size ?? 0) > 0 &&
(selectedNames?.size ?? 0) < databases.length;
+
+ // `columns` is intentionally NOT a function of `selectedNames` /
+ // `databases` so it stays referentially stable across selection toggles
+ // and pagination. The select column used to live here and dragged
+ // `selectedNames` into the deps, which invalidated `columns` on every
+ // toggle and forced every row to re-render. The leading checkbox is now
+ // rendered separately in the row + header so columns can stay stable.
const columns = useMemo<DatabaseColumn[]>(() => {
const cols: DatabaseColumn[] = [];
- if (showSelection) {
- cols.push({
- key: "select",
- title: (
- <Checkbox
- checked={someSelected ? "indeterminate" : allSelected}
- onCheckedChange={toggleSelectAll}
- onClick={(e) => e.stopPropagation()}
- />
- ),
- defaultWidth: 48,
- onCellClick: (db, e) => {
- e.stopPropagation();
- toggleSelection(db.name);
- },
- onHeaderClick: (e) => {
- e.stopPropagation();
- toggleSelectAll();
- },
- render: (db) => (
- <Checkbox
- checked={selectedNames?.has(db.name) ?? false}
- onCheckedChange={() => toggleSelection(db.name)}
- onClick={(e) => e.stopPropagation()}
- />
- ),
- });
- }
cols.push({
key: "name",
title: t("common.name"),
@@ -186,7 +215,10 @@ export function DatabaseTableView({
minWidth: 120,
resizable: true,
render: (db) => (
- <EnvironmentLabel environmentName={getDatabaseEnvironment(db).name} />
+ <EnvironmentBadge
+ environment={resolveEnvironment(db.effectiveEnvironment)}
+ hasEnvTierFeature={hasEnvTierFeature}
+ />
),
});
if (showProjectColumn) {
@@ -265,33 +297,38 @@ export function DatabaseTableView({
),
});
return cols;
- // `databases` and `onSelectedNamesChange` belong here because the
- // header checkbox's `toggleSelectAll` closes over both. Pagination /
- // filtering can replace `databases` while `allSelected` stays false —
- // without listing it the memoized handler keeps the previous page's
- // names and "select all" selects the wrong rows.
- }, [
- showSelection,
- showProjectColumn,
- allSelected,
- selectedNames,
- onSelectedNamesChange,
- databases,
- t,
- ]);
+ }, [showProjectColumn, t, resolveEnvironment, hasEnvTierFeature]);
const { widths, totalWidth, onResizeStart } = useColumnWidths(columns);
+ const totalColumnCount = columns.length + (showSelection ? 1 : 0);
+
return (
<div className="overflow-x-auto border rounded-sm">
<Table className="table-fixed" style={{ minWidth: `${totalWidth}px` }}>
<colgroup>
+ {showSelection && <col style={{ width: "48px" }} />}
{widths.map((w, i) => (
<col key={columns[i].key} style={{ width: `${w}px` }} />
))}
</colgroup>
<TableHeader>
<TableRow className="bg-control-bg">
+ {showSelection && (
+ <TableHead
+ className="cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleSelectAll();
+ }}
+ >
+ <Checkbox
+ checked={someSelected ? "indeterminate" : allSelected}
+ onCheckedChange={toggleSelectAll}
+ onClick={(e) => e.stopPropagation()}
+ />
+ </TableHead>
+ )}
{columns.map((col, colIdx) => {
const colSortKey = col.sortKey;
const sortActive = Boolean(
@@ -325,7 +362,7 @@ export function DatabaseTableView({
{loading && databases.length === 0 ? (
<TableRow>
<TableCell
- colSpan={columns.length}
+ colSpan={totalColumnCount}
className="py-8 text-center text-control-placeholder"
>
<div className="flex items-center justify-center gap-x-2">
@@ -337,7 +374,7 @@ export function DatabaseTableView({
) : databases.length === 0 ? (
<TableRow>
<TableCell
- colSpan={columns.length}
+ colSpan={totalColumnCount}
className="py-8 text-center text-control-placeholder"
>
{t("common.no-data")}
@@ -345,29 +382,15 @@ export function DatabaseTableView({
</TableRow>
) : (
databases.map((db) => (
- <TableRow
+ <DatabaseRowView
key={db.name}
- className={onRowClick ? "cursor-pointer" : undefined}
- onClick={onRowClick ? (e) => onRowClick(db, e) : undefined}
- >
- {columns.map((col) => (
- <TableCell
- key={col.key}
- className={cn(
- "overflow-hidden",
- col.cellClassName,
- col.onCellClick && "cursor-pointer"
- )}
- onClick={
- col.onCellClick
- ? (e) => col.onCellClick!(db, e)
- : undefined
- }
- >
- {col.render(db)}
- </TableCell>
- ))}
- </TableRow>
+ database={db}
+ columns={columns}
+ showSelection={showSelection}
+ selected={selectedNames?.has(db.name) ?? false}
+ onToggleSelection={toggleSelection}
+ onRowClick={onRowClick}
+ />
))
)}
</TableBody>
@@ -375,3 +398,71 @@ export function DatabaseTableView({
</div>
);
}
+
+interface DatabaseRowViewProps {
+ database: Database;
+ columns: DatabaseColumn[];
+ showSelection: boolean;
+ /** Primitive boolean — keeps memo equality cheap. Only flips for the
+ * row whose selection changed, so other rows skip re-rendering even
+ * when the parent re-runs (e.g. selection toggles, pagination loads). */
+ selected: boolean;
+ /** Stable per-render thanks to `useCallback` upstream. Wrapped via
+ * closure inside the row so the Checkbox can call it with the row's
+ * `database.name` without forcing the row to depend on `selectedNames`. */
+ onToggleSelection: (name: string) => void;
+ onRowClick?: (db: Database, e: React.MouseEvent) => void;
+}
+
+/**
+ * Memoized per-row renderer. Keeps large database tables (hundreds of
+ * rows) from re-running every cell's per-row helpers (`getInstanceResource`,
+ * `getDatabaseEnvironment`, `getDatabaseProject`, etc.) on every parent
+ * re-render. Only props on this list trigger a re-render of a given row.
+ */
+const DatabaseRowView = memo(function DatabaseRowView({
+ database,
+ columns,
+ showSelection,
+ selected,
+ onToggleSelection,
+ onRowClick,
+}: DatabaseRowViewProps) {
+ return (
+ <TableRow
+ className={onRowClick ? "cursor-pointer" : undefined}
+ onClick={onRowClick ? (e) => onRowClick(database, e) : undefined}
+ >
+ {showSelection && (
+ <TableCell
+ className="overflow-hidden cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleSelection(database.name);
+ }}
+ >
+ <Checkbox
+ checked={selected}
+ onCheckedChange={() => onToggleSelection(database.name)}
+ onClick={(e) => e.stopPropagation()}
+ />
+ </TableCell>
+ )}
+ {columns.map((col) => (
+ <TableCell
+ key={col.key}
+ className={cn(
+ "overflow-hidden",
+ col.cellClassName,
+ col.onCellClick && "cursor-pointer"
+ )}
+ onClick={
+ col.onCellClick ? (e) => col.onCellClick!(database, e) : undefined
+ }
+ >
+ {col.render(database)}
+ </TableCell>
+ ))}
+ </TableRow>
+ );
+});
diff --git a/frontend/src/react/pages/project/ProjectDatabasesPage.tsx b/frontend/src/react/pages/project/ProjectDatabasesPage.tsx
index f11a255a75..feee4e0b32 100644
--- a/frontend/src/react/pages/project/ProjectDatabasesPage.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabasesPage.tsx
@@ -1,7 +1,7 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { Plus } from "lucide-react";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
AdvancedSearch,
@@ -227,6 +227,28 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
.map((name) => databaseStore.getDatabaseByName(name));
}, [selectedNames, databaseStore]);
+ // Stable references for downstream sheets. Without these the JSX would
+ // rebuild a fresh array + fresh object literal on every parent re-render
+ // (e.g. opening any drawer flips state on this page) — DataExportPrepSheet
+ // would then see a new `seed` prop reference each render and re-run its
+ // `seedKey = selectedDatabaseNames.join(",")` work (O(N) on every render).
+ const selectedDatabaseNames = useMemo(
+ () => selectedDatabases.map((db) => db.name),
+ [selectedDatabases]
+ );
+ const exportPrepSeed = useMemo(
+ () => ({ selectedDatabaseNames, step: 2 as const }),
+ [selectedDatabaseNames]
+ );
+
+ // Mirror `selectedDatabases` into a ref so the batch-operation handlers
+ // below can read the latest value without listing it as a dep. Otherwise
+ // every selection toggle re-creates the handler closures, which cascades
+ // down as fresh prop refs into `DatabaseBatchOperationsBar` and forces
+ // it to re-render (with N selected items, this compounds quickly).
+ const selectedDatabasesRef = useRef(selectedDatabases);
+ selectedDatabasesRef.current = selectedDatabases;
+
const refresh = useCallback(() => {
setRefreshToken((prev) => prev + 1);
setSelectedNames(new Set());
@@ -269,7 +291,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
await databaseStore.batchUpdateDatabases(
create(BatchUpdateDatabasesRequestSchema, {
parent: "-",
- requests: selectedDatabases.map((database, i) =>
+ requests: selectedDatabasesRef.current.map((database, i) =>
create(UpdateDatabaseRequestSchema, {
database: create(DatabaseSchema$, {
...database,
@@ -294,7 +316,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
});
}
},
- [selectedDatabases, databaseStore, refresh, t]
+ [databaseStore, refresh, t]
);
const handleEnvironmentUpdate = useCallback(
@@ -303,7 +325,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
await databaseStore.batchUpdateDatabases(
create(BatchUpdateDatabasesRequestSchema, {
parent: "-",
- requests: selectedDatabases.map((database) =>
+ requests: selectedDatabasesRef.current.map((database) =>
create(UpdateDatabaseRequestSchema, {
database: create(DatabaseSchema$, {
name: database.name,
@@ -328,7 +350,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
});
}
},
- [selectedDatabases, databaseStore, refresh, t]
+ [databaseStore, refresh, t]
);
const handleUnassign = useCallback(async () => {
@@ -337,7 +359,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
await databaseStore.batchUpdateDatabases(
create(BatchUpdateDatabasesRequestSchema, {
parent: "-",
- requests: selectedDatabases.map((database) =>
+ requests: selectedDatabasesRef.current.map((database) =>
create(UpdateDatabaseRequestSchema, {
database: create(DatabaseSchema$, {
name: database.name,
@@ -361,14 +383,11 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
title: t("common.failed"),
});
}
- }, [selectedDatabases, databaseStore, actuatorStore, refresh, t]);
+ }, [databaseStore, actuatorStore, refresh, t]);
const handleChangeDatabase = useCallback(() => {
- preCreateIssue(
- projectName,
- selectedDatabases.map((db) => db.name)
- );
- }, [projectName, selectedDatabases]);
+ preCreateIssue(projectName, selectedDatabaseNames);
+ }, [projectName, selectedDatabaseNames]);
const [showExportDrawer, setShowExportDrawer] = useState(false);
@@ -465,10 +484,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
open={showExportDrawer}
onClose={() => setShowExportDrawer(false)}
projectName={projectName}
- seed={{
- selectedDatabaseNames: selectedDatabases.map((db) => db.name),
- step: 2,
- }}
+ seed={exportPrepSeed}
/>
{/* Unassign confirmation dialog */}
diff --git a/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx b/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx
index 462f74dfc1..24561a20e0 100644
--- a/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx
+++ b/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx
@@ -259,7 +259,7 @@ export function ProjectIssueDashboardPage({
key={issue.name}
issue={issue}
selected={selectedNames.has(issue.name)}
- onToggleSelection={() => toggleSelection(issue.name)}
+ onToggleSelection={toggleSelection}
highlightText={searchParams.query}
/>
))
diff --git a/frontend/src/react/pages/settings/DatabasesPage.tsx b/frontend/src/react/pages/settings/DatabasesPage.tsx
index 07fe7d0770..85be13f673 100644
--- a/frontend/src/react/pages/settings/DatabasesPage.tsx
+++ b/frontend/src/react/pages/settings/DatabasesPage.tsx
@@ -1,7 +1,7 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { Plus } from "lucide-react";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
AdvancedSearch,
@@ -314,6 +314,14 @@ export function DatabasesPage() {
.map((name) => databaseStore.getDatabaseByName(name));
}, [selectedNames, databaseStore]);
+ // Mirror `selectedDatabases` into a ref so the batch-operation handlers
+ // below can read the latest value without listing it as a dep. Otherwise
+ // every selection toggle re-creates the handler closures, which cascades
+ // down as fresh prop refs into `DatabaseBatchOperationsBar` and forces
+ // it to re-render (with N selected items, this compounds quickly).
+ const selectedDatabasesRef = useRef(selectedDatabases);
+ selectedDatabasesRef.current = selectedDatabases;
+
const refresh = useCallback(() => {
setRefreshToken((prev) => prev + 1);
setSelectedNames(new Set());
@@ -356,7 +364,7 @@ export function DatabasesPage() {
await databaseStore.batchUpdateDatabases(
create(BatchUpdateDatabasesRequestSchema, {
parent: "-",
- requests: selectedDatabases.map((database, i) =>
+ requests: selectedDatabasesRef.current.map((database, i) =>
create(UpdateDatabaseRequestSchema, {
database: create(DatabaseSchema$, {
...database,
@@ -381,7 +389,7 @@ export function DatabasesPage() {
});
}
},
- [selectedDatabases, databaseStore, refresh, t]
+ [databaseStore, refresh, t]
);
const handleEnvironmentUpdate = useCallback(
@@ -390,7 +398,7 @@ export function DatabasesPage() {
await databaseStore.batchUpdateDatabases(
create(BatchUpdateDatabasesRequestSchema, {
parent: "-",
- requests: selectedDatabases.map((database) =>
+ requests: selectedDatabasesRef.current.map((database) =>
create(UpdateDatabaseRequestSchema, {
database: create(DatabaseSchema$, {
name: database.name,
@@ -415,7 +423,7 @@ export function DatabasesPage() {
});
}
},
- [selectedDatabases, databaseStore, refresh, t]
+ [databaseStore, refresh, t]
);
const handleTransferProject = useCallback(
@@ -424,7 +432,7 @@ export function DatabasesPage() {
await databaseStore.batchUpdateDatabases(
create(BatchUpdateDatabasesRequestSchema, {
parent: "-",
- requests: selectedDatabases.map((database) =>
+ requests: selectedDatabasesRef.current.map((database) =>
create(UpdateDatabaseRequestSchema, {
database: create(DatabaseSchema$, {
name: database.name,
@@ -449,7 +457,7 @@ export function DatabasesPage() {
});
}
},
- [selectedDatabases, databaseStore, refresh, t]
+ [databaseStore, refresh, t]
);
return (
diff --git a/frontend/src/react/pages/settings/InstanceDetailPage.tsx b/frontend/src/react/pages/settings/InstanceDetailPage.tsx
index 84ae38b8d2..69f4dadcca 100644
--- a/frontend/src/react/pages/settings/InstanceDetailPage.tsx
+++ b/frontend/src/react/pages/settings/InstanceDetailPage.tsx
@@ -1,6 +1,6 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
AdvancedSearch,
@@ -106,6 +106,14 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
.map((name) => databaseStore.getDatabaseByName(name));
}, [selectedNames, databaseStore]);
+ // Mirror `selectedDatabases` into a ref so the batch-operation handlers
+ // below can read the latest value without listing it as a dep. Otherwise
+ // every selection toggle re-creates the handler closures, which cascades
+ // down as fresh prop refs into `DatabaseBatchOperationsBar` and forces
+ // it to re-render (with N selected items, this compounds quickly).
+ const selectedDatabasesRef = useRef(selectedDatabases);
+ selectedDatabasesRef.current = selectedDatabases;
+
const refresh = useCallback(() => {
setRefreshToken((prev) => prev + 1);
setSelectedNames(new Set());
@@ -147,7 +155,7 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
await databaseStore.batchUpdateDatabases(
create(BatchUpdateDatabasesRequestSchema, {
parent: "-",
- requests: selectedDatabases.map((database, i) =>
+ requests: selectedDatabasesRef.current.map((database, i) =>
create(UpdateDatabaseRequestSchema, {
database: create(DatabaseSchema$, {
...database,
@@ -172,7 +180,7 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
});
}
},
- [selectedDatabases, databaseStore, refresh, t]
+ [databaseStore, refresh, t]
);
const handleEnvironmentUpdate = useCallback(
@@ -181,7 +189,7 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
await databaseStore.batchUpdateDatabases(
create(BatchUpdateDatabasesRequestSchema, {
parent: "-",
- requests: selectedDatabases.map((database) =>
+ requests: selectedDatabasesRef.current.map((database) =>
create(UpdateDatabaseRequestSchema, {
database: create(DatabaseSchema$, {
name: database.name,
@@ -206,7 +214,7 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
});
}
},
- [selectedDatabases, databaseStore, refresh, t]
+ [databaseStore, refresh, t]
);
const handleTransferProject = useCallback(
@@ -215,7 +223,7 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
await databaseStore.batchUpdateDatabases(
create(BatchUpdateDatabasesRequestSchema, {
parent: "-",
- requests: selectedDatabases.map((database) =>
+ requests: selectedDatabasesRef.current.map((database) =>
create(UpdateDatabaseRequestSchema, {
database: create(DatabaseSchema$, {
name: database.name,
@@ -240,7 +248,7 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
});
}
},
- [selectedDatabases, databaseStore, refresh, t]
+ [databaseStore, refresh, t]
);
// Trigger a Pinia-side fetch on mount. The parent `InstanceRouteShell`
// populates the React-side `useAppStore` cache, but this page reads
diff --git a/frontend/src/react/pages/workspace/MyIssuesPage.tsx b/frontend/src/react/pages/workspace/MyIssuesPage.tsx
index 2b0ddaa631..2cacccf507 100644
--- a/frontend/src/react/pages/workspace/MyIssuesPage.tsx
+++ b/frontend/src/react/pages/workspace/MyIssuesPage.tsx
@@ -204,7 +204,7 @@ export function MyIssuesPage() {
key={issue.name}
issue={issue}
selected={selectedNames.has(issue.name)}
- onToggleSelection={() => toggleSelection(issue.name)}
+ onToggleSelection={toggleSelection}
highlightText={searchParams.query}
showProject
/>