Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: optimize workspace switcher (#20208)
ecmadao2b1d0daa3869
diff --git a/frontend/src/react/components/DashboardSidebar.tsx b/frontend/src/react/components/DashboardSidebar.tsxindex b829013607..2da6d77857 100644--- a/frontend/src/react/components/DashboardSidebar.tsx+++ b/frontend/src/react/components/DashboardSidebar.tsx@@ -52,7 +52,6 @@ import {WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,} from "@/react/router";import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";-import { WorkspaceSwitcher } from "./WorkspaceSwitcher";// ---------------------------------------------------------------------------// Types@@ -527,7 +526,6 @@ export function DashboardSidebar() {><img src={logoSrc} alt="Bytebase" className="max-w-44" /></a>- <WorkspaceSwitcher /><div className="flex-1 overflow-y-auto px-2.5 pb-4 flex flex-col gap-y-1">{filteredItems.map((item, i) => renderItem(item, i))}</div>diff --git a/frontend/src/react/components/ProjectSelect.tsx b/frontend/src/react/components/ProjectSelect.tsxindex b5e3381ff0..585103ffec 100644--- a/frontend/src/react/components/ProjectSelect.tsx+++ b/frontend/src/react/components/ProjectSelect.tsx@@ -1,5 +1,5 @@import type { ReactNode } from "react";-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { Combobox } from "@/react/components/ui/combobox";import { useProjectV1Store } from "@/store";@@ -46,21 +46,36 @@ export function ProjectSelect({// returns it.const [additionalProjects, setAdditionalProjects] = useState<Project[]>([]);+ // Read `excludeDefault` from a ref inside the callback so the+ // callback identity stays stable across re-renders. Without this, any+ // parent re-render that re-evaluates the `excludeDefault` prop+ // expression (e.g. the SQL Editor's `AsidePanel` re-rendering on+ // tab.connection mutations) recreates the callback, which causes the+ // mount-`useEffect` below to re-fire and hit `ListProjects` on every+ // re-render. The boolean value itself is read live each call, so+ // updates still take effect — just without re-running the effect.+ const excludeDefaultRef = useRef(excludeDefault);+ excludeDefaultRef.current = excludeDefault;+const fetchProjects = useCallback((query: string) => {projectStore.fetchProjectList({- filter: { query, excludeDefault },+ filter: { query, excludeDefault: excludeDefaultRef.current },pageSize: getDefaultPagination(),}).then(({ projects: result }) => setProjects(result));},- [projectStore, excludeDefault]+ [projectStore]);+ // Fetch the first page on mount, and re-fetch only when+ // `excludeDefault` actually flips (rare — typically once after+ // permissions hydrate). `fetchProjects` is stable so this effect+ // never re-fires from parent re-renders alone.useEffect(() => {fetchProjects("");- }, [fetchProjects]);+ }, [excludeDefault, fetchProjects]);// Hydrate the selected project so the trigger always renders its// label, even before the paged list loads or when the project isdiff --git a/frontend/src/react/components/header/DashboardHeader.test.tsx b/frontend/src/react/components/header/DashboardHeader.test.tsxindex 81962cae52..3811279602 100644--- a/frontend/src/react/components/header/DashboardHeader.test.tsx+++ b/frontend/src/react/components/header/DashboardHeader.test.tsx@@ -62,8 +62,8 @@ vi.mock("@/react/components/BytebaseLogo", () => ({),}));-vi.mock("@/react/components/header/ProjectSwitchPopover", () => ({- ProjectSwitchPopover: () => <div data-testid="project-switch-popover" />,+vi.mock("@/react/components/header/HeaderBreadcrumb", () => ({+ HeaderBreadcrumb: () => <div data-testid="header-breadcrumb" />,}));vi.mock("@/react/components/header/ProfileMenuTrigger", () => ({@@ -83,9 +83,12 @@ vi.mock("@/react/router", () => ({SQL_EDITOR_DATABASE_MODULE: "sql-editor.database",}));-vi.mock("@/utils/storage-keys", () => ({- STORAGE_KEY_MY_ISSUES_TAB: "bb.components.MY_ISSUES.id",-}));+vi.mock("@/utils/storage-keys", async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...(actual as Record<string, unknown>),+ };+});vi.mock("@/react/plugins/agent/store/agent", () => ({useAgentStore: {@@ -155,7 +158,7 @@ describe("DashboardHeader", () => {container.querySelector('[data-testid="bytebase-logo"]')).not.toBeNull();expect(- container.querySelector('[data-testid="project-switch-popover"]')+ container.querySelector('[data-testid="header-breadcrumb"]')).not.toBeNull();expect(container.querySelector('[data-testid="profile-menu-trigger"]')diff --git a/frontend/src/react/components/header/DashboardHeader.tsx b/frontend/src/react/components/header/DashboardHeader.tsxindex 3ea3dbce9b..150c53b674 100644--- a/frontend/src/react/components/header/DashboardHeader.tsx+++ b/frontend/src/react/components/header/DashboardHeader.tsx@@ -22,8 +22,8 @@ import {} from "@/react/router";import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";import { STORAGE_KEY_MY_ISSUES_TAB } from "@/utils/storage-keys";+import { HeaderBreadcrumb } from "./HeaderBreadcrumb";import { ProfileMenuTrigger } from "./ProfileMenuTrigger";-import { ProjectSwitchPopover } from "./ProjectSwitchPopover";export interface DashboardHeaderProps {showLogo: boolean;@@ -117,7 +117,7 @@ export function DashboardHeader({</button>) : null}- <ProjectSwitchPopover />+ <HeaderBreadcrumb /><div className="flex flex-1 items-center justify-end gap-x-2"><Buttondiff --git a/frontend/src/react/components/header/HeaderBreadcrumb.tsx b/frontend/src/react/components/header/HeaderBreadcrumb.tsxnew file mode 100644index 0000000000..cd55fe7edd--- /dev/null+++ b/frontend/src/react/components/header/HeaderBreadcrumb.tsx@@ -0,0 +1,230 @@+import { Building2, Check, ChevronDown, FolderKanban } from "lucide-react";+import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Badge } from "@/react/components/ui/badge";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/react/components/ui/popover";+import {+ useProject,+ useSubscription,+ useSwitchWorkspace,+ useWorkspace,+ useWorkspaceList,+} from "@/react/hooks/useAppState";+import {+ isValidProjectName,+ projectNamePrefix,+} from "@/react/lib/resourceName";+import { cn } from "@/react/lib/utils";+import {+ useCurrentRoute,+ useNavigate,+ WORKSPACE_ROUTE_LANDING,+} from "@/react/router";+import { useAppStore } from "@/react/stores/app";+import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";+import { ProjectCreateDialog } from "./ProjectCreateDialog";+import { ProjectSwitchPanel } from "./ProjectSwitchPanel";++function planLabel(+ t: (key: string) => string,+ plan: PlanType+): string | undefined {+ switch (plan) {+ case PlanType.FREE:+ return t("subscription.plan.free.title");+ case PlanType.TEAM:+ return t("subscription.plan.team.title");+ case PlanType.ENTERPRISE:+ return t("subscription.plan.enterprise.title");+ default:+ return undefined;+ }+}++function planVariant(+ plan: PlanType+): "default" | "secondary" | "success" | "warning" {+ switch (plan) {+ case PlanType.TEAM:+ return "default";+ case PlanType.ENTERPRISE:+ return "secondary";+ default:+ return "success";+ }+}++// ---------------------------------------------------------------------------+// WorkspaceSegment — shows workspace name + plan badge + optional dropdown+// ---------------------------------------------------------------------------+function WorkspaceSegment() {+ const { t } = useTranslation();+ const isSaaSMode = useAppStore((state) => state.isSaaSMode());+ const workspace = useWorkspace();+ const workspaceList = useWorkspaceList();+ const currentWorkspaceName = workspace?.name ?? "";+ const { subscription } = useSubscription();+ const currentPlan = subscription?.plan ?? PlanType.FREE;+ const label = planLabel(t, currentPlan);+ const hasMultiple = workspaceList.length > 1;+ const switchWorkspace = useSwitchWorkspace();+ const navigate = useNavigate();++ // Self-host has a single workspace — no need to show the workspace segment.+ if (!isSaaSMode) {+ return null;+ }++ const [open, setOpen] = useState(false);++ const onSwitch = useCallback(+ (workspaceName: string) => {+ if (workspaceName === currentWorkspaceName) return;+ setOpen(false);+ void switchWorkspace(workspaceName);+ },+ [currentWorkspaceName, switchWorkspace]+ );++ const handleNameClick = useCallback(() => {+ void navigate.push({ name: WORKSPACE_ROUTE_LANDING });+ }, [navigate]);++ return (+ <div className="inline-flex items-center">+ <button+ type="button"+ className="inline-flex items-center gap-x-1.5 rounded-xs px-2 py-1 text-sm font-medium text-control hover:bg-control-bg cursor-pointer"+ onClick={handleNameClick}+ >+ <Building2 className="size-4 text-control-light shrink-0" />+ <span className="truncate max-w-40">{workspace?.title}</span>+ {label && (+ <Badge+ variant={planVariant(currentPlan)}+ className="text-[10px] px-1.5 py-0"+ >+ {label}+ </Badge>+ )}+ </button>+ {hasMultiple && (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger+ render={+ <button+ type="button"+ className="inline-flex items-center rounded-xs p-1 text-control-placeholder hover:bg-control-bg cursor-pointer"+ />+ }+ >+ <ChevronDown className="size-3.5" />+ </PopoverTrigger>+ <PopoverContent+ align="start"+ sideOffset={6}+ className="min-w-[14rem] p-1!"+ >+ {workspaceList.map((ws) => (+ <button+ key={ws.name}+ type="button"+ className={cn(+ "w-full flex items-center justify-between rounded-xs px-3 py-1.5 text-sm cursor-pointer",+ ws.name === currentWorkspaceName+ ? "bg-control-bg font-medium text-accent"+ : "text-control hover:bg-control-bg"+ )}+ onClick={() => onSwitch(ws.name)}+ >+ <span className="truncate">{ws.title}</span>+ {ws.name === currentWorkspaceName && (+ <Check className="size-4 shrink-0" />+ )}+ </button>+ ))}+ </PopoverContent>+ </Popover>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// ProjectSegment — shows project name + dropdown, only when inside a project+// ---------------------------------------------------------------------------+function ProjectSegment({ showSeparator }: { showSeparator: boolean }) {+ const route = useCurrentRoute();+ const [open, setOpen] = useState(false);+ const [createOpen, setCreateOpen] = useState(false);+ const projectId = route.params.projectId as string | undefined;+ const currentProjectName = projectId+ ? `${projectNamePrefix}${projectId}`+ : "";+ const currentProject = useProject(currentProjectName);++ useEffect(() => {+ setOpen(false);+ }, [route.fullPath]);++ if (!isValidProjectName(currentProject?.name)) {+ return null;+ }++ return (+ <>+ {showSeparator && (+ <span className="text-control-placeholder select-none">/</span>+ )}+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger+ render={+ <button+ type="button"+ className="inline-flex items-center gap-x-1.5 rounded-xs px-2 py-1 text-sm font-medium text-control hover:bg-control-bg cursor-pointer"+ />+ }+ >+ <FolderKanban className="size-4 text-control-light shrink-0" />+ <span className="truncate max-w-48">{currentProject.title}</span>+ <ChevronDown className="size-3.5 text-control-placeholder shrink-0" />+ </PopoverTrigger>+ <PopoverContent+ align="start"+ sideOffset={6}+ className="w-[24rem] max-w-[calc(100vw-2rem)] p-0! py-3!"+ >+ <ProjectSwitchPanel+ onClose={() => setOpen(false)}+ onRequestCreate={() => {+ setOpen(false);+ setCreateOpen(true);+ }}+ />+ </PopoverContent>+ </Popover>++ <ProjectCreateDialog+ open={createOpen}+ onClose={() => setCreateOpen(false)}+ />+ </>+ );+}++// ---------------------------------------------------------------------------+// HeaderBreadcrumb — the assembled breadcrumb bar+// ---------------------------------------------------------------------------+export function HeaderBreadcrumb() {+ const isSaaSMode = useAppStore((state) => state.isSaaSMode());+ return (+ <div className="flex items-center gap-x-1">+ <WorkspaceSegment />+ <ProjectSegment showSeparator={isSaaSMode} />+ </div>+ );+}diff --git a/frontend/src/react/hooks/useAppState.ts b/frontend/src/react/hooks/useAppState.tsindex 7a137b3514..c647b5ba48 100644--- a/frontend/src/react/hooks/useAppState.ts+++ b/frontend/src/react/hooks/useAppState.ts@@ -37,6 +37,19 @@ export function useWorkspace() {return workspace;}+export function useWorkspaceList() {+ const workspaceList = useAppStore((state) => state.workspaceList);+ const loadWorkspaceList = useAppStore((state) => state.loadWorkspaceList);+ useEffect(() => {+ void loadWorkspaceList();+ }, [loadWorkspaceList]);+ return workspaceList;+}++export function useSwitchWorkspace() {+ return useAppStore((state) => state.switchWorkspace);+}+export function useSubscription() {const subscription = useAppStore((state) => state.subscription);const loadSubscription = useAppStore((state) => state.loadSubscription);diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.tsindex 4ec9563415..0d693561e6 100644--- a/frontend/src/react/stores/app/types.ts+++ b/frontend/src/react/stores/app/types.ts@@ -38,6 +38,7 @@ export type WorkspaceSlice = {serverInfoTs: number;serverInfoRequest?: Promise<ActuatorInfo | undefined>;workspace?: Workspace;+ workspaceList: Workspace[];workspaceRequest?: Promise<Workspace | undefined>;workspaceProfile?: WorkspaceProfileSetting;workspaceProfileRequest?: Promise<WorkspaceProfileSetting | undefined>;@@ -49,6 +50,8 @@ export type WorkspaceSlice = {loadServerInfo: () => Promise<ActuatorInfo | undefined>;refreshServerInfo: () => Promise<ActuatorInfo | undefined>;loadWorkspace: () => Promise<Workspace | undefined>;+ loadWorkspaceList: () => Promise<Workspace[]>;+ switchWorkspace: (workspaceName: string) => Promise<void>;loadWorkspaceProfile: () => Promise<WorkspaceProfileSetting | undefined>;loadEnvironmentList: (force?: boolean) => Promise<Environment[]>;refreshEnvironmentList: () => Promise<Environment[]>;diff --git a/frontend/src/react/stores/app/workspace.ts b/frontend/src/react/stores/app/workspace.tsindex e3269c2828..652689ac88 100644--- a/frontend/src/react/stores/app/workspace.ts+++ b/frontend/src/react/stores/app/workspace.ts@@ -3,6 +3,7 @@ import dayjs from "dayjs";import semver from "semver";import {actuatorServiceClientConnect,+ authServiceClientConnect,settingServiceClientConnect,subscriptionServiceClientConnect,workspaceServiceClientConnect,@@ -19,6 +20,7 @@ import {instanceLimitFeature,PLANS,} from "@/types/plan";+import { SwitchWorkspaceRequestSchema } from "@/types/proto-es/v1/auth_service_pb";import {DatabaseChangeMode,type EnvironmentSetting_Environment,@@ -40,6 +42,12 @@ import type { Environment } from "@/types/v1/environment";import { formatAbsoluteDateTime } from "@/utils/datetime";import type { AppSliceCreator, WorkspaceSlice } from "./types";+// Notify other tabs when the user switches workspace.+const workspaceSwitchChannel = new BroadcastChannel("bb-workspace-switch");+workspaceSwitchChannel.onmessage = () => {+ window.location.href = "/";+};+const workspaceProfileSettingName = `${settingNamePrefix}${Setting_SettingName[Setting_SettingName.WORKSPACE_PROFILE]}`;@@ -93,6 +101,7 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (get) => ({serverInfoTs: 0,+ workspaceList: [],environmentList: [],appFeatures: defaultAppProfile().features,@@ -151,6 +160,25 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (return request;},+ loadWorkspaceList: async () => {+ const resp = await workspaceServiceClientConnect.listWorkspaces({});+ set({ workspaceList: resp.workspaces });+ return resp.workspaces;+ },++ switchWorkspace: async (workspaceName: string) => {+ await authServiceClientConnect.switchWorkspace(+ createProto(SwitchWorkspaceRequestSchema, {+ workspace: workspaceName,+ web: true,+ })+ );+ // Notify other tabs to reload with the new workspace.+ workspaceSwitchChannel.postMessage(workspaceName);+ // Full-reload to the landing page to reset all frontend state.+ window.location.href = "/";+ },+loadWorkspaceProfile: async () => {const existing = get().workspaceProfile;if (existing) return existing;diff --git a/frontend/src/store/modules/v1/workspace.ts b/frontend/src/store/modules/v1/workspace.tsindex 8990136064..cdf8c7e2ab 100644--- a/frontend/src/store/modules/v1/workspace.ts+++ b/frontend/src/store/modules/v1/workspace.ts@@ -7,6 +7,8 @@ import {authServiceClientConnect,workspaceServiceClientConnect,} from "@/connect";+import { router } from "@/router";+import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";import { userNamePrefix, workspaceNamePrefix } from "@/store/modules/v1/common";import { ALL_USERS_USER_EMAIL } from "@/types";import { SwitchWorkspaceRequestSchema } from "@/types/proto-es/v1/auth_service_pb";@@ -26,8 +28,10 @@ import { composePolicyBindings } from "./projectIamPolicy";// Notify other tabs when the user switches workspace.const workspaceSwitchChannel = new BroadcastChannel("bb-workspace-switch");workspaceSwitchChannel.onmessage = () => {- // Another tab switched workspace — reload to pick up the new cookie.- window.location.reload();+ // Another tab switched workspace — full-reload to the landing page+ // to pick up the new cookie and reset all frontend state.+ const landingPath = router.resolve({ name: WORKSPACE_ROUTE_LANDING }).href;+ window.location.href = landingPath;};export const useWorkspaceV1Store = defineStore("workspace_v1", () => {@@ -238,8 +242,11 @@ export const useWorkspaceV1Store = defineStore("workspace_v1", () => {);// Notify other tabs to reload with the new workspace.workspaceSwitchChannel.postMessage(workspaceName);- // Full page reload to reset all frontend state with new workspace context.- window.location.reload();+ // Full-reload to the landing page to reset all frontend state.+ // Reloading the current URL would fail if the page is project-scoped+ // (the project likely doesn't exist in the target workspace).+ const landingPath = router.resolve({ name: WORKSPACE_ROUTE_LANDING }).href;+ window.location.href = landingPath;};return {