Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(react): unify selection bar across my-issues, projects, instances, databases (#20256)
boojack4fb370f5d0b0
diff --git a/docs/superpowers/plans/2026-05-08-selection-action-bar.md b/docs/superpowers/plans/2026-05-08-selection-action-bar.mdnew file mode 100644index 0000000000..63f9e61cf6--- /dev/null+++ b/docs/superpowers/plans/2026-05-08-selection-action-bar.md@@ -0,0 +1,1200 @@+# Unified SelectionActionBar Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Replace three near-identical batch-operation strips (`ProjectsPage`, `DatabaseBatchOperationsBar`, `InstancesPage`) with one shared `SelectionActionBar` — a floating bottom-center pill mounted into the overlay layer.++**Architecture:** New generic component at `frontend/src/react/components/SelectionActionBar.tsx` rendered via `createPortal` into `getLayerRoot("overlay")`, with declarative `actions[]` props plus a `children` slot for custom action nodes (e.g. `SyncDropdown`). The existing `DatabaseBatchOperationsBar` becomes a thin wrapper preserving its external API across its three callers (`DatabasesPage`, `InstanceDetailPage`, `ProjectDatabasesPage`).++**Tech Stack:** React 18 + Base UI + Tailwind CSS v4 + lucide-react + vitest + react-i18next.++> **Spec correction (worth noting):** The approved spec at `docs/superpowers/specs/2026-05-08-selection-action-bar-design.md` mentions `bg-control` for the pill surface. `--color-control` is actually a dark text color (`#52525b`), not a background. Existing primitives (`dialog.tsx`, `popover.tsx`) use `bg-background` for surfaces. This plan uses `bg-background` instead — same visual intent (white/dark surface), correct semantic token. Update the spec inline if you want consistency.++---++## File Structure++**Created files:**++- `frontend/src/react/components/SelectionActionBar.tsx` — the new shared component (the only place the floating-pill UI lives)+- `frontend/src/react/components/SelectionActionBar.test.tsx` — vitest unit tests++**Modified files:**++- `frontend/src/locales/en-US.json` — add two ARIA-label keys (`common.batch-actions`, `common.clear-selection`)+- `frontend/src/react/pages/settings/ProjectsPage.tsx` — delete local `BatchOperationsBar`, replace with `SelectionActionBar` usage+- `frontend/src/react/components/database/DatabaseBatchOperationsBar.tsx` — rewritten as a thin wrapper around `SelectionActionBar` (external API unchanged)+- `frontend/src/react/pages/settings/InstancesPage.tsx` — delete local `BatchOperationsBar`, replace with `SelectionActionBar` usage. `SyncDropdown` (lines 539–589) stays and is passed as `children`.++**Untouched (compile unchanged through the wrapper):**++- `frontend/src/react/pages/settings/DatabasesPage.tsx`+- `frontend/src/react/pages/settings/InstanceDetailPage.tsx`+- `frontend/src/react/pages/project/ProjectDatabasesPage.tsx`+- `frontend/src/react/components/database/index.tsx` (re-exports `DatabaseBatchOperationsBar`; signature unchanged)++---++## Task 1: Add i18n keys for ARIA labels++**Files:**++- Modify: `frontend/src/locales/en-US.json`+- Verify: every other locale file under `frontend/src/locales/*.json` (zh-CN.json, ja-JP.json, etc.) — `vue-i18n` falls back to en-US for missing keys, but adding placeholders avoids future drift; for this task, **only add to en-US.json**. Other locales are picked up by Crowdin sync downstream.++- [ ] **Step 1: Open `frontend/src/locales/en-US.json` and locate the `"common"` block**++Find the existing `common` object containing keys like `"archive"`, `"cancel"`, `"clear"`, etc. (around line 209+ in the current file).++- [ ] **Step 2: Add two new keys inside the `common` block, alphabetized**++Add `"batch-actions"` (just after `"batch": ...` if present, or near the `b*` cluster) and `"clear-selection"` (just after `"clear"`):++```json+"batch-actions": "Batch actions",+"clear-selection": "Clear selection",+```++Example diff:++```diff+ "cancel": "Cancel",++ "batch-actions": "Batch actions",+ "clear": "Clear",++ "clear-selection": "Clear selection",+ "create": "Create",+```++(Exact alphabetic position depends on existing keys — keep the file alphabetized as the existing entries are.)++- [ ] **Step 3: Verify JSON is valid**++Run: `node -e "JSON.parse(require('fs').readFileSync('frontend/src/locales/en-US.json','utf8'))"`++Expected: no output (success). If a `SyntaxError` is thrown, fix the trailing comma / quotation issue before continuing.++- [ ] **Step 4: Commit**++```bash+git add frontend/src/locales/en-US.json+git commit -m "i18n: add common.batch-actions and common.clear-selection keys"+```++---++## Task 2: Write the failing test for `SelectionActionBar`++**Files:**++- Create: `frontend/src/react/components/SelectionActionBar.test.tsx`++> Why this task exists alone: TDD. We write the test before any component code so we see it fail, then make it pass in Task 3.++- [ ] **Step 1: Create the test file with full content**++Path: `frontend/src/react/components/SelectionActionBar.test.tsx`++```tsx+import { Archive, Trash2 } from "lucide-react";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { SelectionActionBar } from "./SelectionActionBar";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++describe("SelectionActionBar", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(async () => {+ await act(async () => {+ root.unmount();+ });+ document.body.innerHTML = "";+ });++ test("renders nothing when count is 0", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={0}+ label="0 selected"+ onClear={() => {}}+ actions={[]}+ />+ );+ });+ // Bar is not in the overlay layer.+ expect(+ document.getElementById("bb-react-layer-overlay")?.textContent ?? ""+ ).not.toContain("0 selected");+ });++ test("renders label, clear button, and visible actions when count > 0", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={2}+ label="2 selected"+ onClear={() => {}}+ actions={[+ {+ key: "archive",+ label: "Archive",+ icon: Archive,+ onClick: () => {},+ },+ {+ key: "delete",+ label: "Delete",+ icon: Trash2,+ onClick: () => {},+ tone: "destructive",+ },+ ]}+ />+ );+ });+ const overlay = document.getElementById("bb-react-layer-overlay");+ expect(overlay?.textContent).toContain("2 selected");+ expect(overlay?.querySelector('[aria-label="Clear selection"]')).not.toBeNull();+ expect(overlay?.textContent).toContain("Archive");+ expect(overlay?.textContent).toContain("Delete");+ });++ test("omits hidden actions and disables disabled actions", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ onClear={() => {}}+ actions={[+ { key: "a", label: "AlphaAction", onClick: () => {} },+ { key: "b", label: "BetaAction", onClick: () => {}, hidden: true },+ { key: "c", label: "GammaAction", onClick: () => {}, disabled: true },+ ]}+ />+ );+ });+ const overlay = document.getElementById("bb-react-layer-overlay")!;+ expect(overlay.textContent).toContain("AlphaAction");+ expect(overlay.textContent).not.toContain("BetaAction");+ const gamma = Array.from(overlay.querySelectorAll("button")).find(+ (b) => b.textContent === "GammaAction"+ );+ expect(gamma).toBeDefined();+ expect(gamma?.hasAttribute("disabled")).toBe(true);+ });++ test("clicking an action invokes its onClick", async () => {+ const onClick = vi.fn();+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ onClear={() => {}}+ actions={[{ key: "a", label: "ActionLabel", onClick }]}+ />+ );+ });+ const overlay = document.getElementById("bb-react-layer-overlay")!;+ const btn = Array.from(overlay.querySelectorAll("button")).find(+ (b) => b.textContent === "ActionLabel"+ )!;+ await act(async () => {+ btn.click();+ });+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ test("clicking the clear button invokes onClear", async () => {+ const onClear = vi.fn();+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ onClear={onClear}+ actions={[]}+ />+ );+ });+ const overlay = document.getElementById("bb-react-layer-overlay")!;+ const clearBtn = overlay.querySelector<HTMLButtonElement>(+ '[aria-label="Clear selection"]'+ )!;+ await act(async () => {+ clearBtn.click();+ });+ expect(onClear).toHaveBeenCalledTimes(1);+ });++ test("Escape clears when count > 0 and not when count === 0", async () => {+ const onClear = vi.fn();++ // count > 0 → Escape clears.+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ onClear={onClear}+ actions={[]}+ />+ );+ });+ await act(async () => {+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));+ });+ expect(onClear).toHaveBeenCalledTimes(1);++ // count === 0 → Escape no-ops.+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={0}+ label="0 selected"+ onClear={onClear}+ actions={[]}+ />+ );+ });+ await act(async () => {+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));+ });+ expect(onClear).toHaveBeenCalledTimes(1); // unchanged+ });++ test("destructive tone applies the red-text override class", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ onClear={() => {}}+ actions={[+ {+ key: "del",+ label: "DestructiveAction",+ onClick: () => {},+ tone: "destructive",+ },+ ]}+ />+ );+ });+ const overlay = document.getElementById("bb-react-layer-overlay")!;+ const btn = Array.from(overlay.querySelectorAll("button")).find(+ (b) => b.textContent === "DestructiveAction"+ )!;+ expect(btn.className).toContain("text-error");+ });++ test("children render after declarative actions", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ onClear={() => {}}+ actions={[{ key: "a", label: "InlineAction", onClick: () => {} }]}+ >+ <span data-testid="custom-slot">CustomSlot</span>+ </SelectionActionBar>+ );+ });+ const overlay = document.getElementById("bb-react-layer-overlay")!;+ expect(overlay.querySelector('[data-testid="custom-slot"]')).not.toBeNull();+ expect(overlay.textContent).toContain("CustomSlot");+ });+});+```++> **Note on i18n in tests:** the test asserts hardcoded `"Clear selection"` for the clear button's aria-label. The test uses raw labels (no `t()`), so the component must accept the aria-label key from the consumer or render an English default in test environments. We solve this by having the component **call `t("common.clear-selection")` directly**; the project's vitest setup wires `react-i18next` to fall back to the literal key value or to `en-US` text. Verify by checking `frontend/src/react/test-utils/` for the test-side i18n setup; if the resolved string is the key itself (e.g. `"common.clear-selection"`), update this test's assertion accordingly. **Action when running:** if the test fails on aria-label string mismatch, change the assertion to match what `t()` returns in the test env (do not change the component).++- [ ] **Step 2: Run the test to verify it fails**++Run: `pnpm --dir frontend test SelectionActionBar`++Expected: FAIL with module-not-found / import error for `./SelectionActionBar` (the component does not exist yet).++- [ ] **Step 3: Commit**++```bash+git add frontend/src/react/components/SelectionActionBar.test.tsx+git commit -m "test: failing test for SelectionActionBar (component to follow)"+```++---++## Task 3: Implement `SelectionActionBar`++**Files:**++- Create: `frontend/src/react/components/SelectionActionBar.tsx`++- [ ] **Step 1: Create the component file with full content**++Path: `frontend/src/react/components/SelectionActionBar.tsx`++```tsx+import type { LucideIcon } from "lucide-react";+import { X } from "lucide-react";+import { useEffect, type ReactNode } from "react";+import { createPortal } from "react-dom";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { getLayerRoot } from "@/react/components/ui/layer";+import { Separator } from "@/react/components/ui/separator";+import { cn } from "@/react/lib/utils";++export interface SelectionAction {+ /** Stable key for React reconciliation. */+ key: string;+ label: string;+ icon?: LucideIcon;+ onClick: () => void;+ disabled?: boolean;+ /** When true, the action is omitted from the bar entirely. */+ hidden?: boolean;+ /**+ * Visual tone. "destructive" applies a red-text override on top of+ * the ghost variant. Default: "neutral".+ */+ tone?: "neutral" | "destructive";+}++export interface SelectionActionBarProps {+ /** Number of selected items. The bar renders only when count > 0. */+ count: number;+ /**+ * Pre-formatted label (e.g. "2 selected", "3 databases selected").+ * The call site owns i18n + pluralization.+ */+ label: string;+ /** Clears the selection. Also invoked on Escape. */+ onClear: () => void;+ /** Declarative actions. Rendered in order. Hidden actions are omitted. */+ actions?: SelectionAction[];+ /**+ * Custom action nodes rendered after `actions`. Used for actions that+ * require richer UI (e.g. InstancesPage's split-dropdown Sync).+ */+ children?: ReactNode;+}++const DESTRUCTIVE_TONE_CLASS =+ "text-error hover:bg-error/10 hover:text-error focus-visible:ring-error";++export function SelectionActionBar({+ count,+ label,+ onClear,+ actions,+ children,+}: SelectionActionBarProps) {+ const { t } = useTranslation();++ useEffect(() => {+ if (count <= 0) return;+ const handler = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ if (event.defaultPrevented) return;+ // Avoid hijacking dialog dismissal: bail if focus is inside a Base UI+ // dialog/popover surface.+ const active = document.activeElement;+ if (+ active instanceof HTMLElement &&+ active.closest("[data-base-ui-popup], [role='dialog']")+ ) {+ return;+ }+ onClear();+ };+ window.addEventListener("keydown", handler);+ return () => window.removeEventListener("keydown", handler);+ }, [count, onClear]);++ if (count <= 0) return null;++ const visibleActions = (actions ?? []).filter((a) => !a.hidden);++ return createPortal(+ <div+ role="toolbar"+ aria-label={t("common.batch-actions")}+ className={cn(+ "fixed bottom-6 left-1/2 -translate-x-1/2",+ "max-w-[90vw]",+ "flex items-center gap-x-1",+ "rounded-full bg-background border border-control-border shadow-lg",+ "px-2 py-1.5"+ )}+ >+ <Button+ variant="ghost"+ size="sm"+ aria-label={t("common.clear-selection")}+ onClick={onClear}+ >+ <X className="size-4" aria-hidden />+ </Button>++ <output+ aria-live="polite"+ className="text-sm font-medium text-control whitespace-nowrap px-1"+ >+ {label}+ </output>++ <Separator orientation="vertical" className="h-5 mx-1" />++ <div className="flex flex-wrap items-center gap-x-1 gap-y-1">+ {visibleActions.map((action) => {+ const Icon = action.icon;+ return (+ <Button+ key={action.key}+ variant="ghost"+ size="sm"+ disabled={action.disabled}+ onClick={action.onClick}+ className={cn(+ action.tone === "destructive" && DESTRUCTIVE_TONE_CLASS+ )}+ >+ {Icon && <Icon className="size-4" aria-hidden />}+ {action.label}+ </Button>+ );+ })}+ {children}+ </div>+ </div>,+ getLayerRoot("overlay")+ );+}+```++- [ ] **Step 2: Run the test to verify it passes**++Run: `pnpm --dir frontend test SelectionActionBar`++Expected: all tests in `SelectionActionBar.test.tsx` PASS.++If the aria-label assertion fails because `t()` returned the literal key (`"common.clear-selection"`) instead of the English string, update the assertion in `SelectionActionBar.test.tsx` to match what `t()` actually returns in the test env — do not change the component.++- [ ] **Step 3: Run the layering scanner**++Run: `node frontend/scripts/check-react-layering.mjs`++Expected: PASS. The component uses `getLayerRoot("overlay")` (no body portal) and has no raw `z-index` in its `className`.++- [ ] **Step 4: Type-check**++Run: `pnpm --dir frontend type-check`++Expected: no new errors. (If pre-existing errors are reported in unrelated files, ignore those — but ensure no errors point at `SelectionActionBar.tsx` or `SelectionActionBar.test.tsx`.)++- [ ] **Step 5: Lint and format**++Run: `pnpm --dir frontend fix`++Expected: no errors; the formatter may rewrite whitespace/import order in the new files.++- [ ] **Step 6: Commit**++```bash+git add frontend/src/react/components/SelectionActionBar.tsx+git add -u frontend/src/react/components/SelectionActionBar.test.tsx+git commit -m "feat(react): add SelectionActionBar (floating selection toolbar)"+```++---++## Task 4: Migrate `ProjectsPage` to `SelectionActionBar`++**Files:**++- Modify: `frontend/src/react/pages/settings/ProjectsPage.tsx` (delete local `BatchOperationsBar` at lines 116–319; replace usage at line 729; add new actions array)++- [ ] **Step 1: Delete the local `BatchOperationsBar` function**++Remove the entire block from line 116 (the `// ============================================================` divider that precedes `BatchOperationsBar`) through line 319 (closing `}` of `BatchOperationsBar`). **Keep** the `ConfirmDialog` and `ProjectListPreview` functions — they're still used.++After deletion, reorganize the remaining helpers so the file structure is:++1. `projectIssuesRoute` (top)+2. `ConfirmDialog`+3. `ProjectListPreview`+4. `ProjectActionDropdown`+5. `ProjectsPage` (main)++Move `ConfirmDialog` and `ProjectListPreview` (and their dividers) to sit before `ProjectActionDropdown` if they're not already. The three confirm-dialog usages now live inside `ProjectsPage` itself (next steps).++- [ ] **Step 2: Add `SelectionActionBar` import and lift confirm-dialog state into `ProjectsPage`**++In `ProjectsPage.tsx`, add to the imports:++```tsx+import {+ SelectionActionBar,+ type SelectionAction,+} from "@/react/components/SelectionActionBar";+```++Inside `ProjectsPage`, just below the existing `selectedNames` / `selectedProjectList` / `handleBatchOperation` block (around line 665+), add the three confirm-dialog state hooks **and** the three batch handlers (move them from the deleted `BatchOperationsBar`):++```tsx+const [showArchiveConfirm, setShowArchiveConfirm] = useState(false);+const [showRestoreConfirm, setShowRestoreConfirm] = useState(false);+const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);++const hasActiveProjects = selectedProjectList.some(+ (p) => p.state === State.ACTIVE+);+const hasArchivedProjects = selectedProjectList.some(+ (p) => p.state === State.DELETED+);++const handleBatchArchive = useCallback(async () => {+ try {+ const activeProjects = selectedProjectList.filter(+ (p) => p.state === State.ACTIVE+ );+ await projectStore.batchDeleteProjects(activeProjects.map((p) => p.name));+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.batch.archive.success", {+ count: activeProjects.length,+ }),+ });+ setShowArchiveConfirm(false);+ handleBatchOperation();+ } catch (error: unknown) {+ const err = error as { message?: string };+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("project.batch.archive.error"),+ description: err.message,+ });+ }+}, [selectedProjectList, projectStore, t, handleBatchOperation]);++const handleBatchRestore = useCallback(async () => {+ try {+ const archivedProjects = selectedProjectList.filter(+ (p) => p.state === State.DELETED+ );+ await Promise.all(+ archivedProjects.map((project) => projectStore.restoreProject(project))+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.restored"),+ });+ setShowRestoreConfirm(false);+ handleBatchOperation();+ } catch (error: unknown) {+ const err = error as { message?: string };+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.restore"),+ description: err.message,+ });+ }+}, [selectedProjectList, projectStore, t, handleBatchOperation]);++const handleBatchDelete = useCallback(async () => {+ try {+ await projectStore.batchPurgeProjects(+ selectedProjectList.map((p) => p.name)+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.batch.delete.success", {+ count: selectedProjectList.length,+ }),+ });+ setShowDeleteConfirm(false);+ handleBatchOperation();+ } catch (error: unknown) {+ const err = error as { message?: string };+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("project.batch.delete.error"),+ description: err.message,+ });+ }+}, [selectedProjectList, projectStore, t, handleBatchOperation]);++const batchActions: SelectionAction[] = [+ {+ key: "archive",+ label: t("common.archive"),+ icon: Archive,+ onClick: () => setShowArchiveConfirm(true),+ hidden: !hasActiveProjects,+ },+ {+ key: "restore",+ label: t("common.restore"),+ onClick: () => setShowRestoreConfirm(true),+ hidden: !hasArchivedProjects,+ },+ {+ key: "delete",+ label: t("common.delete"),+ icon: Trash2,+ onClick: () => setShowDeleteConfirm(true),+ tone: "destructive",+ },+];+```++- [ ] **Step 3: Replace the old bar render and add the three confirm dialogs**++In the JSX, replace this block (currently around line 727–733):++```tsx+{canDelete && (+ <BatchOperationsBar+ selectedProjects={selectedProjectList}+ onUpdate={handleBatchOperation}+ />+)}+```++with:++```tsx+{canDelete && (+ <SelectionActionBar+ count={selectedProjectList.length}+ label={t("project.batch.selected", { count: selectedProjectList.length })}+ onClear={() => setSelectedNames(new Set())}+ actions={batchActions}+ />+)}++<ConfirmDialog+ open={showArchiveConfirm}+ variant="warning"+ title={t("project.batch.archive.title", {+ count: selectedProjectList.length,+ })}+ description={t("project.batch.archive.description")}+ okText={t("common.archive")}+ onOk={handleBatchArchive}+ onCancel={() => setShowArchiveConfirm(false)}+>+ <ProjectListPreview+ projects={selectedProjectList}+ iconColor="text-success"+ />+</ConfirmDialog>++<ConfirmDialog+ open={showRestoreConfirm}+ variant="warning"+ title={t("common.restore")}+ description={t("common.restore")}+ okText={t("common.restore")}+ onOk={handleBatchRestore}+ onCancel={() => setShowRestoreConfirm(false)}+>+ <ProjectListPreview+ projects={selectedProjectList}+ iconColor="text-success"+ />+</ConfirmDialog>++<ConfirmDialog+ open={showDeleteConfirm}+ variant="error"+ title={t("project.batch.delete.title", {+ count: selectedProjectList.length,+ })}+ description={t("project.batch.delete.description")}+ okText={t("common.delete")}+ onOk={handleBatchDelete}+ onCancel={() => setShowDeleteConfirm(false)}+>+ <div className="flex flex-col gap-y-3">+ <ProjectListPreview+ projects={selectedProjectList}+ iconColor="text-error"+ />+ <div className="rounded-sm border border-error bg-error/5 p-3">+ <p className="text-sm font-medium text-error">+ {t("common.cannot-undo-this-action")}+ </p>+ <p className="text-sm text-error/80 mt-1">+ {t("project.batch.delete.warning")}+ </p>+ </div>+ </div>+</ConfirmDialog>+```++- [ ] **Step 4: Type-check**++Run: `pnpm --dir frontend type-check`++Expected: no new errors in `ProjectsPage.tsx`. If unused-import errors point at the deleted `BatchOperationsBar` artifacts (e.g. icons no longer referenced inside the deleted block), remove them. The page still uses `Archive`, `Trash2`, `EllipsisVertical`, `Plus`, `Check` — so verify each import is still needed.++- [ ] **Step 5: Lint, format, run tests**++Run: `pnpm --dir frontend fix && pnpm --dir frontend test ProjectsPage`++Expected: no lint errors. If a `ProjectsPage` test exists, it passes; if not, no test failure introduced.++- [ ] **Step 6: Manual smoke (optional but recommended)**++Run the dev server (`pnpm --dir frontend dev`) and on the Projects page, select 1+ projects → confirm:+- Floating pill appears at bottom-center, not as a top strip.+- Pill shows count + Archive (if any active selected) + Delete; Delete text is red.+- Click ✕ → selection clears.+- Press Escape → selection clears.+- Click Archive → existing `ConfirmDialog` opens with the project list preview.++- [ ] **Step 7: Commit**++```bash+git add -u frontend/src/react/pages/settings/ProjectsPage.tsx+git commit -m "refactor(react): migrate ProjectsPage batch bar to SelectionActionBar"+```++---++## Task 5: Convert `DatabaseBatchOperationsBar` to a thin wrapper++**Files:**++- Modify: `frontend/src/react/components/database/DatabaseBatchOperationsBar.tsx` (full rewrite — preserve external API, body becomes a `SelectionActionBar` invocation)+- Untouched (compile unchanged): `DatabasesPage.tsx`, `InstanceDetailPage.tsx`, `ProjectDatabasesPage.tsx`++- [ ] **Step 1: Replace the file body with the thin wrapper**++Path: `frontend/src/react/components/database/DatabaseBatchOperationsBar.tsx`++Full new content:++```tsx+import {+ ArrowRightLeft,+ Download,+ Pencil,+ RefreshCw,+ SquareStack,+ Tag,+ Unlink,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import {+ SelectionActionBar,+ type SelectionAction,+} from "@/react/components/SelectionActionBar";+import type { Permission } from "@/types";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import {+ hasProjectPermissionV2,+ hasWorkspacePermissionV2,+ PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE,+ PERMISSIONS_FOR_DATABASE_EXPORT_ISSUE,+} from "@/utils";++export interface DatabaseBatchOperationsBarProps {+ databases: Database[];+ /** When provided, permission checks use project-level IAM. */+ project?: Project;+ onSyncSchema: () => void;+ onEditLabels: () => void;+ onEditEnvironment: () => void;+ // Global context: transfer to another project+ onTransferProject?: () => void;+ // Project context: unassign from current project+ onUnassign?: () => void;+ // Project context: change database schema+ onChangeDatabase?: () => void;+ // Project context: export data+ onExportData?: () => void;+ /** Optional: clears the upstream selection. If omitted, the bar still+ * renders but the ✕/Escape clear is a no-op for the consumer. */+ onClearSelection?: () => void;+}++export function DatabaseBatchOperationsBar({+ databases,+ project,+ onSyncSchema,+ onEditLabels,+ onEditEnvironment,+ onTransferProject,+ onUnassign,+ onChangeDatabase,+ onExportData,+ onClearSelection,+}: DatabaseBatchOperationsBarProps) {+ const { t } = useTranslation();++ const hasPermission = (permission: Permission) =>+ project+ ? hasProjectPermissionV2(project, permission)+ : hasWorkspacePermissionV2(permission);++ const canSync = hasPermission("bb.databases.sync");+ const canUpdate = hasPermission("bb.databases.update");+ const canGetEnvironment = hasPermission("bb.settings.getEnvironment");+ const canChangeDatabase =+ PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE.every(hasPermission);+ const canExportData =+ PERMISSIONS_FOR_DATABASE_EXPORT_ISSUE.every(hasPermission);++ const actions: SelectionAction[] = [+ {+ key: "change-database",+ label: t("database.change-database"),+ icon: Pencil,+ onClick: () => onChangeDatabase?.(),+ disabled: !canChangeDatabase,+ hidden: !onChangeDatabase,+ },+ {+ key: "export-data",+ label: t("custom-approval.risk-rule.risk.namespace.data_export"),+ icon: Download,+ onClick: () => onExportData?.(),+ disabled: !canExportData,+ hidden: !onExportData,+ },+ {+ key: "sync-schema",+ label: t("database.sync-schema-button"),+ icon: RefreshCw,+ onClick: onSyncSchema,+ disabled: !canSync,+ },+ {+ key: "edit-labels",+ label: t("database.edit-labels"),+ icon: Tag,+ onClick: onEditLabels,+ disabled: !canUpdate,+ },+ {+ key: "edit-environment",+ label: t("database.edit-environment"),+ icon: SquareStack,+ onClick: onEditEnvironment,+ disabled: !canUpdate || !canGetEnvironment,+ },+ {+ key: "transfer-project",+ label: t("database.transfer-project"),+ icon: ArrowRightLeft,+ onClick: () => onTransferProject?.(),+ disabled: !canUpdate,+ hidden: !onTransferProject,+ },+ {+ key: "unassign",+ label: t("database.unassign"),+ icon: Unlink,+ onClick: () => onUnassign?.(),+ disabled: !canUpdate,+ hidden: !onUnassign,+ },+ ];++ return (+ <SelectionActionBar+ count={databases.length}+ label={t("database.selected-n-databases", { n: databases.length })}+ onClear={() => onClearSelection?.()}+ actions={actions}+ />+ );+}+```++> Note: `onClearSelection` is added as an **optional** new prop. The three existing call sites (`DatabasesPage`, `InstanceDetailPage`, `ProjectDatabasesPage`) compile unchanged because they don't pass it. We thread it through in Task 7 so ✕/Escape actually clear the upstream selection. Until then the clear button is a visible no-op.++- [ ] **Step 2: Type-check**++Run: `pnpm --dir frontend type-check`++Expected: no new errors. Both removed-import warnings (e.g. `Button`) and any external-call-site signatures pass cleanly.++- [ ] **Step 3: Lint and format**++Run: `pnpm --dir frontend fix`++Expected: clean.++- [ ] **Step 4: Commit**++```bash+git add -u frontend/src/react/components/database/DatabaseBatchOperationsBar.tsx+git commit -m "refactor(react): rebuild DatabaseBatchOperationsBar on SelectionActionBar"+```++---++## Task 6: Migrate `InstancesPage` batch bar++**Files:**++- Modify: `frontend/src/react/pages/settings/InstancesPage.tsx` (delete local `BatchOperationsBar` at lines 591–644; replace usage at line 1273; keep `SyncDropdown` lines 539–589)++- [ ] **Step 1: Delete the local `BatchOperationsBar` function**++Remove the function body for `BatchOperationsBar` (lines 591–644). **Keep** `SyncDropdown` (lines 539–589) — it's reused.++- [ ] **Step 2: Add the import**++In the imports block, add:++```tsx+import {+ SelectionActionBar,+ type SelectionAction,+} from "@/react/components/SelectionActionBar";+```++- [ ] **Step 3: Replace the bar usage**++Find the JSX usage of `BatchOperationsBar` (around line 1273). It looks like:++```tsx+<BatchOperationsBar+ selectedInstances={selectedInstanceList}+ syncing={syncing}+ onSync={handleBatchSync}+ onEditEnvironment={() => setShowEditEnvSheet(true)}+ onAssignLicense={() => setShowAssignLicenseSheet(true)}+ showAssignLicense={...}+/>+```++(Confirm exact prop names from the file — they may differ slightly.)++Replace with the inline `SelectionActionBar` call:++```tsx+{(() => {+ const canSync = hasWorkspacePermissionV2("bb.instances.sync");+ const canUpdate = hasWorkspacePermissionV2("bb.instances.update");+ const actions: SelectionAction[] = [+ {+ key: "edit-env",+ label: t("database.edit-environment"),+ icon: SquareStack,+ onClick: () => setShowEditEnvSheet(true),+ disabled: !canUpdate,+ },+ {+ key: "assign-license",+ label: t("subscription.instance-assignment.assign-license"),+ icon: GraduationCap,+ onClick: () => setShowAssignLicenseSheet(true),+ disabled: !canUpdate,+ hidden: !showAssignLicenseAction, // rename from old `showAssignLicense` prop+ },+ ];+ return (+ <SelectionActionBar+ count={selectedInstanceList.length}+ label={t("instance.selected-n-instances", {+ n: selectedInstanceList.length,+ })}+ onClear={() => setSelectedInstanceNames(new Set())}+ actions={actions}+ >+ <SyncDropdown+ disabled={!canSync || syncing}+ onSync={handleBatchSync}+ />+ </SelectionActionBar>+ );+})()}+```++> The exact local variable names (`selectedInstanceList`, `setSelectedInstanceNames`, `syncing`, `handleBatchSync`, `showAssignLicenseAction`, `setShowEditEnvSheet`, `setShowAssignLicenseSheet`) **must be confirmed by reading the file**. The old `BatchOperationsBar` already references these — copy whatever names it uses. Do not introduce new state variables.++- [ ] **Step 4: Sanity-check the i18n variable name still matches**++Run: `grep -n "selected-n-instances\|selected-n-databases" frontend/src/locales/en-US.json`++Expected (per current code): both keys declare the variable as `n` (e.g. `"{n} instance selected | {n} instances selected"`). The plan's calls in Step 3 (above) and in Task 5 already use `{ n: ... }`. If a future change has renamed the variable, mirror it in both call sites; mismatched names render the literal `{n}` in the UI.++- [ ] **Step 5: Type-check**++Run: `pnpm --dir frontend type-check`++Expected: no new errors. Remove now-unused imports (e.g. the file may have `useClickOutside` only used by the deleted bar — check and prune).++- [ ] **Step 6: Lint, format, run tests**++Run: `pnpm --dir frontend fix && pnpm --dir frontend test InstancesPage`++Expected: clean.++- [ ] **Step 7: Manual smoke**++`pnpm --dir frontend dev` → Instances page → select instances → confirm:+- Floating pill at bottom; SyncDropdown is the leftmost action node, opens its menu correctly.+- Edit Environment / Assign License (when applicable) appear.+- ✕ and Escape clear the selection.++- [ ] **Step 8: Commit**++```bash+git add -u frontend/src/react/pages/settings/InstancesPage.tsx+git commit -m "refactor(react): migrate InstancesPage batch bar to SelectionActionBar"+```++---++## Task 7: Wire `onClearSelection` through the database batch-bar callers++**Files:**++- Modify: `frontend/src/react/pages/settings/DatabasesPage.tsx` (line 479 area)+- Modify: `frontend/src/react/pages/settings/InstanceDetailPage.tsx` (line 427 area)+- Modify: `frontend/src/react/pages/project/ProjectDatabasesPage.tsx` (line 412 area)++> Why: in Task 5 we added `onClearSelection?: () => void`. Without it, the ✕ / Escape on the Database bar clears nothing. We pass the existing selection-clearing setter through.++- [ ] **Step 1: For each of the three pages, find the existing selection state**++Each page already maintains a selection state (whatever Set/array it passes to `selectedDatabases` or filters into `databases`). Locate the setter that clears it.++- [ ] **Step 2: Pass `onClearSelection` to `DatabaseBatchOperationsBar`**++For each call site, add the prop:++```tsx+<DatabaseBatchOperationsBar+ databases={selectedDatabaseList}+ /* ...existing props... */+ onClearSelection={() => setSelectedDatabaseNames(new Set())}+/>+```++(Use whatever the existing setter is — `setSelectedDatabaseNames`, `setSelectedDatabases`, etc.)++- [ ] **Step 3: Type-check, lint, manual smoke**++```+pnpm --dir frontend type-check+pnpm --dir frontend fix+```++Smoke: Databases / Instance detail / Project databases pages — select rows, click ✕ on the floating pill, confirm rows deselect.++- [ ] **Step 4: Commit**++```bash+git add -u frontend/src/react/pages/settings/DatabasesPage.tsx+git add -u frontend/src/react/pages/settings/InstanceDetailPage.tsx+git add -u frontend/src/react/pages/project/ProjectDatabasesPage.tsx+git commit -m "refactor(react): wire onClearSelection in DatabaseBatchOperationsBar callers"+```++---++## Task 8: Cleanup verification & full gates++- [ ] **Step 1: Confirm no `bg-blue-100` strip pattern remains in batch bars**++Run:++```bash+grep -rn "bg-blue-100" frontend/src/react/pages frontend/src/react/components/database+```++Expected: zero matches. If any remain in unrelated files (e.g. an info banner unrelated to selection), leave them.++- [ ] **Step 2: Confirm no leftover local `BatchOperationsBar` definitions**++Run:++```bash+grep -rn "function BatchOperationsBar" frontend/src/react+```++Expected: zero matches. (The shared component is named `SelectionActionBar`; the wrapper component is `DatabaseBatchOperationsBar`.)++- [ ] **Step 3: Confirm no `useClickOutside` orphans**++If the old InstancesPage `BatchOperationsBar` was the only consumer of `useClickOutside` in that file, the import should now be unused. Run:++```bash+grep -n "useClickOutside" frontend/src/react/pages/settings/InstancesPage.tsx+```++If it appears only in the import, delete the import line.++- [ ] **Step 4: Run the full frontend gate suite**++```bash+pnpm --dir frontend fix+pnpm --dir frontend check+pnpm --dir frontend type-check+pnpm --dir frontend test+node frontend/scripts/check-react-layering.mjs+```++Expected:+- `fix`: no errors; may rewrite formatting.+- `check`: passes (CI-equivalent validation, includes the layering scanner).+- `type-check`: passes.+- `test`: passes; `SelectionActionBar.test.tsx` is in the run.+- Layering scanner: passes — no raw `z-index`, no `document.body` portals, no forbidden global overlay classes.++- [ ] **Step 5: Final commit (only if any tooling-driven fixes were applied)**++If `fix` produced changes:++```bash+git add -u+git commit -m "chore(react): apply formatter / lint fixups after SelectionActionBar migration"+```++If no changes, skip this step.++- [ ] **Step 6: Push & open PR (optional — at user's discretion)**++This plan does not auto-push. The branch is ready for `gh pr create`. Per `docs/pre-pr-checklist.md`, walk through the breaking-change review and SonarCloud properties before creating the PR.++---++## Summary of commits produced++1. `i18n: add common.batch-actions and common.clear-selection keys`+2. `test: failing test for SelectionActionBar (component to follow)`+3. `feat(react): add SelectionActionBar (floating selection toolbar)`+4. `refactor(react): migrate ProjectsPage batch bar to SelectionActionBar`+5. `refactor(react): rebuild DatabaseBatchOperationsBar on SelectionActionBar`+6. `refactor(react): migrate InstancesPage batch bar to SelectionActionBar`+7. `refactor(react): wire onClearSelection in DatabaseBatchOperationsBar callers`+8. (optional) `chore(react): apply formatter / lint fixups after SelectionActionBar migration`diff --git a/docs/superpowers/specs/2026-05-08-selection-action-bar-design.md b/docs/superpowers/specs/2026-05-08-selection-action-bar-design.mdnew file mode 100644index 0000000000..59c4322bbc--- /dev/null+++ b/docs/superpowers/specs/2026-05-08-selection-action-bar-design.md@@ -0,0 +1,338 @@+# Unified Selection Action Bar — Design++**Date:** 2026-05-08+**Scope:** Frontend, React (`frontend/src/react/`)+**Owner:** [email protected]++## Problem++Three near-identical batch-operation bars exist in the React codebase:++1. `BatchOperationsBar` in `frontend/src/react/pages/settings/ProjectsPage.tsx` —+ Archive / Restore / Delete on selected projects.+2. `DatabaseBatchOperationsBar` in+ `frontend/src/react/components/database/DatabaseBatchOperationsBar.tsx` — up+ to seven actions (Change DB, Export, Sync Schema, Edit Labels, Edit+ Environment, Transfer, Unassign), used on `DatabasesPage`,+ `InstanceDetailPage`, and `ProjectDatabasesPage`.+3. `BatchOperationsBar` in `frontend/src/react/pages/settings/InstancesPage.tsx`+ — Sync (with split dropdown: Sync All / Sync New), Edit Environment, Assign+ License.++All three render the same pattern: a full-width strip with `bg-blue-100`, a+plain count label, and a row of `variant="ghost"` buttons inserted between the+page header and the table.++Concrete issues:++- `bg-blue-100` is a **raw color**. `frontend/AGENTS.md` requires semantic+ tokens (`bg-accent`, `bg-control`, etc.) and forbids raw `bg-blue-*` /+ `text-gray-*`.+- No visual hierarchy: destructive actions (Delete, Archive) sit alongside+ neutral edits (Edit Labels, Sync Schema) as identical ghost buttons. Users+ cannot tell at a glance which action is dangerous.+- The strip occupies vertical space above the table, pushing rows down. With 7+ buttons (Database case) the strip can wrap onto a second line, doubling the+ intrusion.+- No "clear selection" affordance — the only way to dismiss the bar is to+ uncheck rows manually.+- No `Escape`-to-clear keyboard shortcut.+- The selection count is a plain `<span>`, no emphasis or noun styling.+- Three independent implementations means style fixes must be made three+ times, and the InstancesPage variant currently uses an ad-hoc+ `useClickOutside` dropdown instead of a shared `DropdownMenu`.++## Goals++- One shared `SelectionActionBar` component used by all three call sites.+- Floating bottom-center pill (Linear/Notion/Gmail style), not a full-width+ strip — keeps the table layout stable and is visually lighter.+- Uses semantic tokens only; passes the React layering scanner+ (`frontend/scripts/check-react-layering.mjs`).+- Visual hierarchy: ghost neutral actions, red-text destructive action.+- Built-in clear affordance (✕ button + `Escape` keypress).+- Accepts both declarative `actions[]` (covers Projects + Database cases) and+ custom node `children` (covers InstancesPage's `SyncDropdown`).+- All four database-bar call sites recompile unchanged+ (`DatabaseBatchOperationsBar` becomes a thin wrapper that builds the actions+ array).++## Non-goals++- Replacing the existing `ConfirmDialog` / `ProjectListPreview` flow on+ ProjectsPage. Those continue to handle final confirmation; the bar only+ triggers them.+- Introducing an overflow ("⋯ More") menu. v1 uses `flex-wrap` (Tier A) for+ many-action cases. Overflow can be added later if Database page feels+ crowded.+- Changing per-permission / per-state visibility logic. Each call site+ continues to compute `hidden` / `disabled` flags and pass them in.+- Building a generic toolbar component. `SelectionActionBar` is specifically+ for "N items selected → operate on them" toolbars, not for general page+ toolbars.++## Design++### Placement++`SelectionActionBar` mounts via React portal into `getLayerRoot("overlay")`+(per `frontend/AGENTS.md` overlay policy — never `document.body`). The bar is+absolutely positioned `bottom-6 left-1/2 -translate-x-1/2`, with+`max-w-[90vw]`. No raw `z-index` — relies on the overlay layer's stacking.++The bar is rendered conditionally on `count > 0`. Mount/unmount is animated+via Base UI's transition primitives (or a small CSS transition on+`data-state`): slide-up + fade-in on appear (~150ms), reverse on dismiss.++### Visual++- Pill: `rounded-full bg-control border border-control-border shadow-lg+ px-2 py-1.5 flex items-center gap-x-1`.+- `bg-control` is theme-aware (light: white-ish, dark: dark surface). Compare+ to current `bg-blue-100` which has no dark-mode counterpart.++### Internal layout (left → right)++```+[ ✕ ] N selected │ Edit Sync Transfer 🗑 Delete+```++1. **Clear button** — icon-only ghost `Button` with an `X` icon, `size="sm"`,+ `aria-label={t("common.clear-selection")}`. Calls `onClear`.+2. **Count label** — `<span>` with `text-sm font-medium text-control`. The+ noun is rendered via `t()` at the call site (`"2 selected"` /+ `"3 databases selected"`).+3. **Vertical separator** — `<Separator orientation="vertical"+ className="h-5 mx-1" />`. Single divider only between count and the action+ group.+4. **Action buttons** — each `variant="ghost" size="sm"` with optional+ `lucide-react` icon + label. No vertical divider between actions (per+ approved design).+5. **Destructive action** — same `variant="ghost" size="sm"` but with a tone+ override applied via `cn()`:+ `"text-error hover:bg-error/10 hover:text-error focus-visible:ring-error"`.+ Per design choice "all ghost, only Delete is red", we do not use the solid+ `variant="destructive"` here — that would clash with the pill's neutral+ surface.++Many-action layout (Tier A): the action group uses `flex flex-wrap+items-center gap-x-1 gap-y-1`. On wide viewports it stays one line; on narrow+viewports the buttons wrap inside the pill. The pill itself does not wrap+(count + separator + actions are siblings of a top-level `flex items-center`).++### Component API++```tsx+// frontend/src/react/components/SelectionActionBar.tsx++import type { LucideIcon } from "lucide-react";+import type { ReactNode } from "react";++export interface SelectionAction {+ /** Stable key for React reconciliation. */+ key: string;+ label: string;+ icon?: LucideIcon;+ onClick: () => void;+ disabled?: boolean;+ /** When true, the action is omitted from the bar entirely. */+ hidden?: boolean;+ /**+ * Visual tone. "destructive" applies the red-text override.+ * Default: "neutral".+ */+ tone?: "neutral" | "destructive";+}++export interface SelectionActionBarProps {+ /** Number of selected items. The bar renders only when count > 0. */+ count: number;+ /**+ * Pre-formatted label (e.g. "2 selected", "3 databases selected").+ * The call site owns i18n + pluralization.+ */+ label: string;+ /** Clears the selection. Also invoked on Escape. */+ onClear: () => void;+ /** Declarative actions. Rendered in order. */+ actions?: SelectionAction[];+ /**+ * Custom action nodes rendered after `actions`. Used for actions that+ * require richer UI (e.g. InstancesPage's split-dropdown Sync).+ */+ children?: ReactNode;+}++export function SelectionActionBar(props: SelectionActionBarProps): JSX.Element | null;+```++### Keyboard++While `count > 0`, attach a window-level `keydown` listener for `Escape` →+calls `onClear`. Removed when `count === 0` or on unmount. Listener is+attached with `{ capture: false }` and bails out if `event.defaultPrevented`+or if the active element is inside a modal — to avoid hijacking dialog+dismissal.++### Accessibility++- The pill has `role="toolbar"` and `aria-label={t("common.batch-actions")}`.+- The count label is inside an `<output aria-live="polite">` so screen readers+ announce changes (e.g. "3 selected" → "5 selected").+- Clear button has explicit `aria-label`.+- Action icons are `aria-hidden`; accessible names come from each action's+ `label`.+- Focus management: when the bar appears, focus is **not** auto-stolen (the+ user is mid-table-interaction). Tab order naturally reaches the bar after+ the table.++### Layering++Per `frontend/AGENTS.md`:++- Mount target: `getLayerRoot("overlay")`. Never `document.body`.+- No raw `z-index` in the component or its consumers.+- No agent / critical layer use — this is a normal app overlay.+- After implementation: run `pnpm --dir frontend check` (which includes+ `node frontend/scripts/check-react-layering.mjs`).++## Migration++### 1. ProjectsPage++- Delete the local `BatchOperationsBar` function (ProjectsPage.tsx:120–319).+- Build the actions array inline in `ProjectsPage`:++```tsx+const batchActions: SelectionAction[] = [+ {+ key: "archive",+ label: t("common.archive"),+ icon: Archive,+ onClick: () => setShowArchiveConfirm(true),+ hidden: !hasActiveProjects,+ },+ {+ key: "restore",+ label: t("common.restore"),+ onClick: () => setShowRestoreConfirm(true),+ hidden: !hasArchivedProjects,+ },+ {+ key: "delete",+ label: t("common.delete"),+ icon: Trash2,+ onClick: () => setShowDeleteConfirm(true),+ tone: "destructive",+ },+];+```++- Render:++```tsx+{canDelete && (+ <SelectionActionBar+ count={selectedProjectList.length}+ label={t("project.batch.selected", { count: selectedProjectList.length })}+ onClear={() => setSelectedNames(new Set())}+ actions={batchActions}+ />+)}+```++- Keep `ConfirmDialog`, `ProjectListPreview`, and the three `handleBatch*`+ callbacks unchanged. State (`showArchiveConfirm` etc.) stays at the page+ level.++### 2. DatabaseBatchOperationsBar++- The file becomes a thin wrapper that preserves the existing external API+ (`databases`, `project?`, `onSyncSchema`, `onEditLabels`, `onEditEnvironment`,+ `onTransferProject?`, `onUnassign?`, `onChangeDatabase?`, `onExportData?`).+- Internally, it builds an `actions[]` array from the props and renders+ `SelectionActionBar`. All four call sites compile unchanged.+- Permission checks (`hasPermission`) move from rendering branches into the+ `disabled` field of each action.++### 3. InstancesPage++- Delete the local `BatchOperationsBar` (InstancesPage.tsx:591–644).+- Keep `SyncDropdown` (lines 539–589). Pass it as `children`:++```tsx+<SelectionActionBar+ count={selectedInstances.length}+ label={t("instance.selected-n-instances", { count: selectedInstances.length })}+ onClear={() => setSelectedInstanceNames(new Set())}+ actions={[+ {+ key: "edit-env",+ label: t("database.edit-environment"),+ icon: SquareStack,+ onClick: onEditEnvironment,+ disabled: !canUpdate,+ },+ showAssignLicense && {+ key: "assign-license",+ label: t("subscription.instance-assignment.assign-license"),+ icon: GraduationCap,+ onClick: onAssignLicense,+ disabled: !canUpdate,+ },+ ].filter(Boolean) as SelectionAction[]}+>+ <SyncDropdown disabled={!canSync || syncing} onSync={onSync} />+</SelectionActionBar>+```++Note: `SyncDropdown` will need a `size="sm"` cosmetic tweak so it visually+aligns with the bar's `size="sm"` action buttons. Optionally migrate+`SyncDropdown` to use the shared `DropdownMenu` primitive — this is a small+cleanup that fits the same change.++### 4. Cleanup++After the three migrations:++- Remove the `bg-blue-100` strip pattern from the codebase+ (`grep "bg-blue-100" frontend/src/react` should return zero matches in batch+ bars).+- Verify no remaining call sites of the old local `BatchOperationsBar`+ functions.++## Testing++- **Component test** for `SelectionActionBar` (`SelectionActionBar.test.tsx`):+ - Renders nothing when `count === 0`.+ - Renders `label`, all visible actions, and the clear button when `count > 0`.+ - `hidden: true` actions are omitted; `disabled: true` actions render as+ `disabled`.+ - Clicking an action button invokes its `onClick`.+ - Clicking the clear button invokes `onClear`.+ - Pressing `Escape` while `count > 0` invokes `onClear`.+ - `Escape` listener is **not** attached when `count === 0`.+ - `tone: "destructive"` applies the red-text override class.+ - Custom `children` render after declarative actions.+- **Integration smoke**: ProjectsPage, DatabasesPage, and InstancesPage each+ render the new bar when items are selected. (Existing tests cover selection+ state; assert the new bar's presence.)+- **Layering**: `pnpm --dir frontend check` passes after migration. No new+ raw-`z-index` or `document.body`-portal violations.+- **Type check**: `pnpm --dir frontend type-check` passes.++## Open questions++None. Tier A (flex-wrap) chosen for v1; Tier B (overflow menu) deferred. File+location is `frontend/src/react/components/SelectionActionBar.tsx` (top-level+components folder, not `ui/`), per design approval.++## Out of scope / follow-ups++- Tier B overflow menu — add only if the Database page (with up to 7 actions)+ feels crowded in practice.+- Migration of `SyncDropdown` to the shared `DropdownMenu` primitive — small+ optional cleanup; can be a follow-up if it bloats this PR.+- Other future selection-bar consumers (e.g. RolesPage, MembersPage) — they+ don't currently have batch bars; if they get one, they should use this+ component.diff --git a/frontend/src/react/components/IssueTable.tsx b/frontend/src/react/components/IssueTable.tsxindex dffcfd4340..c9c80069bf 100644--- a/frontend/src/react/components/IssueTable.tsx+++ b/frontend/src/react/components/IssueTable.tsx@@ -11,6 +11,7 @@ import {} from "@/react/components/AdvancedSearch";import { HighlightLabelText } from "@/react/components/HighlightLabelText";import { HumanizeTs } from "@/react/components/HumanizeTs";+import { SelectionActionBar } from "@/react/components/SelectionActionBar";import { TimeRangePicker } from "@/react/components/TimeRangePicker";import { Button } from "@/react/components/ui/button";import { Checkbox } from "@/react/components/ui/checkbox";@@ -916,51 +917,36 @@ export function BatchActionBar({!statuses.has(IssueStatus.OPEN) && !statuses.has(IssueStatus.DONE);return (- <div className="sticky bottom-0 w-full bg-background flex items-center gap-x-2 px-3 sm:px-4 py-2 border-y">- <Checkbox- checked={allSelected ? true : "indeterminate"}- onCheckedChange={() => onToggleSelectAll()}- />- <span className="text-sm text-control-light">- {issues.length} {t("common.selected")}- </span>- <Tooltip- content={- !canClose- ? t("issue.batch-transition.not-allowed-tips", {+ <SelectionActionBar+ count={issues.length}+ label={`${issues.length} ${t("common.selected")}`}+ allSelected={allSelected}+ onToggleSelectAll={onToggleSelectAll}+ actions={[+ {+ key: "close",+ label: t("issue.batch-transition.close"),+ onClick: () => onStartAction("CLOSE"),+ disabled: !canClose,+ disabledReason: canClose+ ? undefined+ : t("issue.batch-transition.not-allowed-tips", {operation: t("issue.batch-transition.closed"),- })- : undefined- }- >- <Button- variant="outline"- size="sm"- disabled={!canClose}- onClick={() => onStartAction("CLOSE")}- >- {t("issue.batch-transition.close")}- </Button>- </Tooltip>- <Tooltip- content={- !canReopen- ? t("issue.batch-transition.not-allowed-tips", {+ }),+ },+ {+ key: "reopen",+ label: t("issue.batch-transition.reopen"),+ onClick: () => onStartAction("REOPEN"),+ disabled: !canReopen,+ disabledReason: canReopen+ ? undefined+ : t("issue.batch-transition.not-allowed-tips", {operation: t("issue.batch-transition.reopened"),- })- : undefined- }- >- <Button- variant="outline"- size="sm"- disabled={!canReopen}- onClick={() => onStartAction("REOPEN")}- >- {t("issue.batch-transition.reopen")}- </Button>- </Tooltip>- </div>+ }),+ },+ ]}+ />);}diff --git a/frontend/src/react/components/SelectionActionBar.test.tsx b/frontend/src/react/components/SelectionActionBar.test.tsxnew file mode 100644index 0000000000..6734f9f4ed--- /dev/null+++ b/frontend/src/react/components/SelectionActionBar.test.tsx@@ -0,0 +1,219 @@+import { Archive, Trash2 } from "lucide-react";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { SelectionActionBar } from "./SelectionActionBar";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++describe("SelectionActionBar", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(async () => {+ await act(async () => {+ root.unmount();+ });+ document.body.innerHTML = "";+ });++ test("renders nothing when count is 0", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={0}+ label="0 selected"+ allSelected={false}+ onToggleSelectAll={() => {}}+ actions={[]}+ />+ );+ });+ expect(container.textContent ?? "").not.toContain("0 selected");+ expect(container.querySelector("[role='toolbar']")).toBeNull();+ });++ test("renders label and visible actions when count > 0", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={2}+ label="2 selected"+ allSelected={false}+ onToggleSelectAll={() => {}}+ actions={[+ {+ key: "archive",+ label: "Archive",+ icon: Archive,+ onClick: () => {},+ },+ {+ key: "delete",+ label: "Delete",+ icon: Trash2,+ onClick: () => {},+ tone: "destructive",+ },+ ]}+ />+ );+ });+ expect(container.textContent).toContain("2 selected");+ expect(container.textContent).toContain("Archive");+ expect(container.textContent).toContain("Delete");+ });++ test("omits hidden actions and disables disabled actions", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ allSelected={true}+ onToggleSelectAll={() => {}}+ actions={[+ { key: "a", label: "AlphaAction", onClick: () => {} },+ { key: "b", label: "BetaAction", onClick: () => {}, hidden: true },+ {+ key: "c",+ label: "GammaAction",+ onClick: () => {},+ disabled: true,+ },+ ]}+ />+ );+ });+ expect(container.textContent).toContain("AlphaAction");+ expect(container.textContent).not.toContain("BetaAction");+ const gamma = Array.from(container.querySelectorAll("button")).find((b) =>+ b.textContent?.includes("GammaAction")+ );+ expect(gamma).toBeDefined();+ expect(gamma?.hasAttribute("disabled")).toBe(true);+ });++ test("clicking an action invokes its onClick", async () => {+ const onClick = vi.fn();+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ allSelected={true}+ onToggleSelectAll={() => {}}+ actions={[{ key: "a", label: "ActionLabel", onClick }]}+ />+ );+ });+ const btn = Array.from(container.querySelectorAll("button")).find((b) =>+ b.textContent?.includes("ActionLabel")+ )!;+ await act(async () => {+ btn.click();+ });+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ test("toggling the leading checkbox invokes onToggleSelectAll", async () => {+ const onToggleSelectAll = vi.fn();+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ allSelected={false}+ onToggleSelectAll={onToggleSelectAll}+ actions={[]}+ />+ );+ });+ const checkbox =+ container.querySelector<HTMLButtonElement>('[role="checkbox"]')!;+ await act(async () => {+ checkbox.click();+ });+ expect(onToggleSelectAll).toHaveBeenCalledTimes(1);+ });++ test("destructive tone applies the red-tone override class", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ allSelected={true}+ onToggleSelectAll={() => {}}+ actions={[+ {+ key: "del",+ label: "DestructiveAction",+ onClick: () => {},+ tone: "destructive",+ },+ ]}+ />+ );+ });+ const btn = Array.from(container.querySelectorAll("button")).find((b) =>+ b.textContent?.includes("DestructiveAction")+ )!;+ expect(btn.className).toContain("text-error");+ });++ test("children render after declarative actions", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ allSelected={true}+ onToggleSelectAll={() => {}}+ actions={[{ key: "a", label: "InlineAction", onClick: () => {} }]}+ >+ <span data-testid="custom-slot">CustomSlot</span>+ </SelectionActionBar>+ );+ });+ expect(+ container.querySelector('[data-testid="custom-slot"]')+ ).not.toBeNull();+ expect(container.textContent).toContain("CustomSlot");+ });++ test("disabled action with disabledReason is wrapped in a tooltip-capable element", async () => {+ await act(async () => {+ root.render(+ <SelectionActionBar+ count={1}+ label="1 selected"+ allSelected={true}+ onToggleSelectAll={() => {}}+ actions={[+ {+ key: "blocked",+ label: "BlockedAction",+ onClick: () => {},+ disabled: true,+ disabledReason: "Permission denied",+ },+ ]}+ />+ );+ });+ const btn = Array.from(container.querySelectorAll("button")).find((b) =>+ b.textContent?.includes("BlockedAction")+ );+ expect(btn).toBeDefined();+ expect(btn?.hasAttribute("disabled")).toBe(true);+ });+});diff --git a/frontend/src/react/components/SelectionActionBar.tsx b/frontend/src/react/components/SelectionActionBar.tsxnew file mode 100644index 0000000000..7f7929560a--- /dev/null+++ b/frontend/src/react/components/SelectionActionBar.tsx@@ -0,0 +1,132 @@+import type { LucideIcon } from "lucide-react";+import type { ReactNode } from "react";+import { Button } from "@/react/components/ui/button";+import { Checkbox } from "@/react/components/ui/checkbox";+import { LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";+import { Separator } from "@/react/components/ui/separator";+import { Tooltip } from "@/react/components/ui/tooltip";+import { cn } from "@/react/lib/utils";++export interface SelectionAction {+ /** Stable key for React reconciliation. */+ key: string;+ label: string;+ icon?: LucideIcon;+ onClick: () => void;+ disabled?: boolean;+ /**+ * When `disabled` and this is set, the reason is shown as a tooltip+ * on hover/focus.+ */+ disabledReason?: string;+ /** When true, the action is omitted from the bar entirely. */+ hidden?: boolean;+ /**+ * Visual tone. "destructive" applies a red-text/border override on top+ * of the outline variant. Default: "neutral".+ */+ tone?: "neutral" | "destructive";+}++export interface SelectionActionBarProps {+ /** Number of selected items. The bar renders only when count > 0. */+ count: number;+ /**+ * Pre-formatted label (e.g. "2 selected", "3 databases selected").+ * The call site owns i18n + pluralization.+ */+ label: string;+ /**+ * True when every visible item on the current page is selected. Drives+ * the checkbox's checked vs. indeterminate state.+ */+ allSelected: boolean;+ /**+ * Toggles between "select every visible item" and "clear selection".+ * Called by the leading checkbox.+ */+ onToggleSelectAll: () => void;+ /** Declarative actions. Rendered in order. Hidden actions are omitted. */+ actions?: SelectionAction[];+ /**+ * Custom action nodes rendered after `actions`. Used for actions that+ * require richer UI (e.g. InstancesPage's split-dropdown Sync).+ *+ * Style note: declarative `actions` get `rounded-full` automatically so+ * they match the pill surface. Custom buttons rendered here should also+ * use `rounded-full` (or a wrapper Button with `className="rounded-full"`)+ * to stay visually consistent.+ */+ children?: ReactNode;+}++const DESTRUCTIVE_TONE_CLASS =+ "border-error text-error hover:bg-error/10 hover:text-error focus-visible:ring-error";++export function SelectionActionBar({+ count,+ label,+ allSelected,+ onToggleSelectAll,+ actions,+ children,+}: SelectionActionBarProps) {+ if (count <= 0) return null;++ const visibleActions = (actions ?? []).filter((a) => !a.hidden);++ return (+ <div+ className={cn(+ "fixed bottom-6 left-1/2 -translate-x-1/2 max-w-[90vw]",+ "flex items-center gap-x-3 rounded-full bg-background border border-control-border shadow-lg",+ "px-4 py-2",+ LAYER_SURFACE_CLASS+ )}+ >+ {/* Leading cluster — never shrinks; stays visible on narrow viewports+ even when the actions group has to scroll horizontally. */}+ <Checkbox+ checked={allSelected ? true : "indeterminate"}+ onCheckedChange={() => onToggleSelectAll()}+ />+ <span className="shrink-0 text-sm font-medium text-control whitespace-nowrap">+ {label}+ </span>+ {visibleActions.length > 0 && (+ <Separator orientation="vertical" className="h-5 shrink-0" />+ )}+ {/* Actions cluster — `min-w-0` lets flex shrink the container so+ `overflow-x-auto` can actually scroll within the pill's max-width. */}+ <div className="flex items-center gap-x-3 min-w-0 overflow-x-auto">+ {visibleActions.map((action) => {+ const Icon = action.icon;+ const button = (+ <Button+ variant="outline"+ size="sm"+ disabled={action.disabled}+ onClick={action.onClick}+ className={cn(+ "rounded-full",+ action.tone === "destructive" && DESTRUCTIVE_TONE_CLASS+ )}+ >+ {Icon && <Icon className="size-4" aria-hidden />}+ {action.label}+ </Button>+ );+ if (action.disabled && action.disabledReason) {+ return (+ <Tooltip key={action.key} content={action.disabledReason}>+ {button}+ </Tooltip>+ );+ }+ return <div key={action.key}>{button}</div>;+ })}+ {children}+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/database/DatabaseBatchOperationsBar.tsx b/frontend/src/react/components/database/DatabaseBatchOperationsBar.tsxindex e526f89812..214ecfbbaa 100644--- a/frontend/src/react/components/database/DatabaseBatchOperationsBar.tsx+++ b/frontend/src/react/components/database/DatabaseBatchOperationsBar.tsx@@ -8,7 +8,10 @@ import {Unlink,} from "lucide-react";import { useTranslation } from "react-i18next";-import { Button } from "@/react/components/ui/button";+import {+ type SelectionAction,+ SelectionActionBar,+} from "@/react/components/SelectionActionBar";import type { Permission } from "@/types";import type { Database } from "@/types/proto-es/v1/database_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";@@ -34,6 +37,15 @@ export interface DatabaseBatchOperationsBarProps {onChangeDatabase?: () => void;// Project context: export dataonExportData?: () => void;+ /**+ * True when every visible database on the current page is selected.+ * Drives the leading checkbox's checked vs. indeterminate state.+ */+ allSelected: boolean;+ /**+ * Toggles between "select every visible database" and "clear selection".+ */+ onToggleSelectAll: () => void;}export function DatabaseBatchOperationsBar({@@ -46,6 +58,8 @@ export function DatabaseBatchOperationsBar({onUnassign,onChangeDatabase,onExportData,+ allSelected,+ onToggleSelectAll,}: DatabaseBatchOperationsBarProps) {const { t } = useTranslation();@@ -62,85 +76,69 @@ export function DatabaseBatchOperationsBar({const canExportData =PERMISSIONS_FOR_DATABASE_EXPORT_ISSUE.every(hasPermission);- if (databases.length === 0) return null;+ const actions: SelectionAction[] = [+ {+ key: "change-database",+ label: t("database.change-database"),+ icon: Pencil,+ onClick: () => onChangeDatabase?.(),+ disabled: !canChangeDatabase,+ hidden: !onChangeDatabase,+ },+ {+ key: "export-data",+ label: t("custom-approval.risk-rule.risk.namespace.data_export"),+ icon: Download,+ onClick: () => onExportData?.(),+ disabled: !canExportData,+ hidden: !onExportData,+ },+ {+ key: "sync-schema",+ label: t("database.sync-schema-button"),+ icon: RefreshCw,+ onClick: onSyncSchema,+ disabled: !canSync,+ },+ {+ key: "edit-labels",+ label: t("database.edit-labels"),+ icon: Tag,+ onClick: onEditLabels,+ disabled: !canUpdate,+ },+ {+ key: "edit-environment",+ label: t("database.edit-environment"),+ icon: SquareStack,+ onClick: onEditEnvironment,+ disabled: !canUpdate || !canGetEnvironment,+ },+ {+ key: "transfer-project",+ label: t("database.transfer-project"),+ icon: ArrowRightLeft,+ onClick: () => onTransferProject?.(),+ disabled: !canUpdate,+ hidden: !onTransferProject,+ },+ {+ key: "unassign",+ label: t("database.unassign"),+ icon: Unlink,+ onClick: () => onUnassign?.(),+ disabled: !canUpdate,+ hidden: !onUnassign,+ },+ ];+return (- <div className="text-sm flex flex-col lg:flex-row items-start lg:items-center bg-blue-100 py-3 px-4 text-main gap-y-2 gap-x-4">- <span className="whitespace-nowrap text-sm">- {t("database.selected-n-databases", { n: databases.length })}- </span>- <div className="flex items-center flex-wrap">- {onChangeDatabase && (- <Button- variant="ghost"- size="md"- disabled={!canChangeDatabase}- onClick={onChangeDatabase}- >- <Pencil className="h-4 w-4 mr-1" />- {t("database.change-database")}- </Button>- )}- {onExportData && (- <Button- variant="ghost"- size="md"- disabled={!canExportData}- onClick={onExportData}- >- <Download className="h-4 w-4 mr-1" />- {t("custom-approval.risk-rule.risk.namespace.data_export")}- </Button>- )}- <Button- variant="ghost"- size="md"- disabled={!canSync}- onClick={onSyncSchema}- >- <RefreshCw className="h-4 w-4 mr-1" />- {t("database.sync-schema-button")}- </Button>- <Button- variant="ghost"- size="md"- disabled={!canUpdate}- onClick={onEditLabels}- >- <Tag className="h-4 w-4 mr-1" />- {t("database.edit-labels")}- </Button>- <Button- variant="ghost"- size="md"- disabled={!canUpdate || !canGetEnvironment}- onClick={onEditEnvironment}- >- <SquareStack className="h-4 w-4 mr-1" />- {t("database.edit-environment")}- </Button>- {onTransferProject && (- <Button- variant="ghost"- size="md"- disabled={!canUpdate}- onClick={onTransferProject}- >- <ArrowRightLeft className="h-4 w-4 mr-1" />- {t("database.transfer-project")}- </Button>- )}- {onUnassign && (- <Button- variant="ghost"- size="md"- disabled={!canUpdate}- onClick={onUnassign}- >- <Unlink className="h-4 w-4 mr-1" />- {t("database.unassign")}- </Button>- )}- </div>- </div>+ <SelectionActionBar+ count={databases.length}+ label={t("database.selected-n-databases", { n: databases.length })}+ allSelected={allSelected}+ onToggleSelectAll={onToggleSelectAll}+ actions={actions}+ />);}diff --git a/frontend/src/react/components/database/DatabaseTable.tsx b/frontend/src/react/components/database/DatabaseTable.tsxindex 05dd610df2..b95a89fb42 100644--- a/frontend/src/react/components/database/DatabaseTable.tsx+++ b/frontend/src/react/components/database/DatabaseTable.tsx@@ -24,6 +24,16 @@ export interface DatabaseTableProps {mode?: DatabaseTableMode;selectedNames?: Set<string>;onSelectedNamesChange?: (names: Set<string>) => void;+ /**+ * Fires when the visible-page database list changes. Lets a caller+ * compute "all selected on this page" for an external selection toolbar.+ *+ * Pass a stable callback reference (e.g. `setVisibleDatabases` directly,+ * not `(d) => setVisibleDatabases(d)` inline) — the effect that fires+ * this depends on the function identity, so an inline arrow recreates+ * it every render and re-fires the effect on every parent re-render.+ */+ onDatabasesChange?: (databases: Database[]) => void;refreshToken?: number;}@@ -40,6 +50,7 @@ export function DatabaseTable({mode = "ALL",selectedNames,onSelectedNamesChange,+ onDatabasesChange,refreshToken,}: DatabaseTableProps) {const databaseStore = useDatabaseV1Store();@@ -132,6 +143,11 @@ export function DatabaseTable({}}, [isFetchingMore, fetchDatabases]);+ // Notify caller whenever the visible-page database list changes.+ useEffect(() => {+ onDatabasesChange?.(databases);+ }, [databases, onDatabasesChange]);+const handleRowClick = useCallback((db: Database, e: React.MouseEvent) => {const url = router.resolve(autoDatabaseRoute(db)).fullPath;if (e.ctrlKey || e.metaKey) {@@ -155,7 +171,7 @@ export function DatabaseTable({onSortChange={setSort}onRowClick={handleRowClick}/>- <div className="mx-2">+ <div className="mt-4 mx-2"><PagedTableFooterpageSize={pageSize}pageSizeOptions={pageSizeOptions}diff --git a/frontend/src/react/pages/project/ProjectDatabasesPage.tsx b/frontend/src/react/pages/project/ProjectDatabasesPage.tsxindex b1b99982c2..c010bc1e79 100644--- a/frontend/src/react/pages/project/ProjectDatabasesPage.tsx+++ b/frontend/src/react/pages/project/ProjectDatabasesPage.tsx@@ -50,6 +50,7 @@ import {unknownEnvironment,} from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";+import type { Database } from "@/types/proto-es/v1/database_service_pb";import {BatchUpdateDatabasesRequestSchema,DatabaseSchema$,@@ -217,6 +218,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {// Selection stateconst [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());+ const [visibleDatabases, setVisibleDatabases] = useState<Database[]>([]);const selectedDatabases = useMemo(() => {if (selectedNames.size === 0) return [];@@ -408,47 +410,56 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {</div></div>- <div className="flex flex-col gap-y-4">- <DatabaseBatchOperationsBar- databases={selectedDatabases}- project={project}- onSyncSchema={handleSyncSchema}- onEditLabels={() => setShowLabelEditor(true)}- onEditEnvironment={() => setShowEditEnvDrawer(true)}- onUnassign={- isDefault ? undefined : () => setShowUnassignConfirm(true)- }- onChangeDatabase={isDefault ? undefined : handleChangeDatabase}- onExportData={isDefault ? undefined : handleExportData}- />-- <EditEnvironmentSheet- open={showEditEnvDrawer}- onClose={() => setShowEditEnvDrawer(false)}- onUpdate={handleEnvironmentUpdate}- />- <LabelEditorSheet- open={showLabelEditor}- databases={selectedDatabases}- onClose={() => setShowLabelEditor(false)}- onApply={handleLabelsApply}- />+ <DatabaseTable+ filter={filter}+ parent={projectName}+ mode="PROJECT"+ selectedNames={selectedNames}+ onSelectedNamesChange={setSelectedNames}+ onDatabasesChange={setVisibleDatabases}+ refreshToken={refreshToken}+ />- <DatabaseTable- filter={filter}- parent={projectName}- mode="PROJECT"- selectedNames={selectedNames}- onSelectedNamesChange={setSelectedNames}- refreshToken={refreshToken}- />- </div>+ {/* Batch operations bar */}+ <DatabaseBatchOperationsBar+ databases={selectedDatabases}+ project={project}+ onSyncSchema={handleSyncSchema}+ onEditLabels={() => setShowLabelEditor(true)}+ onEditEnvironment={() => setShowEditEnvDrawer(true)}+ onUnassign={isDefault ? undefined : () => setShowUnassignConfirm(true)}+ onChangeDatabase={isDefault ? undefined : handleChangeDatabase}+ onExportData={isDefault ? undefined : handleExportData}+ allSelected={+ visibleDatabases.length > 0 &&+ visibleDatabases.every((d) => selectedNames.has(d.name))+ }+ onToggleSelectAll={() => {+ const allOnPage =+ visibleDatabases.length > 0 &&+ visibleDatabases.every((d) => selectedNames.has(d.name));+ if (allOnPage) setSelectedNames(new Set());+ else setSelectedNames(new Set(visibleDatabases.map((d) => d.name)));+ }}+ />+ {/* Modals (portaled, position-independent) */}<CreateDatabaseSheetopen={showCreateDrawer}onClose={() => setShowCreateDrawer(false)}projectName={projectName}/>+ <EditEnvironmentSheet+ open={showEditEnvDrawer}+ onClose={() => setShowEditEnvDrawer(false)}+ onUpdate={handleEnvironmentUpdate}+ />+ <LabelEditorSheet+ open={showLabelEditor}+ databases={selectedDatabases}+ onClose={() => setShowLabelEditor(false)}+ onApply={handleLabelsApply}+ /><DataExportPrepSheetopen={showExportDrawer}diff --git a/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx b/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsxindex 1c56b7ef99..54c6fbff28 100644--- a/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx+++ b/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx@@ -267,7 +267,6 @@ export function ProjectIssueDashboardPage({/>)))}-{paged.dataList.length > 0 && (<div className="mt-4 mx-2"><PagedTableFooter@@ -294,6 +293,7 @@ export function ProjectIssueDashboardPage({/>)}+ {/* Modals (portaled, position-independent) */}<BatchIssueStatusActionDrawerissues={selectedIssues}action={batchAction}diff --git a/frontend/src/react/pages/settings/DatabasesPage.tsx b/frontend/src/react/pages/settings/DatabasesPage.tsxindex c119e61390..07fe7d0770 100644--- a/frontend/src/react/pages/settings/DatabasesPage.tsx+++ b/frontend/src/react/pages/settings/DatabasesPage.tsx@@ -46,6 +46,7 @@ import {unknownEnvironment,} from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";+import type { Database } from "@/types/proto-es/v1/database_service_pb";import {BatchUpdateDatabasesRequestSchema,DatabaseSchema$,@@ -304,6 +305,7 @@ export function DatabasesPage() {// Selection stateconst [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());+ const [visibleDatabases, setVisibleDatabases] = useState<Database[]>([]);const selectedDatabases = useMemo(() => {if (selectedNames.size === 0) return [];@@ -475,45 +477,57 @@ export function DatabasesPage() {</PermissionGuard></div>- <div className="flex flex-col gap-y-4">- <DatabaseBatchOperationsBar- databases={selectedDatabases}- onSyncSchema={handleSyncSchema}- onEditLabels={() => setShowLabelEditor(true)}- onEditEnvironment={() => setShowEditEnvDrawer(true)}- onTransferProject={() => setShowTransferDrawer(true)}- />- <EditEnvironmentSheet- open={showEditEnvDrawer}- onClose={() => setShowEditEnvDrawer(false)}- onUpdate={handleEnvironmentUpdate}- />- <LabelEditorSheet- open={showLabelEditor}- databases={selectedDatabases}- onClose={() => setShowLabelEditor(false)}- onApply={handleLabelsApply}- />- <TransferProjectSheet- open={showTransferDrawer}- databases={selectedDatabases}- onClose={() => setShowTransferDrawer(false)}- onTransfer={handleTransferProject}- />+ <DatabaseTable+ filter={filter}+ mode="ALL"+ selectedNames={selectedNames}+ onSelectedNamesChange={setSelectedNames}+ onDatabasesChange={setVisibleDatabases}+ refreshToken={refreshToken}+ />- <DatabaseTable- filter={filter}- mode="ALL"- selectedNames={selectedNames}- onSelectedNamesChange={setSelectedNames}- refreshToken={refreshToken}- />- </div>+ {/* Batch operations bar */}+ <DatabaseBatchOperationsBar+ databases={selectedDatabases}+ onSyncSchema={handleSyncSchema}+ onEditLabels={() => setShowLabelEditor(true)}+ onEditEnvironment={() => setShowEditEnvDrawer(true)}+ onTransferProject={() => setShowTransferDrawer(true)}+ allSelected={+ visibleDatabases.length > 0 &&+ visibleDatabases.every((d) => selectedNames.has(d.name))+ }+ onToggleSelectAll={() => {+ const allOnPage =+ visibleDatabases.length > 0 &&+ visibleDatabases.every((d) => selectedNames.has(d.name));+ if (allOnPage) setSelectedNames(new Set());+ else setSelectedNames(new Set(visibleDatabases.map((d) => d.name)));+ }}+ />+ {/* Modals (portaled, position-independent) */}<CreateDatabaseSheetopen={showCreateDrawer}onClose={() => setShowCreateDrawer(false)}/>+ <EditEnvironmentSheet+ open={showEditEnvDrawer}+ onClose={() => setShowEditEnvDrawer(false)}+ onUpdate={handleEnvironmentUpdate}+ />+ <LabelEditorSheet+ open={showLabelEditor}+ databases={selectedDatabases}+ onClose={() => setShowLabelEditor(false)}+ onApply={handleLabelsApply}+ />+ <TransferProjectSheet+ open={showTransferDrawer}+ databases={selectedDatabases}+ onClose={() => setShowTransferDrawer(false)}+ onTransfer={handleTransferProject}+ /></div>);}diff --git a/frontend/src/react/pages/settings/InstanceDetailPage.tsx b/frontend/src/react/pages/settings/InstanceDetailPage.tsxindex 3ac7333010..46edf7597c 100644--- a/frontend/src/react/pages/settings/InstanceDetailPage.tsx+++ b/frontend/src/react/pages/settings/InstanceDetailPage.tsx@@ -54,6 +54,7 @@ import {unknownEnvironment,} from "@/types";import { State } from "@/types/proto-es/v1/common_pb";+import type { Database } from "@/types/proto-es/v1/database_service_pb";import {BatchUpdateDatabasesRequestSchema,DatabaseSchema$,@@ -89,6 +90,7 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {// Selection / batch operationsconst [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());+ const [visibleDatabases, setVisibleDatabases] = useState<Database[]>([]);const [refreshToken, setRefreshToken] = useState(0);const [syncing, setSyncing] = useState(false);const [showLabelEditor, setShowLabelEditor] = useState(false);@@ -424,13 +426,6 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {placeholder={t("database.filter-database")}scopeOptions={scopeOptions}/>- <DatabaseBatchOperationsBar- databases={selectedDatabases}- onSyncSchema={handleSyncSchema}- onEditLabels={() => setShowLabelEditor(true)}- onEditEnvironment={() => setShowEditEnvDrawer(true)}- onTransferProject={() => setShowTransferDrawer(true)}- /><EditEnvironmentSheetopen={showEditEnvDrawer}onClose={() => setShowEditEnvDrawer(false)}@@ -454,8 +449,32 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {mode="ALL"selectedNames={selectedNames}onSelectedNamesChange={setSelectedNames}+ onDatabasesChange={setVisibleDatabases}refreshToken={refreshToken}/>+ {/* Batch operations bar (sticky at bottom; rendered after the+ table so selection doesn't shift table position) */}+ <DatabaseBatchOperationsBar+ databases={selectedDatabases}+ onSyncSchema={handleSyncSchema}+ onEditLabels={() => setShowLabelEditor(true)}+ onEditEnvironment={() => setShowEditEnvDrawer(true)}+ onTransferProject={() => setShowTransferDrawer(true)}+ allSelected={+ visibleDatabases.length > 0 &&+ visibleDatabases.every((d) => selectedNames.has(d.name))+ }+ onToggleSelectAll={() => {+ const allOnPage =+ visibleDatabases.length > 0 &&+ visibleDatabases.every((d) => selectedNames.has(d.name));+ if (allOnPage) setSelectedNames(new Set());+ else+ setSelectedNames(+ new Set(visibleDatabases.map((d) => d.name))+ );+ }}+ /></div></TabsPanel>diff --git a/frontend/src/react/pages/settings/InstancesPage.tsx b/frontend/src/react/pages/settings/InstancesPage.tsxindex edbf3755aa..12c6d6bc8f 100644--- a/frontend/src/react/pages/settings/InstancesPage.tsx+++ b/frontend/src/react/pages/settings/InstancesPage.tsx@@ -9,7 +9,6 @@ import {RefreshCw,SquareStack,} from "lucide-react";-import type { RefObject } from "react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import {@@ -22,6 +21,10 @@ import { EngineIcon } from "@/react/components/EngineIcon";import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";import { InstanceAssignmentSheet } from "@/react/components/InstanceAssignmentSheet";import { PermissionGuard } from "@/react/components/PermissionGuard";+import {+ type SelectionAction,+ SelectionActionBar,+} from "@/react/components/SelectionActionBar";import { Alert } from "@/react/components/ui/alert";import {AlertDialog,@@ -109,26 +112,6 @@ interface InstanceColumn {render: (instance: Instance) => React.ReactNode;}-// Shared hooks-// ============================================================--function useClickOutside(- ref: RefObject<HTMLElement | null>,- active: boolean,- onClose: () => void-) {- useEffect(() => {- if (!active) return;- const handler = (e: MouseEvent) => {- if (ref.current && !ref.current.contains(e.target as Node)) {- onClose();- }- };- document.addEventListener("mousedown", handler);- return () => document.removeEventListener("mousedown", handler);- }, [ref, active, onClose]);-}-// ============================================================// ConfirmDialog// ============================================================@@ -532,7 +515,7 @@ function EditEnvironmentSheet({}// ============================================================-// BatchOperationsBar+// SyncDropdown// ============================================================function SyncDropdown({@@ -543,102 +526,35 @@ function SyncDropdown({onSync: (enableFullSync: boolean) => void;}) {const { t } = useTranslation();- const [open, setOpen] = useState(false);- const dropdownRef = useRef<HTMLDivElement>(null);- const closeDropdown = useCallback(() => setOpen(false), []);- useClickOutside(dropdownRef, open, closeDropdown);-- return (- <div ref={dropdownRef} className="relative">- <Button- variant="ghost"- size="md"- disabled={disabled}- onClick={() => setOpen(!open)}- >- <RefreshCw className={cn("h-4 w-4 mr-1", disabled && "animate-spin")} />- {disabled ? t("instance.syncing") : t("instance.sync.self")}- <ChevronDown className="h-3 w-3 ml-1" />- </Button>- {open && (- <div className="absolute left-0 top-full mt-1 bg-background border border-control-border rounded-sm shadow-lg z-10 min-w-[200px]">- <button- className="w-full text-left px-3 py-2 text-sm hover:bg-control-bg"- title={t("instance.sync.sync-all-tip")}- onClick={() => {- setOpen(false);- onSync(true);- }}- >- {t("instance.sync.sync-all")}- </button>- <button- className="w-full text-left px-3 py-2 text-sm hover:bg-control-bg"- onClick={() => {- setOpen(false);- onSync(false);- }}- >- {t("instance.sync.sync-new")}- </button>- </div>- )}- </div>- );-}--function BatchOperationsBar({- selectedInstances,- syncing,- onSync,- onEditEnvironment,- onAssignLicense,- showAssignLicense,-}: {- selectedInstances: Instance[];- syncing: boolean;- onSync: (enableFullSync: boolean) => void;- onEditEnvironment: () => void;- onAssignLicense: () => void;- showAssignLicense?: boolean;-}) {- const { t } = useTranslation();- const canSync = hasWorkspacePermissionV2("bb.instances.sync");- const canUpdate = hasWorkspacePermissionV2("bb.instances.update");-- if (selectedInstances.length === 0) return null;return (- <div className="relative z-10 text-sm flex flex-col lg:flex-row items-start lg:items-center bg-blue-100 py-3 px-4 text-main gap-y-2 gap-x-4 overflow-visible">- <span className="whitespace-nowrap text-sm">- {t("instance.selected-n-instances", {- count: selectedInstances.length,- })}- </span>- <div className="flex items-center">- <SyncDropdown disabled={!canSync || syncing} onSync={onSync} />- <Button- variant="ghost"- size="md"- disabled={!canUpdate}- onClick={onEditEnvironment}- >- <SquareStack className="h-4 w-4 mr-1" />- {t("database.edit-environment")}- </Button>- {showAssignLicense && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={<Button- variant="ghost"- size="md"- disabled={!canUpdate}- onClick={onAssignLicense}+ variant="outline"+ size="sm"+ className="rounded-full"+ disabled={disabled}>- <GraduationCap className="h-4 w-4 mr-1" />- {t("subscription.instance-assignment.assign-license")}+ <RefreshCw className={cn("size-4", disabled && "animate-spin")} />+ {disabled ? t("instance.syncing") : t("instance.sync.self")}+ <ChevronDown className="size-3" /></Button>- )}- </div>- </div>+ }+ />+ <DropdownMenuContent align="start" className="min-w-[200px]">+ <DropdownMenuItem+ title={t("instance.sync.sync-all-tip")}+ onClick={() => onSync(true)}+ >+ {t("instance.sync.sync-all")}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => onSync(false)}>+ {t("instance.sync.sync-new")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>);}@@ -1257,35 +1173,6 @@ export function InstancesPage() {</PermissionGuard></div>- {/* Batch operations */}- <BatchOperationsBar- selectedInstances={selectedInstanceList}- syncing={syncing}- onSync={handleSync}- onEditEnvironment={() => setShowEditEnvDrawer(true)}- onAssignLicense={() =>- handleAssignLicense(- selectedInstanceList.map((instance) => instance.name)- )- }- showAssignLicense={hasSplitInstanceLicense}- />-- <EditEnvironmentSheet- open={showEditEnvDrawer}- onClose={() => setShowEditEnvDrawer(false)}- onUpdate={handleEnvironmentUpdate}- />- {hasSplitInstanceLicense && (- <InstanceAssignmentSheet- open={showAssignLicenseSheet}- selectedInstanceList={assignLicenseNames}- onOpenChange={setShowAssignLicenseSheet}- onUpdated={handleRowAction}- />- )}-- {/* Table */}<div className="overflow-x-auto border-y border-block-border"><Table className="table-fixed" style={{ minWidth: `${totalWidth}px` }}><colgroup>@@ -1362,7 +1249,6 @@ export function InstancesPage() {</Table></div>- {/* Pagination footer */}<div className="mt-4 mx-2"><PagedTableFooterpageSize={pageSize}@@ -1373,6 +1259,67 @@ export function InstancesPage() {onLoadMore={loadMore}/></div>++ {/* Batch operations bar (sticky at bottom; rendered after the+ table so selection doesn't shift table position) */}+ {(() => {+ const canSync = hasWorkspacePermissionV2("bb.instances.sync");+ const canUpdate = hasWorkspacePermissionV2("bb.instances.update");+ const instanceActions: SelectionAction[] = [+ {+ key: "edit-env",+ label: t("database.edit-environment"),+ icon: SquareStack,+ onClick: () => setShowEditEnvDrawer(true),+ disabled: !canUpdate,+ },+ {+ key: "assign-license",+ label: t("subscription.instance-assignment.assign-license"),+ icon: GraduationCap,+ onClick: () =>+ handleAssignLicense(+ selectedInstanceList.map((instance) => instance.name)+ ),+ disabled: !canUpdate,+ hidden: !hasSplitInstanceLicense,+ },+ ];+ const allSelected =+ instances.length > 0 &&+ instances.every((i) => selectedNames.has(i.name));+ return (+ <SelectionActionBar+ count={selectedInstanceList.length}+ label={t("instance.selected-n-instances", {+ count: selectedInstanceList.length,+ })}+ allSelected={allSelected}+ onToggleSelectAll={() => {+ if (allSelected) setSelectedNames(new Set());+ else setSelectedNames(new Set(instances.map((i) => i.name)));+ }}+ actions={instanceActions}+ >+ <SyncDropdown disabled={!canSync || syncing} onSync={handleSync} />+ </SelectionActionBar>+ );+ })()}++ {/* Modals (portaled, position-independent) */}+ <EditEnvironmentSheet+ open={showEditEnvDrawer}+ onClose={() => setShowEditEnvDrawer(false)}+ onUpdate={handleEnvironmentUpdate}+ />+ {hasSplitInstanceLicense && (+ <InstanceAssignmentSheet+ open={showAssignLicenseSheet}+ selectedInstanceList={assignLicenseNames}+ onOpenChange={setShowAssignLicenseSheet}+ onUpdated={handleRowAction}+ />+ )}</div>);}diff --git a/frontend/src/react/pages/settings/ProjectsPage.tsx b/frontend/src/react/pages/settings/ProjectsPage.tsxindex d33699c822..0d7a5f6112 100644--- a/frontend/src/react/pages/settings/ProjectsPage.tsx+++ b/frontend/src/react/pages/settings/ProjectsPage.tsx@@ -10,6 +10,10 @@ import {import { ProjectCreateDialog } from "@/react/components/header/ProjectCreateDialog";import { PermissionGuard } from "@/react/components/PermissionGuard";import { ProjectTable } from "@/react/components/ProjectTable";+import {+ type SelectionAction,+ SelectionActionBar,+} from "@/react/components/SelectionActionBar";import {AlertDialog,AlertDialogContent,@@ -113,211 +117,6 @@ function ConfirmDialog({);}-// ============================================================-// BatchOperationsBar-// ============================================================--function BatchOperationsBar({- selectedProjects,- onUpdate,-}: {- selectedProjects: Project[];- onUpdate: () => void;-}) {- const { t } = useTranslation();- const projectStore = useProjectV1Store();- const [showArchiveConfirm, setShowArchiveConfirm] = useState(false);- const [showRestoreConfirm, setShowRestoreConfirm] = useState(false);- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);-- // Determine which actions to show based on selected projects' actual state- const hasActiveProjects = selectedProjects.some(- (p) => p.state === State.ACTIVE- );- const hasArchivedProjects = selectedProjects.some(- (p) => p.state === State.DELETED- );-- const handleBatchArchive = useCallback(async () => {- try {- const activeProjects = selectedProjects.filter(- (p) => p.state === State.ACTIVE- );- await projectStore.batchDeleteProjects(activeProjects.map((p) => p.name));- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("project.batch.archive.success", {- count: activeProjects.length,- }),- });- setShowArchiveConfirm(false);- onUpdate();- } catch (error: unknown) {- const err = error as { message?: string };- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("project.batch.archive.error"),- description: err.message,- });- }- }, [selectedProjects, projectStore, t, onUpdate]);-- const handleBatchRestore = useCallback(async () => {- try {- const archivedProjects = selectedProjects.filter(- (p) => p.state === State.DELETED- );- await Promise.all(- archivedProjects.map((project) => projectStore.restoreProject(project))- );- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.restored"),- });- setShowRestoreConfirm(false);- onUpdate();- } catch (error: unknown) {- const err = error as { message?: string };- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.restore"),- description: err.message,- });- }- }, [selectedProjects, projectStore, t, onUpdate]);-- const handleBatchDelete = useCallback(async () => {- try {- await projectStore.batchPurgeProjects(- selectedProjects.map((p) => p.name)- );- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("project.batch.delete.success", {- count: selectedProjects.length,- }),- });- setShowDeleteConfirm(false);- onUpdate();- } catch (error: unknown) {- const err = error as { message?: string };- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("project.batch.delete.error"),- description: err.message,- });- }- }, [selectedProjects, projectStore, t, onUpdate]);-- if (selectedProjects.length === 0) return null;-- return (- <>- <div className="text-sm flex flex-col lg:flex-row items-start lg:items-center bg-blue-100 py-3 px-4 text-main gap-y-2 gap-x-4 overflow-x-auto">- <span className="whitespace-nowrap text-sm">- {t("project.batch.selected", {- count: selectedProjects.length,- })}- </span>- <div className="flex items-center">- {hasActiveProjects && (- <Button- variant="ghost"- size="md"- onClick={() => setShowArchiveConfirm(true)}- >- <Archive className="h-4 w-4 mr-1" />- {t("common.archive")}- </Button>- )}- {hasArchivedProjects && (- <Button- variant="ghost"- size="md"- onClick={() => setShowRestoreConfirm(true)}- >- {t("common.restore")}- </Button>- )}- <Button- variant="ghost"- size="md"- onClick={() => setShowDeleteConfirm(true)}- >- <Trash2 className="h-4 w-4 mr-1" />- {t("common.delete")}- </Button>- </div>- </div>-- <ConfirmDialog- open={showArchiveConfirm}- variant="warning"- title={t("project.batch.archive.title", {- count: selectedProjects.length,- })}- description={t("project.batch.archive.description")}- okText={t("common.archive")}- onOk={handleBatchArchive}- onCancel={() => setShowArchiveConfirm(false)}- >- <ProjectListPreview- projects={selectedProjects}- iconColor="text-success"- />- </ConfirmDialog>-- <ConfirmDialog- open={showRestoreConfirm}- variant="warning"- title={t("common.restore")}- description={t("common.restore")}- okText={t("common.restore")}- onOk={handleBatchRestore}- onCancel={() => setShowRestoreConfirm(false)}- >- <ProjectListPreview- projects={selectedProjects}- iconColor="text-success"- />- </ConfirmDialog>-- <ConfirmDialog- open={showDeleteConfirm}- variant="error"- title={t("project.batch.delete.title", {- count: selectedProjects.length,- })}- description={t("project.batch.delete.description")}- okText={t("common.delete")}- onOk={handleBatchDelete}- onCancel={() => setShowDeleteConfirm(false)}- >- <div className="flex flex-col gap-y-3">- <ProjectListPreview- projects={selectedProjects}- iconColor="text-error"- />- <div className="rounded-sm border border-error bg-error/5 p-3">- <p className="text-sm font-medium text-error">- {t("common.cannot-undo-this-action")}- </p>- <p className="text-sm text-error/80 mt-1">- {t("project.batch.delete.warning")}- </p>- </div>- </div>- </ConfirmDialog>- </>- );-}-function ProjectListPreview({projects,iconColor,@@ -676,6 +475,118 @@ export function ProjectsPage() {fetchProjects(true);}, [fetchProjects]);+ // Batch confirm dialog state + handlers (lifted from old BatchOperationsBar)+ const [showArchiveConfirm, setShowArchiveConfirm] = useState(false);+ const [showRestoreConfirm, setShowRestoreConfirm] = useState(false);+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);++ const hasActiveProjects = selectedProjectList.some(+ (p) => p.state === State.ACTIVE+ );+ const hasArchivedProjects = selectedProjectList.some(+ (p) => p.state === State.DELETED+ );++ const handleBatchArchive = useCallback(async () => {+ try {+ const activeProjects = selectedProjectList.filter(+ (p) => p.state === State.ACTIVE+ );+ await projectStore.batchDeleteProjects(activeProjects.map((p) => p.name));+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.batch.archive.success", {+ count: activeProjects.length,+ }),+ });+ setShowArchiveConfirm(false);+ handleBatchOperation();+ } catch (error: unknown) {+ const err = error as { message?: string };+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("project.batch.archive.error"),+ description: err.message,+ });+ }+ }, [selectedProjectList, projectStore, t, handleBatchOperation]);++ const handleBatchRestore = useCallback(async () => {+ try {+ const archivedProjects = selectedProjectList.filter(+ (p) => p.state === State.DELETED+ );+ await Promise.all(+ archivedProjects.map((project) => projectStore.restoreProject(project))+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.restored"),+ });+ setShowRestoreConfirm(false);+ handleBatchOperation();+ } catch (error: unknown) {+ const err = error as { message?: string };+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.restore"),+ description: err.message,+ });+ }+ }, [selectedProjectList, projectStore, t, handleBatchOperation]);++ const handleBatchDelete = useCallback(async () => {+ try {+ await projectStore.batchPurgeProjects(+ selectedProjectList.map((p) => p.name)+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.batch.delete.success", {+ count: selectedProjectList.length,+ }),+ });+ setShowDeleteConfirm(false);+ handleBatchOperation();+ } catch (error: unknown) {+ const err = error as { message?: string };+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("project.batch.delete.error"),+ description: err.message,+ });+ }+ }, [selectedProjectList, projectStore, t, handleBatchOperation]);++ const batchActions: SelectionAction[] = [+ {+ key: "archive",+ label: t("common.archive"),+ icon: Archive,+ onClick: () => setShowArchiveConfirm(true),+ hidden: !hasActiveProjects,+ },+ {+ key: "restore",+ label: t("common.restore"),+ onClick: () => setShowRestoreConfirm(true),+ hidden: !hasArchivedProjects,+ },+ {+ key: "delete",+ label: t("common.delete"),+ icon: Trash2,+ onClick: () => setShowDeleteConfirm(true),+ tone: "destructive",+ },+ ];+// Create drawerconst [showCreateDrawer, setShowCreateDrawer] = useState(false);const canCreate = hasWorkspacePermissionV2("bb.projects.create");@@ -724,15 +635,6 @@ export function ProjectsPage() {</PermissionGuard></div>- {/* Batch operations */}- {canDelete && (- <BatchOperationsBar- selectedProjects={selectedProjectList}- onUpdate={handleBatchOperation}- />- )}-- {/* Table */}<div className="overflow-x-auto border-y border-block-border"><ProjectTableclassName="min-w-[700px]"@@ -757,7 +659,6 @@ export function ProjectsPage() {/></div>- {/* Pagination footer */}<div className="mt-4 mx-2"><PagedTableFooterpageSize={pageSize}@@ -769,12 +670,94 @@ export function ProjectsPage() {/></div>- {/* Create drawer */}+ {/* Batch operations bar (sticky at bottom; rendered after the+ table so selection doesn't shift table position) */}+ {canDelete && (+ <SelectionActionBar+ count={selectedProjectList.length}+ label={t("project.batch.selected", {+ count: selectedProjectList.length,+ })}+ allSelected={+ projects.length > 0 &&+ projects.every((p) => selectedNames.has(p.name))+ }+ onToggleSelectAll={() => {+ const allOnPage =+ projects.length > 0 &&+ projects.every((p) => selectedNames.has(p.name));+ if (allOnPage) setSelectedNames(new Set());+ else setSelectedNames(new Set(projects.map((p) => p.name)));+ }}+ actions={batchActions}+ />+ )}++ {/* Modals (portaled, position-independent) */}<ProjectCreateDialogopen={showCreateDrawer}onClose={() => setShowCreateDrawer(false)}onCreated={handleCreated}/>++ <ConfirmDialog+ open={showArchiveConfirm}+ variant="warning"+ title={t("project.batch.archive.title", {+ count: selectedProjectList.length,+ })}+ description={t("project.batch.archive.description")}+ okText={t("common.archive")}+ onOk={handleBatchArchive}+ onCancel={() => setShowArchiveConfirm(false)}+ >+ <ProjectListPreview+ projects={selectedProjectList}+ iconColor="text-success"+ />+ </ConfirmDialog>++ <ConfirmDialog+ open={showRestoreConfirm}+ variant="warning"+ title={t("common.restore")}+ description={t("common.restore")}+ okText={t("common.restore")}+ onOk={handleBatchRestore}+ onCancel={() => setShowRestoreConfirm(false)}+ >+ <ProjectListPreview+ projects={selectedProjectList}+ iconColor="text-success"+ />+ </ConfirmDialog>++ <ConfirmDialog+ open={showDeleteConfirm}+ variant="error"+ title={t("project.batch.delete.title", {+ count: selectedProjectList.length,+ })}+ description={t("project.batch.delete.description")}+ okText={t("common.delete")}+ onOk={handleBatchDelete}+ onCancel={() => setShowDeleteConfirm(false)}+ >+ <div className="flex flex-col gap-y-3">+ <ProjectListPreview+ projects={selectedProjectList}+ iconColor="text-error"+ />+ <div className="rounded-sm border border-error bg-error/5 p-3">+ <p className="text-sm font-medium text-error">+ {t("common.cannot-undo-this-action")}+ </p>+ <p className="text-sm text-error/80 mt-1">+ {t("project.batch.delete.warning")}+ </p>+ </div>+ </div>+ </ConfirmDialog></div>);}diff --git a/frontend/src/react/pages/workspace/MyIssuesPage.tsx b/frontend/src/react/pages/workspace/MyIssuesPage.tsxindex 5af0743f49..4bbecd5c50 100644--- a/frontend/src/react/pages/workspace/MyIssuesPage.tsx+++ b/frontend/src/react/pages/workspace/MyIssuesPage.tsx@@ -212,7 +212,6 @@ export function MyIssuesPage() {/>)))}-{paged.dataList.length > 0 && (<div className="mt-4 mx-2"><PagedTableFooter@@ -239,6 +238,7 @@ export function MyIssuesPage() {/>)}+ {/* Modals (portaled, position-independent) */}<BatchIssueStatusActionDrawerissues={selectedIssues}action={batchAction}