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(frontend): consolidate environment rendering into shared EnvironmentLabel (#19802)
Danny Xue082cdee532c
diff --git a/frontend/src/react/components/EnvironmentLabel.tsx b/frontend/src/react/components/EnvironmentLabel.tsxnew file mode 100644index 0000000000..edbb516a18--- /dev/null+++ b/frontend/src/react/components/EnvironmentLabel.tsx@@ -0,0 +1,81 @@+import { ShieldAlert } from "lucide-react";+import { useTranslation } from "react-i18next";+import { useVueState } from "@/react/hooks/useVueState";+import { cn } from "@/react/lib/utils";+import { featureToRef, useEnvironmentV1Store } from "@/store";+import type { Environment } from "@/types";+import { NULL_ENVIRONMENT_NAME, UNKNOWN_ENVIRONMENT_NAME } from "@/types";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import { hexToRgb } from "@/utils";++/**+ * Renders an environment as a colored pill with optional shield icon+ * for protected environments.+ *+ * Two usage modes:+ * - Pass `environment` object directly (avoids store lookup)+ * - Pass `environmentName` string (looks up from environment store)+ */+export function EnvironmentLabel({+ environment: envProp,+ environmentName,+ className,+}: {+ environment?: Environment;+ environmentName?: string;+ className?: string;+}) {+ const { t } = useTranslation();+ const environmentStore = useEnvironmentV1Store();++ // Always called (rules of hooks); result ignored when envProp is provided.+ const envFromStore = useVueState(() =>+ environmentStore.getEnvironmentByName(+ environmentName || NULL_ENVIRONMENT_NAME+ )+ );++ const environment = envProp ?? envFromStore;++ const isUnset =+ environment.name === UNKNOWN_ENVIRONMENT_NAME ||+ environment.name === NULL_ENVIRONMENT_NAME;++ const hasEnvTierFeature = useVueState(+ () => featureToRef(PlanFeature.FEATURE_ENVIRONMENT_TIERS).value+ );+ const isProtected =+ hasEnvTierFeature && environment.tags?.protected === "protected";++ const bgColorRgb = environment.color ? hexToRgb(environment.color) : null;++ return (+ <span+ className={cn(+ "inline-flex items-center gap-x-1 px-1.5 rounded truncate",+ className+ )}+ style={+ bgColorRgb && !isUnset+ ? {+ backgroundColor: `rgba(${bgColorRgb.join(", ")}, 0.1)`,+ color: `rgb(${bgColorRgb.join(", ")})`,+ }+ : undefined+ }+ >+ <span className="truncate">+ {isUnset ? (+ <span className="text-control-light italic">+ {t("common.unassigned")}+ </span>+ ) : (+ environment.title+ )}+ </span>+ {isProtected && !isUnset && (+ <ShieldAlert className="w-3.5 h-3.5 shrink-0 text-current" />+ )}+ </span>+ );+}diff --git a/frontend/src/react/components/ExprEditor.tsx b/frontend/src/react/components/ExprEditor.tsxindex 65d4403bff..e320c11426 100644--- a/frontend/src/react/components/ExprEditor.tsx+++ b/frontend/src/react/components/ExprEditor.tsx@@ -1,4 +1,5 @@import { Plus, X } from "lucide-react";+import type { ReactNode } from "react";import {createContext,useCallback,@@ -34,6 +35,7 @@ import {isTimestampFactor,LogicalOperatorList,} from "@/plugins/cel";+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";import { Input } from "@/react/components/ui/input";import {Select,@@ -42,6 +44,8 @@ import {SelectTrigger,SelectValue,} from "@/react/components/ui/select";+import { environmentNamePrefix } from "@/store/modules/v1/common";+import { CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID } from "@/utils/cel-attributes";// Re-export OptionConfig so consumers can import from one place.export type { OptionConfig } from "@/components/ExprEditor/context";@@ -539,12 +543,14 @@ function TagInput({function MultiCheckSelect({value,options,+ renderValue,disabled,placeholder,onChange,}: {value: string[];options: { label: string; value: string }[];+ renderValue?: (value: string, fallbackLabel?: string) => ReactNode;disabled?: boolean;placeholder?: string;onChange: (value: string[]) => void;@@ -599,7 +605,9 @@ function MultiCheckSelect({key={v}className="inline-flex items-center gap-1 bg-gray-100 text-xs px-1.5 py-0.5 rounded">- {getLabelForValue(v)}+ {renderValue+ ? renderValue(v, getLabelForValue(v))+ : getLabelForValue(v)}{!disabled && (<spanrole="button"@@ -645,7 +653,7 @@ function MultiCheckSelect({checked={value.includes(o.value)}onChange={() => toggleValue(o.value)}/>- {o.label}+ {renderValue ? renderValue(o.value, o.label) : o.label}</label>))}</div>@@ -792,6 +800,18 @@ function ValueInput({[optionConfigMap, factor]);+ const isEnvironment = factor === CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID;+ const renderOptionValue = (value: string, fallbackLabel?: string) => {+ if (isEnvironment) {+ return (+ <EnvironmentLabel+ environmentName={`${environmentNamePrefix}${value}`}+ />+ );+ }+ return fallbackLabel ?? value;+ };+const hasOption = optionConfig.options.length > 0 || !!optionConfig.search;type InputType = "INPUT" | "SINGLE-SELECT" | "MULTI-SELECT" | "MULTI-INPUT";@@ -918,14 +938,14 @@ function ValueInput({{(value: string | null) => {if (!value) return null;const found = optionConfig.options.find((o) => o.value === value);- return found?.label ?? value;+ return renderOptionValue(value, found?.label);}}</SelectValue></SelectTrigger><SelectContent>{optionConfig.options.map((o) => (<SelectItem key={o.value as string} value={o.value as string}>- {o.label}+ {renderOptionValue(o.value as string, o.label)}</SelectItem>))}</SelectContent>@@ -949,6 +969,7 @@ function ValueInput({<MultiCheckSelectvalue={getArrayValue()}options={optionConfig.options as { label: string; value: string }[]}+ renderValue={isEnvironment ? renderOptionValue : undefined}disabled={readonly}placeholder={t("cel.condition.select-value")}onChange={setArrayValue}diff --git a/frontend/src/react/hooks/useVueState.ts b/frontend/src/react/hooks/useVueState.tsindex 66bcc3ea51..52dc3dd40a 100644--- a/frontend/src/react/hooks/useVueState.ts+++ b/frontend/src/react/hooks/useVueState.ts@@ -3,7 +3,8 @@ import { watch } from "vue";/*** Subscribe a React component to a Vue reactive getter.- * Re-renders whenever the getter's tracked dependencies change.+ * Re-renders whenever the getter's tracked dependencies change,+ * AND whenever the getter's closure variables (e.g. props) change.** @param getter — A function that reads Vue reactive state (Pinia store, ref, computed, etc.)* @returns The current value of the getter, kept in sync with Vue reactivity.@@ -16,24 +17,33 @@ export function useVueState<T>(getter: () => T): T {// between renders when the value hasn't changed.const snapshotRef = useRef<T>(getter());- const subscribe = useCallback(- (onStoreChange: () => void) => {- const stop = watch(- getter,- (newVal) => {- snapshotRef.current = newVal;- onStoreChange();- },- { flush: "sync" }- );- // Initialize with current value- snapshotRef.current = getter();- return stop;- },- // getter is typically an inline arrow — we intentionally omit it from deps- // to keep subscribe stable. The watch() inside tracks Vue deps automatically.- []- );+ // Always point to the latest getter so the Vue watch evaluates+ // up-to-date closure variables (props, local state, etc.).+ const getterRef = useRef(getter);+ getterRef.current = getter;++ const subscribe = useCallback((onStoreChange: () => void) => {+ const stop = watch(+ () => getterRef.current(),+ (newVal) => {+ snapshotRef.current = newVal;+ onStoreChange();+ },+ { flush: "sync" }+ );+ // Initialize with current value+ snapshotRef.current = getterRef.current();+ return stop;+ }, []);++ // Re-evaluate getter on every render to catch closure-driven changes+ // (e.g. a prop like environmentName changing from "prod" to "test").+ // The Vue watch only fires for Vue reactive dep changes — it cannot+ // detect plain JS closure variable changes, so we sync here.+ const currentValue = getter();+ if (!Object.is(snapshotRef.current, currentValue)) {+ snapshotRef.current = currentValue;+ }const getSnapshot = useCallback(() => snapshotRef.current, []);diff --git a/frontend/src/react/pages/settings/EnvironmentsPage.tsx b/frontend/src/react/pages/settings/EnvironmentsPage.tsxindex 82e04bfe8c..1ec5b0cdf5 100644--- a/frontend/src/react/pages/settings/EnvironmentsPage.tsx+++ b/frontend/src/react/pages/settings/EnvironmentsPage.tsx@@ -1,6 +1,6 @@import { create } from "@bufbuild/protobuf";import { cloneDeep, isEqual } from "lodash-es";-import { GripVertical, ListOrdered, Plus, ShieldAlert, X } from "lucide-react";+import { GripVertical, ListOrdered, Plus, X } from "lucide-react";import {forwardRef,useCallback,@@ -11,6 +11,7 @@ import {useState,} from "react";import { useTranslation } from "react-i18next";+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";import { FeatureAttention } from "@/react/components/FeatureAttention";import { ResourceIdField } from "@/react/components/ResourceIdField";import { Button } from "@/react/components/ui/button";@@ -56,7 +57,6 @@ import type { Environment } from "@/types/v1/environment";import {displayRoleTitle,hasWorkspacePermissionV2,- hexToRgb,sqlReviewPolicySlug,} from "@/utils";@@ -85,60 +85,6 @@ function useEscapeKey(onEscape: () => void) {}, [onEscape]);}-// ============================================================-// EnvironmentName - displays env name with color badge-// ============================================================-function EnvironmentName({- environment,- link = false,-}: {- environment: Environment;- link?: boolean;-}) {- const subscriptionStore = useSubscriptionV1Store();- const hasEnvTierFeature = useVueState(() =>- subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_ENVIRONMENT_TIERS)- );- const color = environment.color || "#4f46e5";- const rgbValues = hexToRgb(color);- const rgbStr = rgbValues.join(", ");- const showProductionIcon =- hasEnvTierFeature && environment.tags?.protected === "protected";-- const content = (- <span- className="inline-flex items-center gap-x-1 px-1.5 rounded select-none truncate"- style={{- backgroundColor: `rgba(${rgbStr}, 0.1)`,- color: `rgb(${rgbStr})`,- }}- >- <span className="truncate">{environment.title}</span>- {showProductionIcon && (- <ShieldAlert className="w-3.5 h-3.5 shrink-0 text-control" />- )}- </span>- );-- if (link) {- return (- <a- href={`/${formatEnvironmentName(environment.id)}`}- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- router.push({ path: `/${formatEnvironmentName(environment.id)}` });- }}- className="hover:underline"- >- {content}- </a>- );- }-- return content;-}-// ============================================================// Toggle switch// ============================================================@@ -1231,7 +1177,7 @@ function ReorderDrawer({><div className="flex items-center gap-x-2"><span className="textinfo">{index + 1}.</span>- <EnvironmentName environment={env} />+ <EnvironmentLabel environment={env} /></div><GripVertical className="w-5 h-5 text-gray-500" /></div>@@ -1436,7 +1382,7 @@ export function EnvironmentsPage() {onClick={() => selectTab(env.id)}><span className="text-opacity-60">{index + 1}.</span>- <EnvironmentName environment={env} />+ <EnvironmentLabel environment={env} /></button>))}</div>diff --git a/frontend/src/react/pages/settings/InstancesPage.tsx b/frontend/src/react/pages/settings/InstancesPage.tsxindex 0e02471d73..5bead4de48 100644--- a/frontend/src/react/pages/settings/InstancesPage.tsx+++ b/frontend/src/react/pages/settings/InstancesPage.tsx@@ -9,6 +9,7 @@ import {Plus,RefreshCw,SquareStack,+ X,} from "lucide-react";import type { RefObject } from "react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";@@ -20,13 +21,13 @@ import {type ScopeOption,type SearchParams,} from "@/react/components/AdvancedSearch";+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";import { Button } from "@/react/components/ui/button";import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";import { router } from "@/router";import { INSTANCE_ROUTE_CREATE } from "@/router/dashboard/instance";import {- featureToRef,pushNotification,useActuatorV1Store,useCurrentUserV1,@@ -39,22 +40,17 @@ import { environmentNamePrefix } from "@/store/modules/v1/common";import type { InstanceFilter } from "@/store/modules/v1/instance";import {isValidInstanceName,- NULL_ENVIRONMENT_NAME,UNKNOWN_ENVIRONMENT_NAME,unknownEnvironment,} from "@/types";import { Engine, State } from "@/types/proto-es/v1/common_pb";import type { Instance } from "@/types/proto-es/v1/instance_service_pb";import { UpdateInstanceRequestSchema } from "@/types/proto-es/v1/instance_service_pb";-import {- PlanFeature,- PlanType,-} from "@/types/proto-es/v1/subscription_service_pb";+import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";import {engineNameV1,getDefaultPagination,hasWorkspacePermissionV2,- hexToRgb,hostPortOfDataSource,hostPortOfInstanceV1,supportedEngineV1List,@@ -209,71 +205,6 @@ function ConfirmDialog({);}-// ============================================================-// EnvironmentName-// ============================================================--function EnvironmentName({ environmentName }: { environmentName: string }) {- const { t } = useTranslation();- const environmentStore = useEnvironmentV1Store();- const environment = useVueState(() =>- environmentStore.getEnvironmentByName(- environmentName || NULL_ENVIRONMENT_NAME- )- );-- const isUnset =- environment.name === UNKNOWN_ENVIRONMENT_NAME ||- environment.name === NULL_ENVIRONMENT_NAME;-- const hasEnvTierFeature = useVueState(- () => featureToRef(PlanFeature.FEATURE_ENVIRONMENT_TIERS).value- );- const isProtected =- hasEnvTierFeature && environment.tags?.protected === "protected";-- const bgColorRgb = environment.color ? hexToRgb(environment.color) : null;-- return (- <span- className="inline-flex items-center gap-x-1"- style={- bgColorRgb && !isUnset- ? {- backgroundColor: `rgba(${bgColorRgb.join(", ")}, 0.1)`,- color: `rgb(${bgColorRgb.join(", ")})`,- padding: "0 6px",- borderRadius: "4px",- }- : undefined- }- >- <span className="truncate">- {isUnset ? (- <span className="text-control-light italic">- {t("common.unassigned")}- </span>- ) : (- environment.title- )}- </span>- {isProtected && !isUnset && (- <svg- className="w-4 h-4 shrink-0 text-current"- viewBox="0 0 20 20"- fill="currentColor"- >- <path- fillRule="evenodd"- d="M10 1.944A11.954 11.954 0 012.166 5C2.056 5.649 2 6.319 2 7c0 5.225 3.34 9.67 8 11.317C14.66 16.67 18 12.225 18 7c0-.682-.057-1.351-.166-2.001A11.954 11.954 0 0110 1.944zM11 14a1 1 0 11-2 0 1 1 0 012 0zm0-7a1 1 0 10-2 0v3a1 1 0 102 0V7z"- clipRule="evenodd"- />- </svg>- )}- </span>- );-}-// ============================================================// InstanceActionDropdown// ============================================================@@ -503,9 +434,13 @@ function EditEnvironmentDrawer({() => environmentStore.environmentList ?? []);const [selected, setSelected] = useState("");+ const [updating, setUpdating] = useState(false);useEscapeKey(open, onClose);useEffect(() => {- if (open) setSelected("");+ if (open) {+ setSelected("");+ setUpdating(false);+ }}, [open]);if (!open) return null;@@ -519,16 +454,16 @@ function EditEnvironmentDrawer({{t("database.edit-environment")}</h2><button className="p-1 hover:bg-control-bg rounded" onClick={onClose}>- ×+ <X className="w-4 h-4" /></button></div><div className="flex-1 overflow-y-auto p-6">- <div className="flex flex-col gap-y-2">+ <div className="flex flex-col gap-y-1">{environments.map((env) => (<labelkey={env.name}className={cn(- "flex items-center gap-x-3 px-3 py-2 rounded cursor-pointer border",+ "flex items-center gap-x-3 px-3 py-2.5 rounded-lg cursor-pointer border transition-colors",selected === env.name? "border-accent bg-accent/5": "border-transparent hover:bg-gray-50"@@ -541,15 +476,7 @@ function EditEnvironmentDrawer({onChange={() => setSelected(env.name)}className="accent-accent"/>- <div className="flex items-center gap-x-2">- {env.color && (- <span- className="inline-block w-3 h-3 rounded-full"- style={{ backgroundColor: env.color }}- />- )}- <span>{env.title}</span>- </div>+ <EnvironmentLabel environment={env} /></label>))}</div>@@ -559,10 +486,15 @@ function EditEnvironmentDrawer({{t("common.cancel")}</Button><Button- disabled={!selected}+ disabled={!selected || updating}onClick={async () => {- await onUpdate(selected);- onClose();+ setUpdating(true);+ try {+ await onUpdate(selected);+ onClose();+ } finally {+ setUpdating(false);+ }}}>{t("common.confirm")}@@ -1274,7 +1206,7 @@ export function InstancesPage() {</div></td><td className="px-4 py-2">- <EnvironmentName+ <EnvironmentLabelenvironmentName={instance.environment ?? ""}/></td>