Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(frontend): migrate global masking page to React (#19770)
Danny Xu59a09cfd53bf
diff --git a/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue b/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vuedeleted file mode 100644index 4895c18fec..0000000000--- a/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue+++ /dev/null@@ -1,408 +0,0 @@-<template>- <div class="w-full flex flex-col gap-y-4">- <div class="flex flex-row items-center justify-end">- <div v-if="state.reorderRules" class="flex items-center gap-x-2">- <NButton- :disabled="state.processing"- @click="- () => {- state.reorderRules = false;- updateList();- }- "- >- {{ $t("common.cancel") }}- </NButton>- <NButton- type="primary"- :disabled="state.processing"- @click="onReorderSubmit"- >- {{ $t("common.confirm") }}- </NButton>- </div>- <PermissionGuardWrapper- v-else- v-slot="slotProps"- :permissions="['bb.policies.updateMaskingRulePolicy']"- >- <div class="flex items-center gap-x-2">- <NButton- class="capitalize"- :disabled="- slotProps.disabled ||- !hasSensitiveDataFeature ||- state.maskingRuleItemList.length <= 1- "- @click="state.reorderRules = true"- >- <template #icon>- <ListOrderedIcon class="h-4 w-4" />- </template>- {{ $t("settings.sensitive-data.global-rules.re-order") }}- </NButton>- <NButton- type="primary"- :disabled="slotProps.disabled || !hasSensitiveDataFeature"- @click="addNewRule"- >- <template #icon>- <PlusIcon class="h-4 w-4" />- </template>- {{ $t("common.add") }}- </NButton>- </div>- </PermissionGuardWrapper>- </div>- <div class="textinfolabel">- {{ $t("settings.sensitive-data.global-rules.description") }}- <LearnMoreLink- url="https://docs.bytebase.com/security/data-masking/overview/?source=console"- />- </div>- <NEmpty- class="py-12 border rounded-sm"- v-if="state.maskingRuleItemList.length === 0"- />- <div- v-for="(item, index) in state.maskingRuleItemList"- :key="item.rule.id"- class="flex items-start gap-x-5"- >- <div- v-if="- item.mode === 'NORMAL' && hasPermission && hasSensitiveDataFeature- "- >- <div v-if="state.reorderRules" class="pt-2 flex flex-col">- <MiniActionButton v-if="index > 0" @click="onReorder(item, -1)">- <ChevronUpIcon class="w-4 h-4" />- </MiniActionButton>- <MiniActionButton- v-if="index !== state.maskingRuleItemList.length - 1"- @click="onReorder(item, 1)"- >- <ChevronDownIcon class="w-4 h-4" />- </MiniActionButton>- </div>- <div v-else class="pt-2">- <MiniActionButton @click="onEdit(index)">- <PencilIcon class="w-4 h-4" />- </MiniActionButton>- </div>- </div>- <div- class="pb-5"- :class="[- 'w-full',- item.mode === 'NORMAL' ? '' : 'ml-10.5',- index === state.maskingRuleItemList.length - 1 ? '' : 'border-b',- ]"- >- <MaskingRuleConfig- :key="`expr-${item.rule.id}`"- :index="index + 1"- :disabled="state.processing"- :masking-rule="item.rule"- :readonly="item.mode === 'NORMAL' || state.reorderRules"- :factor-list="factorList"- :option-config-map="factorOptionsMap"- :allow-delete="item.mode === 'EDIT'"- @cancel="onCancel(index)"- @delete="onRuleDelete(index)"- @confirm="(rule: MaskingRulePolicy_MaskingRule) => onConfirm(rule)"- />- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import {- ChevronDownIcon,- ChevronUpIcon,- ListOrderedIcon,- PencilIcon,- PlusIcon,-} from "lucide-vue-next";-import { NButton, NEmpty } from "naive-ui";-import { v4 as uuidv4 } from "uuid";-import { computed, nextTick, onMounted, reactive, ref } from "vue";-import { useI18n } from "vue-i18n";-import { type OptionConfig } from "@/components/ExprEditor/context";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";-import { useBodyLayoutContext } from "@/layouts/common";-import type { Factor } from "@/plugins/cel";-import {- featureToRef,- pushNotification,- useActuatorV1Store,- usePolicyV1Store,- useSettingV1Store,-} from "@/store";-import type {- MaskingRulePolicy_MaskingRule,- Policy,-} from "@/types/proto-es/v1/org_policy_service_pb";-import {- MaskingRulePolicy_MaskingRuleSchema,- MaskingRulePolicySchema,- PolicyResourceType,- PolicyType,-} from "@/types/proto-es/v1/org_policy_service_pb";-import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import {- arraySwap,- getDatabaseIdOptionConfig,- getEnvironmentIdOptions,- getInstanceIdOptionConfig,- getProjectIdOptionConfig,- hasWorkspacePermissionV2,-} from "@/utils";-import {- CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL,- CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,- CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,- CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID,- CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID,- CEL_ATTRIBUTE_RESOURCE_PROJECT_ID,- CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,-} from "@/utils/cel-attributes";-import LearnMoreLink from "../LearnMoreLink.vue";-import { MiniActionButton } from "../v2";-import MaskingRuleConfig from "./components/MaskingRuleConfig.vue";-import { getClassificationLevelOptions } from "./components/utils";--type MaskingRuleMode = "NORMAL" | "EDIT" | "CREATE";--interface MaskingRuleItem {- mode: MaskingRuleMode;- rule: MaskingRulePolicy_MaskingRule;-}--interface LocalState {- maskingRuleItemList: MaskingRuleItem[];- processing: boolean;- reorderRules: boolean;-}-const { t } = useI18n();-const state = reactive<LocalState>({- maskingRuleItemList: [],- processing: false,- reorderRules: false,-});--const policyStore = usePolicyV1Store();-const actuatorStore = useActuatorV1Store();-const hasPermission = computed(() => {- return hasWorkspacePermissionV2("bb.policies.updateMaskingRulePolicy");-});--const hasSensitiveDataFeature = featureToRef(PlanFeature.FEATURE_DATA_MASKING);-const layout = {- mainContainerRef: ref<HTMLDivElement>(),-};-layout.mainContainerRef = useBodyLayoutContext().mainContainerRef;--const updateList = async () => {- const policy = await policyStore.getOrFetchPolicyByParentAndType({- parentPath: actuatorStore.workspaceResourceName,- policyType: PolicyType.MASKING_RULE,- });- if (!policy) {- return;- }-- state.maskingRuleItemList = (- policy.policy?.case === "maskingRulePolicy" ? policy.policy.value.rules : []- ).map((rule) => {- return {- mode: "NORMAL",- rule,- };- });-};--onMounted(async () => {- await updateList();- const settingV1Store = useSettingV1Store();- await Promise.all([- settingV1Store.getOrFetchSettingByName(- Setting_SettingName.SEMANTIC_TYPES,- true- ),- settingV1Store.getOrFetchSettingByName(- Setting_SettingName.DATA_CLASSIFICATION,- true- ),- ]);-});--const addNewRule = () => {- state.maskingRuleItemList.push({- mode: "CREATE",- rule: create(MaskingRulePolicy_MaskingRuleSchema, {- id: uuidv4(),- }),- });- nextTick(() => {- layout.mainContainerRef.value?.scrollTo(- 0,- document.body.scrollHeight || document.documentElement.scrollHeight- );- });-};--const onEdit = (index: number) => {- state.maskingRuleItemList[index].mode = "EDIT";-};--const onCancel = (index: number) => {- const item = state.maskingRuleItemList[index];-- if (item.mode === "CREATE") {- state.maskingRuleItemList.splice(index, 1);- } else {- state.maskingRuleItemList[index] = {- ...item,- mode: "NORMAL",- };- }-};--const onConfirm = async (rule: MaskingRulePolicy_MaskingRule) => {- if (state.processing) {- return;- }-- const index = state.maskingRuleItemList.findIndex(- (item) => item.rule.id === rule.id- );- if (index < 0) {- return;- }-- state.processing = true;- const isCreate = state.maskingRuleItemList[index].mode === "CREATE";-- state.maskingRuleItemList[index] = {- mode: "NORMAL",- rule,- };- try {- await onPolicyUpsert();- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t(`common.${isCreate ? "created" : "updated"}`),- });- } finally {- state.processing = false;- }-};--const onReorder = (maskingRuleItem: MaskingRuleItem, offset: number) => {- const index = state.maskingRuleItemList.findIndex(- (item) => item.rule.id === maskingRuleItem.rule.id- );- if (index < 0) {- return;- }-- arraySwap(state.maskingRuleItemList, index, index + offset);-};--const onReorderSubmit = async () => {- await onPolicyUpsert();- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- state.reorderRules = false;-};--const onRuleDelete = async (index: number) => {- const item = state.maskingRuleItemList[index];-- state.maskingRuleItemList.splice(index, 1);- if (item.mode === "CREATE") {- return;- }-- await onPolicyUpsert();- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.deleted"),- });-};--const onPolicyUpsert = async () => {- const patch: Partial<Policy> = {- type: PolicyType.MASKING_RULE,- resourceType: PolicyResourceType.WORKSPACE,- policy: {- case: "maskingRulePolicy",- value: create(MaskingRulePolicySchema, {- rules: state.maskingRuleItemList- .filter((item) => item.mode === "NORMAL")- .map((item) => item.rule),- }),- },- };-- await policyStore.upsertPolicy({- parentPath: actuatorStore.workspaceResourceName,- policy: patch,- });-};--const factorList = computed((): Factor[] => {- const list: Factor[] = [- CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID,- CEL_ATTRIBUTE_RESOURCE_PROJECT_ID,- CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID,- CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,- CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,- CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,- CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL,- ];-- return list;-});--const factorOptionsMap = computed((): Map<Factor, OptionConfig> => {- return factorList.value.reduce((map, factor) => {- let options: ResourceSelectOption<unknown>[] = [];- switch (factor) {- case CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID:- options = getEnvironmentIdOptions();- break;- case CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID:- map.set(factor, getInstanceIdOptionConfig());- return map;- case CEL_ATTRIBUTE_RESOURCE_PROJECT_ID:- map.set(factor, getProjectIdOptionConfig());- return map;- case CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL:- options = getClassificationLevelOptions();- break;- case CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME: {- map.set(- factor,- getDatabaseIdOptionConfig(actuatorStore.workspaceResourceName)- );- return map;- }- }- map.set(factor, {- options,- });- return map;- }, new Map<Factor, OptionConfig>());-});-</script>diff --git a/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue b/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vuedeleted file mode 100644index 245779de7d..0000000000--- a/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue+++ /dev/null@@ -1,252 +0,0 @@-<template>- <div class="flex flex-col gap-y-4 w-full">- <div- class="flex flex-col md:flex-row items-start md:items-stretch gap-x-4 gap-y-4 overflow-hidden"- >- <div- class="flex-1 flex flex-col gap-y-2 overflow-x-hidden overflow-y-auto"- >- <div class="flex items-center h-9">- <NInput- v-if="!readonly"- v-model:value="state.title"- class="w-64!"- :placeholder="defaultTitle"- type="text"- size="small"- :disabled="disabled"- @input="state.dirty = true"- />- <h3 v-else class="font-medium text-sm text-main">- {{ state.title || defaultTitle }}- </h3>- </div>- <ExprEditor- :expr="state.expr"- :readonly="readonly"- :factor-list="factorList"- :option-config-map="optionConfigMap"- :factor-operator-override-map="factorOperatorOverrideMap"- @update="state.dirty = true"- />- </div>- <div>- <h3 class="font-medium text-sm text-main py-2">- {{ $t("settings.sensitive-data.semantic-types.table.semantic-type") }}- </h3>- <NSelect- v-model:value="state.semanticType"- style="min-width: 10rem"- :filterable="true"- :options="options"- :filter="filterByTitle"- :placeholder="$t('settings.sensitive-data.semantic-types.select')"- :consistent-menu-width="false"- :disabled="disabled || readonly"- @update:value="state.dirty = true"- />- </div>- </div>- <div v-if="!readonly" class="flex justify-between items-center">- <NPopconfirm v-if="allowDelete" @positive-click="$emit('delete')">- <template #trigger>- <NButton- quaternary- type="error"- tag="div"- style="--n-padding: 0 6px; --n-icon-margin: 4px"- :disabled="disabled"- @click.stop=""- >- <template #icon>- <TrashIcon class="w-3.5 h-3.5" />- </template>- {{ $t("common.delete") }}- </NButton>- </template>- <div class="whitespace-nowrap">- {{ $t("settings.sensitive-data.global-rules.delete-rule-tip") }}- </div>- </NPopconfirm>- <div class="flex justify-end gap-x-2 ml-auto">- <NButton :disabled="disabled" @click="onCancel">- {{ $t("common.cancel") }}- </NButton>- <NTooltip :disabled="errorMessages.length === 0">- <template #trigger>- <NButton- type="primary"- :disabled="errorMessages.length !== 0 || disabled || !state.dirty"- @click="onConfirm"- >- {{ $t("common.confirm") }}- </NButton>- </template>- <ul class="list-disc pl-4">- <li v-for="(msg, i) in errorMessages" :key="i">- {{ msg }}- </li>- </ul>- </NTooltip>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { head } from "lodash-es";-import { TrashIcon } from "lucide-vue-next";-import type { SelectOption } from "naive-ui";-import { NButton, NInput, NPopconfirm, NSelect, NTooltip } from "naive-ui";-import { computed, nextTick, onMounted, reactive } from "vue";-import { useI18n } from "vue-i18n";-import ExprEditor from "@/components/ExprEditor";-import { type OptionConfig } from "@/components/ExprEditor/context";-import type { ConditionGroupExpr, Factor, SimpleExpr } from "@/plugins/cel";-import {- buildCELExpr,- emptySimpleExpr,- resolveCELExpr,- validateSimpleExpr,- wrapAsGroup,-} from "@/plugins/cel";-import { useSettingV1Store } from "@/store";-import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";-import type { MaskingRulePolicy_MaskingRule } from "@/types/proto-es/v1/org_policy_service_pb";-import type { SemanticTypeSetting_SemanticType as SemanticType } from "@/types/proto-es/v1/setting_service_pb";-import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";-import {- batchConvertCELStringToParsedExpr,- batchConvertParsedExprToCELString,-} from "@/utils";-import { factorOperatorOverrideMap } from "./utils";--export interface SemanticTypeSelectOption extends SelectOption {- value: string;- semanticType: SemanticType;-}--const props = defineProps<{- index: number;- readonly: boolean;- disabled: boolean;- allowDelete: boolean;- factorList: Factor[];- optionConfigMap: Map<Factor, OptionConfig>;- maskingRule: MaskingRulePolicy_MaskingRule;-}>();--const emit = defineEmits<{- (event: "cancel"): void;- (event: "delete"): void;- (event: "confirm", rule: MaskingRulePolicy_MaskingRule): void;-}>();--type LocalState = {- title: string;- expr: ConditionGroupExpr;- semanticType?: string;- dirty: boolean;-};--const { t } = useI18n();-const state = reactive<LocalState>({- title: "",- expr: wrapAsGroup(emptySimpleExpr()),- dirty: false,-});-const settingStore = useSettingV1Store();--const errorMessages = computed(() => {- const msg: string[] = [];- if (!state.semanticType) {- msg.push(- t("settings.sensitive-data.global-rules.error.missing-semantic-type")- );- }- if (!validateSimpleExpr(state.expr)) {- msg.push(t("settings.sensitive-data.global-rules.error.invalid-condition"));- }- return msg;-});--const semanticTypeSettingValue = computed(() => {- const semanticTypeSetting = settingStore.getSettingByName(- Setting_SettingName.SEMANTIC_TYPES- );- if (semanticTypeSetting?.value?.value?.case === "semanticType") {- return semanticTypeSetting.value.value.value.types ?? [];- }- return [];-});--const options = computed(() => {- return semanticTypeSettingValue.value.map<SemanticTypeSelectOption>(- (semanticType) => ({- value: semanticType.id,- label: semanticType.title,- semanticType,- })- );-});--const filterByTitle = (pattern: string, option: SelectOption) => {- const { semanticType } = option as SemanticTypeSelectOption;- pattern = pattern.toLowerCase();- return semanticType.title.toLowerCase().includes(pattern);-};--const resetLocalState = async (rule: MaskingRulePolicy_MaskingRule) => {- let expr: SimpleExpr = emptySimpleExpr();- if (rule.condition?.expression) {- const parsedExprs = await batchConvertCELStringToParsedExpr([- rule.condition.expression,- ]);- const celExpr = head(parsedExprs);- if (celExpr) {- expr = resolveCELExpr(celExpr);- }- }-- state.dirty = false;- state.title = rule.condition?.title ?? "";- state.expr = wrapAsGroup(expr);- state.semanticType = rule.semanticType ? rule.semanticType : undefined;-};--onMounted(async () => {- await resetLocalState(props.maskingRule);-});--const defaultTitle = computed(() => {- return `${t("settings.sensitive-data.global-rules.condition-order")} ${- props.index- }`;-});--const onCancel = async () => {- await resetLocalState(props.maskingRule);- emit("cancel");- nextTick(() => (state.dirty = false));-};--const onConfirm = async () => {- const celexpr = await buildCELExpr(state.expr);- if (!celexpr) {- return;- }- const expressions = await batchConvertParsedExprToCELString([celexpr]);- emit("confirm", {- ...props.maskingRule,- semanticType: state.semanticType!,- condition: create(ExprSchema, {- expression: expressions[0],- title: state.title,- description: "",- location: "",- }),- });- state.dirty = false;-};-</script>diff --git a/frontend/src/components/SensitiveData/index.ts b/frontend/src/components/SensitiveData/index.tsindex dff5368db7..decff357a2 100644--- a/frontend/src/components/SensitiveData/index.ts+++ b/frontend/src/components/SensitiveData/index.ts@@ -1,4 +1,3 @@import ClassificationView from "./ClassificationView.vue";-import GlobalMaskingRulesView from "./GlobalMaskingRulesView.vue";-export { GlobalMaskingRulesView, ClassificationView };+export { ClassificationView };diff --git a/frontend/src/react/ReactPageMount.vue b/frontend/src/react/ReactPageMount.vueindex 1ce01c7e00..72769c1448 100644--- a/frontend/src/react/ReactPageMount.vue+++ b/frontend/src/react/ReactPageMount.vue@@ -17,7 +17,7 @@ let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-anyasync function render() {if (!container.value) return;- const [{ mountReactPage }, i18nModule] = await Promise.all([+ const [{ mountReactPage, updateReactPage }, i18nModule] = await Promise.all([import("./mount"),import("./i18n"),]);@@ -26,11 +26,17 @@ async function render() {}if (!root) {root = await mountReactPage(container.value, props.page);+ } else {+ await updateReactPage(root, props.page);}}onMounted(() => render());watch(locale, () => render());+watch(+ () => props.page,+ () => render()+);onUnmounted(() => {root?.unmount();root = null;diff --git a/frontend/src/react/components/ExprEditor.tsx b/frontend/src/react/components/ExprEditor.tsxnew file mode 100644index 0000000000..b19dae896c--- /dev/null+++ b/frontend/src/react/components/ExprEditor.tsx@@ -0,0 +1,1332 @@+import { Plus, X } from "lucide-react";+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import {+ factorText,+ getOperatorListByFactor,+} from "@/components/ExprEditor/components/common";+import type { OptionConfig } from "@/components/ExprEditor/context";+import type {+ ConditionExpr,+ ConditionGroupExpr,+ Factor,+ Operator,+ RawStringExpr,+} from "@/plugins/cel";+import {+ ExprType,+ isBooleanFactor,+ isCollectionOperator,+ isConditionExpr,+ isConditionGroupExpr,+ isNumberFactor,+ isRawStringExpr,+ isStringFactor,+ isStringOperator,+ isTimestampFactor,+ LogicalOperatorList,+} from "@/plugins/cel";+import { Input } from "@/react/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/react/components/ui/select";++// Re-export OptionConfig so consumers can import from one place.+export type { OptionConfig } from "@/components/ExprEditor/context";++// ============================================================+// Context+// ============================================================++interface ExprEditorContextValue {+ readonly: boolean;+ enableRawExpression: boolean;+ factorList: Factor[];+ optionConfigMap: Map<Factor, OptionConfig>;+ factorOperatorOverrideMap: Map<Factor, Operator[]> | undefined;+}++const ExprEditorContext = createContext<ExprEditorContextValue>({+ readonly: false,+ enableRawExpression: true,+ factorList: [],+ optionConfigMap: new Map(),+ factorOperatorOverrideMap: undefined,+});++function useExprEditorCtx() {+ return useContext(ExprEditorContext);+}++// ============================================================+// SearchableSelect — async searchable dropdown+// ============================================================++interface SearchableSelectOption {+ label: string;+ value: string;+}++function SearchableSelect({+ value,+ optionConfig,+ disabled,+ placeholder,+ onChange,+}: {+ value: string;+ optionConfig: OptionConfig;+ disabled?: boolean;+ placeholder?: string;+ onChange: (value: string) => void;+}) {+ const { t } = useTranslation();+ const [search, setSearch] = useState("");+ const [open, setOpen] = useState(false);+ const [options, setOptions] = useState<SearchableSelectOption[]>([]);+ const [loading, setLoading] = useState(false);+ const containerRef = useRef<HTMLDivElement>(null);+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const selectedLabel = useMemo(() => {+ const found = options.find((o) => o.value === value);+ if (found) return found.label;+ if (optionConfig.fallback)+ return optionConfig.fallback(value)?.label ?? value;+ return value || "";+ }, [options, value, optionConfig]);++ const doSearch = useCallback(+ async (q: string) => {+ if (!optionConfig.search) return;+ setLoading(true);+ try {+ const resp = await optionConfig.search({+ search: q,+ pageToken: "",+ pageSize: 20,+ });+ setOptions(resp.options as SearchableSelectOption[]);+ } finally {+ setLoading(false);+ }+ },+ [optionConfig]+ );++ useEffect(() => {+ if (!value) return;+ if (optionConfig.fetch) {+ optionConfig.fetch([value]).then((opts) => {+ setOptions(opts as SearchableSelectOption[]);+ });+ } else if (optionConfig.search) {+ doSearch(value);+ }+ }, []);++ const handleOpen = () => {+ setOpen(true);+ doSearch(search);+ };++ const handleSearchChange = (q: string) => {+ setSearch(q);+ if (debounceRef.current) clearTimeout(debounceRef.current);+ debounceRef.current = setTimeout(() => doSearch(q), 300);+ };++ const handleSelect = (v: string) => {+ onChange(v);+ setOpen(false);+ setSearch("");+ };++ useEffect(() => {+ if (!open) return;+ const handler = (e: MouseEvent) => {+ if (+ containerRef.current &&+ !containerRef.current.contains(e.target as Node)+ ) {+ setOpen(false);+ }+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, [open]);++ if (!optionConfig.search) {+ return (+ <Select+ value={value}+ disabled={disabled}+ onValueChange={(val) => {+ if (val != null) onChange(val);+ }}+ >+ <SelectTrigger className="min-w-28">+ <SelectValue placeholder={placeholder}>+ {(value: string | null) => {+ if (!value) return null;+ const found = optionConfig.options.find((o) => o.value === value);+ return found?.label ?? value;+ }}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {optionConfig.options.map((o) => (+ <SelectItem key={o.value as string} value={o.value as string}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+ }++ return (+ <div ref={containerRef} className="relative min-w-28">+ <button+ type="button"+ className="h-8 px-2 text-sm rounded border border-control-border bg-white w-full text-left disabled:opacity-50 truncate"+ disabled={disabled}+ onClick={handleOpen}+ >+ {selectedLabel || (+ <span className="text-control-placeholder">{placeholder ?? ""}</span>+ )}+ </button>+ {open && (+ <div className="absolute z-50 mt-1 w-56 bg-white border border-control-border rounded shadow-md">+ <div className="p-1 border-b border-control-border">+ <input+ autoFocus+ className="w-full h-8 px-2 text-sm rounded border border-control-border outline-none"+ placeholder={t("common.filter-by-name")}+ value={search}+ onChange={(e) => handleSearchChange(e.target.value)}+ />+ </div>+ <ul className="max-h-48 overflow-y-auto py-1">+ {loading && (+ <li className="px-3 py-1 text-sm text-control-placeholder">+ {t("common.loading")}+ </li>+ )}+ {!loading && options.length === 0 && (+ <li className="px-3 py-1 text-sm text-control-placeholder">+ {t("common.no-data")}+ </li>+ )}+ {options.map((o) => (+ <li+ key={o.value}+ className={`px-3 py-1 text-sm cursor-pointer hover:bg-gray-100 ${+ o.value === value ? "font-medium text-accent" : ""+ }`}+ onMouseDown={() => handleSelect(o.value)}+ >+ {o.label}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ );+}++// ============================================================+// MultiSearchableSelect — async searchable multi-select+// ============================================================++function MultiSearchableSelect({+ value,+ optionConfig,+ disabled,+ placeholder,+ onChange,+}: {+ value: string[];+ optionConfig: OptionConfig;+ disabled?: boolean;+ placeholder?: string;+ onChange: (value: string[]) => void;+}) {+ const { t } = useTranslation();+ const [search, setSearch] = useState("");+ const [open, setOpen] = useState(false);+ const [searchOptions, setSearchOptions] = useState<SearchableSelectOption[]>(+ []+ );+ const [loading, setLoading] = useState(false);+ const containerRef = useRef<HTMLDivElement>(null);+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const [knownOptions, setKnownOptions] = useState<SearchableSelectOption[]>(+ []+ );++ const allOptions = useMemo(() => {+ if (optionConfig.search) {+ const merged = new Map<string, SearchableSelectOption>();+ for (const o of knownOptions) merged.set(o.value, o);+ for (const o of searchOptions) merged.set(o.value, o);+ return Array.from(merged.values());+ }+ return optionConfig.options as SearchableSelectOption[];+ }, [optionConfig, knownOptions, searchOptions]);++ const getLabelForValue = useCallback(+ (v: string) => {+ const found = allOptions.find((o) => o.value === v);+ if (found) return found.label;+ if (optionConfig.fallback) return optionConfig.fallback(v)?.label ?? v;+ return v;+ },+ [allOptions, optionConfig]+ );++ const doSearch = useCallback(+ async (q: string) => {+ if (!optionConfig.search) return;+ setLoading(true);+ try {+ const resp = await optionConfig.search({+ search: q,+ pageToken: "",+ pageSize: 20,+ });+ setSearchOptions(resp.options as SearchableSelectOption[]);+ } finally {+ setLoading(false);+ }+ },+ [optionConfig]+ );++ useEffect(() => {+ if (value.length === 0) return;+ if (optionConfig.fetch) {+ optionConfig.fetch(value).then((opts) => {+ setKnownOptions(opts as SearchableSelectOption[]);+ });+ } else if (optionConfig.search) {+ doSearch("");+ }+ }, []);++ const handleOpen = () => {+ setOpen(true);+ doSearch(search);+ };++ const handleSearchChange = (q: string) => {+ setSearch(q);+ if (debounceRef.current) clearTimeout(debounceRef.current);+ debounceRef.current = setTimeout(() => doSearch(q), 300);+ };++ const toggleValue = (v: string) => {+ if (value.includes(v)) {+ onChange(value.filter((x) => x !== v));+ } else {+ onChange([...value, v]);+ }+ };++ const removeValue = (v: string) => {+ onChange(value.filter((x) => x !== v));+ };++ useEffect(() => {+ if (!open) return;+ const handler = (e: MouseEvent) => {+ if (+ containerRef.current &&+ !containerRef.current.contains(e.target as Node)+ ) {+ setOpen(false);+ }+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, [open]);++ if (!optionConfig.search) {+ return (+ <MultiCheckSelect+ value={value}+ options={optionConfig.options as { label: string; value: string }[]}+ disabled={disabled}+ placeholder={placeholder}+ onChange={onChange}+ />+ );+ }++ return (+ <div ref={containerRef} className="relative min-w-32 max-w-xs">+ <div+ className="min-h-8 px-2 py-0.5 text-sm rounded border border-control-border bg-white flex flex-wrap gap-1 cursor-pointer"+ onClick={disabled ? undefined : handleOpen}+ >+ {value.length === 0 && (+ <span className="text-control-placeholder text-sm leading-6">+ {placeholder ?? ""}+ </span>+ )}+ {value.map((v) => (+ <span+ key={v}+ className="inline-flex items-center gap-1 bg-gray-100 text-xs px-1.5 py-0.5 rounded"+ >+ {getLabelForValue(v)}+ {!disabled && (+ <button+ type="button"+ className="text-gray-400 hover:text-gray-600"+ onMouseDown={(e) => {+ e.stopPropagation();+ removeValue(v);+ }}+ >+ ×+ </button>+ )}+ </span>+ ))}+ </div>+ {open && (+ <div className="absolute z-50 mt-1 w-56 bg-white border border-control-border rounded shadow-md">+ <div className="p-1 border-b border-control-border">+ <input+ autoFocus+ className="w-full h-8 px-2 text-sm rounded border border-control-border outline-none"+ placeholder={t("common.filter-by-name")}+ value={search}+ onChange={(e) => handleSearchChange(e.target.value)}+ />+ </div>+ <ul className="max-h-48 overflow-y-auto py-1">+ {loading && (+ <li className="px-3 py-1 text-sm text-control-placeholder">+ {t("common.loading")}+ </li>+ )}+ {!loading && allOptions.length === 0 && (+ <li className="px-3 py-1 text-sm text-control-placeholder">+ {t("common.no-data")}+ </li>+ )}+ {allOptions.map((o) => (+ <li+ key={o.value}+ className={`px-3 py-1 text-sm cursor-pointer hover:bg-gray-100 flex items-center gap-2 ${+ value.includes(o.value) ? "font-medium" : ""+ }`}+ onMouseDown={() => toggleValue(o.value)}+ >+ <input+ type="checkbox"+ readOnly+ checked={value.includes(o.value)}+ className="pointer-events-none"+ />+ {o.label}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ );+}++// ============================================================+// TagInput — multi-value tag input (no dropdown)+// ============================================================++function TagInput({+ value,+ disabled,+ placeholder,+ onChange,+}: {+ value: string[];+ disabled?: boolean;+ placeholder?: string;+ onChange: (value: string[]) => void;+}) {+ const [inputValue, setInputValue] = useState("");++ const addTag = (raw: string) => {+ const tags = raw+ .split(",")+ .map((s) => s.trim())+ .filter(Boolean);+ if (tags.length === 0) return;+ const next = Array.from(new Set([...value, ...tags]));+ onChange(next);+ setInputValue("");+ };++ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Enter" || e.key === ",") {+ e.preventDefault();+ addTag(inputValue);+ } else if (e.key === "Backspace" && inputValue === "" && value.length > 0) {+ onChange(value.slice(0, -1));+ }+ };++ const removeTag = (tag: string) => {+ onChange(value.filter((v) => v !== tag));+ };++ return (+ <div className="flex flex-wrap items-center gap-1 min-h-8 px-2 py-0.5 rounded border border-control-border bg-white min-w-64 max-w-xs">+ {value.map((tag) => (+ <span+ key={tag}+ className="inline-flex items-center gap-1 bg-gray-100 text-xs px-1.5 py-0.5 rounded"+ >+ {tag}+ {!disabled && (+ <button+ type="button"+ className="text-gray-400 hover:text-gray-600"+ onClick={() => removeTag(tag)}+ >+ ×+ </button>+ )}+ </span>+ ))}+ {!disabled && (+ <input+ className="flex-1 min-w-16 h-6 text-sm outline-none bg-transparent"+ placeholder={value.length === 0 ? (placeholder ?? "") : ""}+ value={inputValue}+ disabled={disabled}+ onChange={(e) => setInputValue(e.target.value)}+ onKeyDown={handleKeyDown}+ onBlur={() => {+ if (inputValue) addTag(inputValue);+ }}+ />+ )}+ </div>+ );+}++// ============================================================+// MultiCheckSelect — dropdown with checkboxes + "All" toggle+// ============================================================++function MultiCheckSelect({+ value,+ options,+ disabled,+ placeholder,+ onChange,+}: {+ value: string[];+ options: { label: string; value: string }[];+ disabled?: boolean;+ placeholder?: string;+ onChange: (value: string[]) => void;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const containerRef = useRef<HTMLDivElement>(null);++ const allValues = options.map((o) => o.value);+ const allSelected =+ allValues.length > 0 && allValues.every((v) => value.includes(v));+ const anySelected = value.length > 0;++ const getLabelForValue = (v: string) =>+ options.find((o) => o.value === v)?.label ?? v;++ const toggleValue = (v: string) => {+ if (value.includes(v)) {+ onChange(value.filter((x) => x !== v));+ } else {+ onChange([...value, v]);+ }+ };++ useEffect(() => {+ if (!open) return;+ const handler = (e: MouseEvent) => {+ if (+ containerRef.current &&+ !containerRef.current.contains(e.target as Node)+ ) {+ setOpen(false);+ }+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, [open]);++ return (+ <div ref={containerRef} className="relative min-w-32">+ <button+ type="button"+ className="inline-flex items-center gap-1 min-h-8 w-full px-2 py-0.5 text-sm rounded-md border border-control-border bg-white text-left hover:bg-control-bg disabled:pointer-events-none disabled:opacity-50 flex-wrap"+ disabled={disabled}+ onClick={() => setOpen(!open)}+ >+ {value.length === 0 && (+ <span className="text-control-placeholder">{placeholder}</span>+ )}+ {value.map((v) => (+ <span+ key={v}+ className="inline-flex items-center gap-1 bg-gray-100 text-xs px-1.5 py-0.5 rounded"+ >+ {getLabelForValue(v)}+ {!disabled && (+ <span+ role="button"+ className="text-gray-400 hover:text-gray-600"+ onMouseDown={(e) => {+ e.stopPropagation();+ e.preventDefault();+ onChange(value.filter((x) => x !== v));+ }}+ >+ ×+ </span>+ )}+ </span>+ ))}+ </button>+ {open && (+ <div className="absolute z-50 mt-1 w-full bg-white border border-control-border rounded-md shadow-md py-1">+ <label className="flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer border-b border-control-border hover:bg-control-bg">+ <input+ type="checkbox"+ checked={allSelected}+ ref={(el) => {+ if (el) el.indeterminate = anySelected && !allSelected;+ }}+ onChange={(e) => {+ if (e.target.checked) {+ onChange(allValues);+ } else {+ onChange([]);+ }+ }}+ />+ {t("common.all")}+ </label>+ {options.map((o) => (+ <label+ key={o.value}+ className="flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer hover:bg-control-bg"+ >+ <input+ type="checkbox"+ checked={value.includes(o.value)}+ onChange={() => toggleValue(o.value)}+ />+ {o.label}+ </label>+ ))}+ </div>+ )}+ </div>+ );+}++// ============================================================+// FactorSelect+// ============================================================++function FactorSelect({+ expr,+ onUpdate,+}: {+ expr: ConditionExpr;+ onUpdate: () => void;+}) {+ const { readonly, factorList } = useExprEditorCtx();+ const factor = expr.args[0] as Factor;++ useEffect(() => {+ if (factorList.length === 0) return;+ if (!factorList.includes(factor)) {+ (expr.args as unknown[])[0] = factorList[0];+ onUpdate();+ }+ }, [factor, factorList]);++ return (+ <Select+ value={factor}+ disabled={readonly}+ onValueChange={(val) => {+ (expr.args as unknown[])[0] = val as Factor;+ onUpdate();+ }}+ >+ <SelectTrigger className="shrink-0">+ <SelectValue>+ {(value: string | null) =>+ value ? factorText(value as Factor) : null+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {factorList.map((f) => (+ <SelectItem key={f} value={f}>+ {factorText(f)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++// ============================================================+// OperatorSelect+// ============================================================++const OPERATOR_DICT: Record<string, string> = {+ "_==_": "==",+ "_!=_": "!=",+ "_<_": "<",+ "_<=_": "≤",+ "_>=_": "≥",+ "_>_": ">",+ "@not_in": "not in",+ "@not_contains": "not contains",+};++function operatorLabel(op: string): string {+ return OPERATOR_DICT[op] ?? op.replace(/^@/, "");+}++function OperatorSelect({+ expr,+ onUpdate,+}: {+ expr: ConditionExpr;+ onUpdate: () => void;+}) {+ const { readonly, factorOperatorOverrideMap: overrideMap } =+ useExprEditorCtx();+ const factor = expr.args[0] as Factor;++ const operators = useMemo(+ () => getOperatorListByFactor(factor, overrideMap),+ [factor, overrideMap]+ );++ useEffect(() => {+ if (operators.length === 0) return;+ if (!operators.includes(expr.operator)) {+ expr.operator = operators[0] as typeof expr.operator;+ onUpdate();+ }+ }, [operators, expr.operator]);++ return (+ <Select+ value={expr.operator}+ disabled={readonly}+ onValueChange={(val) => {+ expr.operator = val as typeof expr.operator;+ onUpdate();+ }}+ >+ <SelectTrigger className="shrink-0">+ <SelectValue>+ {(value: string | null) => (value ? operatorLabel(value) : null)}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {operators.map((op) => (+ <SelectItem key={op} value={op}>+ {operatorLabel(op)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++// ============================================================+// ValueInput+// ============================================================++function ValueInput({+ expr,+ onUpdate,+}: {+ expr: ConditionExpr;+ onUpdate: () => void;+}) {+ const { t } = useTranslation();+ const { readonly, optionConfigMap } = useExprEditorCtx();+ const factor = expr.args[0] as Factor;+ const operator = expr.operator;++ const optionConfig = useMemo(+ () => optionConfigMap.get(factor) ?? { options: [] },+ [optionConfigMap, factor]+ );++ const hasOption = optionConfig.options.length > 0 || !!optionConfig.search;++ type InputType = "INPUT" | "SINGLE-SELECT" | "MULTI-SELECT" | "MULTI-INPUT";++ const isArrayValue = isCollectionOperator(operator);++ let inputType: InputType;+ if (isArrayValue) {+ inputType = hasOption ? "MULTI-SELECT" : "MULTI-INPUT";+ } else if (isStringOperator(operator)) {+ // String operators (startsWith, contains, etc.) always use text input+ inputType = "INPUT";+ } else if (hasOption) {+ inputType = "SINGLE-SELECT";+ } else {+ inputType = "INPUT";+ }++ const isNumberValue = isNumberFactor(factor);++ // Reset value when factor or operator changes, matching Vue's watch([factor, operator]) behavior.+ const prevRef = useRef({ factor, operator });+ useEffect(() => {+ const prev = prevRef.current;+ const changed = prev.factor !== factor || prev.operator !== operator;+ prevRef.current = { factor, operator };+ if (!changed) return;++ if (isNumberFactor(factor)) {+ if (isCollectionOperator(operator)) {+ (expr.args as unknown[])[1] = [];+ } else {+ (expr.args as unknown[])[1] = 0;+ }+ } else if (isBooleanFactor(factor)) {+ (expr.args as unknown[])[1] = true;+ } else if (isStringFactor(factor)) {+ if (isCollectionOperator(operator)) {+ (expr.args as unknown[])[1] = [];+ } else {+ (expr.args as unknown[])[1] = "";+ }+ }+ onUpdate();+ }, [factor, operator]);++ const getStringValue = () => {+ const v = expr.args[1];+ if (typeof v === "string") return v;+ if (typeof v === "number") return String(v);+ return "";+ };+ const getNumberValue = () =>+ typeof expr.args[1] === "number" ? expr.args[1] : 0;+ const getArrayValue = (): string[] => {+ if (!Array.isArray(expr.args[1])) return [];+ return (expr.args[1] as unknown[]).map(String);+ };++ const setStringValue = (v: string) => {+ // For number factors, store as number even when selected from a string-valued dropdown+ (expr.args as unknown[])[1] = isNumberFactor(factor) ? Number(v) : v;+ onUpdate();+ };+ const setNumberValue = (v: number) => {+ (expr.args as unknown[])[1] = v;+ onUpdate();+ };+ const setArrayValue = (v: string[]) => {+ if (isNumberFactor(factor)) {+ (expr.args as unknown[])[1] = v.map(Number);+ } else {+ (expr.args as unknown[])[1] = v;+ }+ onUpdate();+ };++ if (inputType === "INPUT") {+ if (isNumberValue) {+ return (+ <input+ type="number"+ className="h-8 px-2 text-sm rounded border border-control-border bg-white disabled:opacity-50 max-w-20"+ value={getNumberValue()}+ disabled={readonly}+ onChange={(e) => setNumberValue(Number(e.target.value))}+ placeholder={t("cel.condition.input-value")}+ />+ );+ }+ return (+ <Input+ className="h-8 min-w-28 text-sm"+ value={getStringValue()}+ disabled={readonly}+ onChange={(e) => setStringValue(e.target.value)}+ placeholder={t("cel.condition.input-value")}+ />+ );+ }++ if (inputType === "SINGLE-SELECT") {+ if (optionConfig.search) {+ return (+ <SearchableSelect+ value={getStringValue()}+ optionConfig={optionConfig}+ disabled={readonly}+ placeholder={t("cel.condition.select-value")}+ onChange={setStringValue}+ />+ );+ }+ return (+ <Select+ value={getStringValue()}+ disabled={readonly}+ onValueChange={(val) => {+ if (val != null) setStringValue(val);+ }}+ >+ <SelectTrigger className="min-w-28">+ <SelectValue placeholder={t("cel.condition.select-value")}>+ {(value: string | null) => {+ if (!value) return null;+ const found = optionConfig.options.find((o) => o.value === value);+ return found?.label ?? value;+ }}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {optionConfig.options.map((o) => (+ <SelectItem key={o.value as string} value={o.value as string}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+ }++ if (inputType === "MULTI-SELECT") {+ if (optionConfig.search) {+ return (+ <MultiSearchableSelect+ value={getArrayValue()}+ optionConfig={optionConfig}+ disabled={readonly}+ placeholder={t("cel.condition.select-value")}+ onChange={setArrayValue}+ />+ );+ }+ return (+ <MultiCheckSelect+ value={getArrayValue()}+ options={optionConfig.options as { label: string; value: string }[]}+ disabled={readonly}+ placeholder={t("cel.condition.select-value")}+ onChange={setArrayValue}+ />+ );+ }++ return (+ <TagInput+ value={getArrayValue()}+ disabled={readonly}+ placeholder={t("cel.condition.input-value-press-enter")}+ onChange={setArrayValue}+ />+ );+}++// ============================================================+// ConditionRow+// ============================================================++function ConditionRow({+ expr,+ onRemove,+ onUpdate,+}: {+ expr: ConditionExpr;+ onRemove: () => void;+ onUpdate: () => void;+}) {+ const { readonly } = useExprEditorCtx();++ return (+ <div className="w-full flex items-center gap-x-1">+ <FactorSelect expr={expr} onUpdate={onUpdate} />+ <OperatorSelect expr={expr} onUpdate={onUpdate} />+ <div className="flex-1 min-w-0">+ <ValueInput expr={expr} onUpdate={onUpdate} />+ </div>+ {!readonly && (+ <button+ type="button"+ className="shrink-0 w-7 h-7 flex items-center justify-center rounded text-control-placeholder hover:text-control hover:bg-gray-100"+ onClick={onRemove}+ >+ <X className="w-4 h-4" />+ </button>+ )}+ </div>+ );+}++// ============================================================+// RawStringEditor+// ============================================================++function RawStringEditor({+ expr,+ onRemove,+ onUpdate,+}: {+ expr: RawStringExpr;+ onRemove: () => void;+ onUpdate: () => void;+}) {+ const { readonly } = useExprEditorCtx();++ return (+ <div className="w-full flex items-start gap-x-1">+ <textarea+ className="flex-1 min-h-16 max-h-24 px-2 py-1 text-sm rounded border border-control-border bg-white resize-y disabled:opacity-50"+ placeholder="Enter raw CEL expression"+ value={expr.content}+ disabled={readonly}+ rows={2}+ onChange={(e) => {+ expr.content = e.target.value;+ onUpdate();+ }}+ />+ {!readonly && (+ <button+ type="button"+ className="shrink-0 w-7 h-7 flex items-center justify-center rounded text-control-placeholder hover:text-control hover:bg-gray-100"+ onClick={onRemove}+ >+ <X className="w-4 h-4" />+ </button>+ )}+ </div>+ );+}++// ============================================================+// ConditionGroup (recursive)+// ============================================================++function ConditionGroup({+ expr,+ root = false,+ onRemove,+ onUpdate,+}: {+ expr: ConditionGroupExpr;+ root?: boolean;+ onRemove?: () => void;+ onUpdate: () => void;+}) {+ const { t } = useTranslation();+ const {+ readonly,+ factorList,+ enableRawExpression,+ factorOperatorOverrideMap: overrideMap,+ } = useExprEditorCtx();++ const operator = expr.operator;+ const args = expr.args;++ const logicalLabel = (op: string) => {+ if (op === "_&&_") return "and";+ if (op === "_||_") return "or";+ return op;+ };++ const getDefaultValue = (+ factor: Factor+ ): string | number | boolean | Date => {+ if (isNumberFactor(factor)) return 0;+ if (isBooleanFactor(factor)) return true;+ if (isStringFactor(factor)) return "";+ if (isTimestampFactor(factor)) return new Date();+ return "";+ };++ const addCondition = () => {+ const factor = factorList[0];+ if (!factor) return;+ const operators = getOperatorListByFactor(factor, overrideMap);+ const op = operators[0];+ if (!op) return;+ args.push({+ type: ExprType.Condition,+ operator: op,+ args: [factor, getDefaultValue(factor)],+ } as ConditionExpr);+ onUpdate();+ };++ const addConditionGroup = () => {+ args.push({+ type: ExprType.ConditionGroup,+ operator: LogicalOperatorList[0],+ args: [],+ });+ onUpdate();+ };++ const addRawString = () => {+ args.push({+ type: ExprType.RawString,+ content: "",+ });+ onUpdate();+ };++ const removeOperand = (index: number) => {+ args.splice(index, 1);+ onUpdate();+ };++ return (+ <div+ className={`w-full flex flex-col gap-y-2 py-0.5 ${+ root ? "" : "border rounded-[3px] bg-gray-50"+ }`}+ >+ {!root && (+ <div className="pl-2.5 pr-1 text-gray-500 flex items-center">+ <div className="flex-1">+ {args.length > 0 ? (+ <>+ {operator === "_||_" && (+ <span>{t("cel.condition.group.or.description")}</span>+ )}+ {operator === "_&&_" && (+ <span>{t("cel.condition.group.and.description")}</span>+ )}+ </>+ ) : (+ <span className="inline-flex items-center">+ {t("cel.condition.add-condition-in-group-placeholder", {+ plus: "+",+ })}+ </span>+ )}+ </div>+ {!readonly && (+ <div className="flex items-center justify-end">+ <button+ type="button"+ className="w-[22px] h-[22px] flex items-center justify-center rounded hover:bg-gray-100"+ onClick={onRemove}+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>+ )}+ </div>+ )}++ {root && args.length === 0 && (+ <div className="text-gray-500 text-sm">+ {t("cel.condition.add-root-condition-placeholder")}+ </div>+ )}++ {args.map((operand, i) => (+ <div+ key={i}+ className={`flex items-start gap-x-1 w-full ${root ? "" : "px-1"}`}+ >+ <div className="w-14 shrink-0">+ {i === 0 ? (+ <div className="pl-1.5 pt-1 text-control text-sm">Where</div>+ ) : i === 1 ? (+ <Select+ value={operator}+ disabled={readonly}+ onValueChange={(val) => {+ expr.operator = val as typeof expr.operator;+ onUpdate();+ }}+ >+ <SelectTrigger className="h-7 px-1.5">+ <SelectValue>+ {(value: string | null) =>+ value ? logicalLabel(value) : null+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="_&&_">{logicalLabel("_&&_")}</SelectItem>+ <SelectItem value="_||_">{logicalLabel("_||_")}</SelectItem>+ </SelectContent>+ </Select>+ ) : (+ <div className="pl-2 pt-1 text-control text-sm lowercase">+ {logicalLabel(operator)}+ </div>+ )}+ </div>+ <div className="flex-1 flex flex-col gap-y-1 min-w-0">+ {isConditionGroupExpr(operand) && (+ <ConditionGroup+ key={i}+ expr={operand}+ onRemove={() => removeOperand(i)}+ onUpdate={onUpdate}+ />+ )}+ {isConditionExpr(operand) && (+ <ConditionRow+ expr={operand}+ onRemove={() => removeOperand(i)}+ onUpdate={onUpdate}+ />+ )}+ {isRawStringExpr(operand) && (+ <RawStringEditor+ expr={operand}+ onRemove={() => removeOperand(i)}+ onUpdate={onUpdate}+ />+ )}+ </div>+ </div>+ ))}++ {!root && (+ <div className="pl-1.5 pb-1 flex gap-x-1">+ <button+ type="button"+ className="inline-flex items-center gap-1 text-sm text-gray-500 px-1.5 py-0.5 rounded hover:bg-gray-100 disabled:opacity-50"+ disabled={readonly}+ onClick={addCondition}+ >+ <Plus className="w-4 h-4" />+ {t("cel.condition.add")}+ </button>+ <button+ type="button"+ className="inline-flex items-center gap-1 text-sm text-gray-500 px-1.5 py-0.5 rounded hover:bg-gray-100 disabled:opacity-50"+ disabled={readonly}+ onClick={addRawString}+ >+ <Plus className="w-4 h-4" />+ {t("cel.condition.add-raw-expression")}+ </button>+ </div>+ )}++ {root && (+ <div className="flex gap-x-1">+ <button+ type="button"+ className="inline-flex items-center gap-1 text-sm px-1.5 py-0.5 rounded hover:bg-gray-100 disabled:opacity-50"+ disabled={readonly}+ onClick={addCondition}+ >+ <Plus className="w-4 h-4" />+ {t("cel.condition.add")}+ </button>+ <button+ type="button"+ className="inline-flex items-center gap-1 text-sm px-1.5 py-0.5 rounded hover:bg-gray-100 disabled:opacity-50"+ disabled={readonly}+ onClick={addConditionGroup}+ >+ <Plus className="w-4 h-4" />+ {t("cel.condition.add-group")}+ </button>+ {enableRawExpression && (+ <button+ type="button"+ className="inline-flex items-center gap-1 text-sm px-1.5 py-0.5 rounded hover:bg-gray-100 disabled:opacity-50"+ disabled={readonly}+ onClick={addRawString}+ >+ <Plus className="w-4 h-4" />+ {t("cel.condition.add-raw-expression")}+ </button>+ )}+ </div>+ )}+ </div>+ );+}++// ============================================================+// ExprEditor (public API)+// ============================================================++export interface ExprEditorProps {+ expr: ConditionGroupExpr;+ readonly?: boolean;+ enableRawExpression?: boolean;+ factorList: Factor[];+ optionConfigMap?: Map<Factor, OptionConfig>;+ factorOperatorOverrideMap?: Map<Factor, Operator[]>;+ onUpdate: () => void;+}++export function ExprEditor({+ expr,+ readonly = false,+ enableRawExpression = true,+ factorList,+ optionConfigMap = new Map(),+ factorOperatorOverrideMap: overrideMap,+ onUpdate,+}: ExprEditorProps) {+ const ctxValue: ExprEditorContextValue = useMemo(+ () => ({+ readonly,+ enableRawExpression,+ factorList,+ optionConfigMap,+ factorOperatorOverrideMap: overrideMap,+ }),+ [readonly, enableRawExpression, factorList, optionConfigMap, overrideMap]+ );++ return (+ <ExprEditorContext.Provider value={ctxValue}>+ <div className="bb-risk-expr-editor text-sm w-full">+ <ConditionGroup expr={expr} root onUpdate={onUpdate} />+ </div>+ </ExprEditorContext.Provider>+ );+}diff --git a/frontend/src/react/components/FeatureAttention.tsx b/frontend/src/react/components/FeatureAttention.tsxnew file mode 100644index 0000000000..1fbd1fc69b--- /dev/null+++ b/frontend/src/react/components/FeatureAttention.tsx@@ -0,0 +1,145 @@+import { CircleAlert, Info } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { router } from "@/router";+import { useActuatorV1Store, useSubscriptionV1Store } from "@/store";+import { ENTERPRISE_INQUIRE_LINK, instanceLimitFeature } from "@/types";+import {+ PlanFeature,+ PlanType,+} from "@/types/proto-es/v1/subscription_service_pb";+import { autoSubscriptionRoute, hasWorkspacePermissionV2 } from "@/utils";+import { useVueState } from "../hooks/useVueState";++export function FeatureAttention({+ feature,+ description: descriptionProp,+}: {+ feature: PlanFeature;+ description?: string;+}) {+ const { t } = useTranslation();+ const subscriptionStore = useSubscriptionV1Store();+ const actuatorStore = useActuatorV1Store();++ const hasFeature = useVueState(() =>+ subscriptionStore.hasInstanceFeature(feature)+ );+ const existInstanceWithoutLicense = useVueState(+ () =>+ actuatorStore.totalInstanceCount > actuatorStore.activatedInstanceCount &&+ instanceLimitFeature.has(feature)+ );++ const show = !hasFeature || existInstanceWithoutLicense;+ if (!show) return null;++ const isWarning = !hasFeature;+ const featureKey = PlanFeature[feature].split(".").join("-");++ const title = t(`dynamic.subscription.features.${featureKey}.title`);++ const featureDesc =+ descriptionProp || t(`dynamic.subscription.features.${featureKey}.desc`);++ let descriptionText: string;+ if (!hasFeature) {+ const startTrial = subscriptionStore.isTrialing+ ? ""+ : t("subscription.trial-for-days", {+ days: subscriptionStore.trialingDays,+ });+ const requiredPlan = subscriptionStore.getMinimumRequiredPlan(feature);+ if (+ requiredPlan === PlanType.FREE &&+ subscriptionStore.hasFeature(feature)+ ) {+ descriptionText = `${featureDesc}\n${startTrial}`;+ } else {+ const trialText = t("subscription.required-plan-with-trial", {+ requiredPlan: t(+ `subscription.plan.${PlanType[requiredPlan].toLowerCase()}.title`+ ),+ startTrial,+ });+ descriptionText = `${featureDesc}\n${trialText}`;+ }+ } else {+ const attention = t(+ "subscription.instance-assignment.missing-license-attention"+ );+ descriptionText = `${featureDesc}\n${attention}`;+ }++ const hasPermission = hasWorkspacePermissionV2("bb.settings.set");++ let actionText = "";+ if (hasPermission) {+ if (!hasFeature) {+ actionText = t("subscription.request-n-days-trial", {+ days: subscriptionStore.trialingDays,+ });+ } else if (hasWorkspacePermissionV2("bb.instances.update")) {+ actionText = t("subscription.instance-assignment.assign-license");+ }+ }++ const onAction = () => {+ if (!hasFeature) {+ // Vue version shows WeChat QR modal for zh-CN, but that's a Vue+ // component. Open the inquiry link for all locales as a fallback.+ window.open(ENTERPRISE_INQUIRE_LINK, "_blank");+ return;+ }+ // Vue version opens InstanceAssignment drawer here, which is a Vue+ // component not yet migrated. Navigate to the subscription page instead,+ // matching the Vue fallback behavior.+ router.push(autoSubscriptionRoute());+ };++ const Icon = isWarning ? CircleAlert : Info;++ return (+ <div+ className={`flex items-start gap-3 rounded-md border px-4 py-3 ${+ isWarning+ ? "border-yellow-300 bg-yellow-50"+ : "border-blue-200 bg-blue-50"+ }`}+ >+ <Icon+ className={`w-5 h-5 mt-0.5 shrink-0 ${+ isWarning ? "text-yellow-600" : "text-blue-600"+ }`}+ />+ <div className="flex-1 flex flex-col md:flex-row md:items-center md:justify-between gap-3">+ <div>+ <p+ className={`font-medium text-sm ${+ isWarning ? "text-yellow-800" : "text-blue-800"+ }`}+ >+ {title}+ </p>+ <p+ className={`text-sm whitespace-pre-line mt-1 ${+ isWarning ? "text-yellow-700" : "text-blue-700"+ }`}+ >+ {descriptionText}+ </p>+ </div>+ {actionText && (+ <Button+ variant="outline"+ size="sm"+ className="shrink-0 whitespace-nowrap"+ onClick={onAction}+ >+ {actionText}+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/ui/select.tsx b/frontend/src/react/components/ui/select.tsxnew file mode 100644index 0000000000..76bc935da4--- /dev/null+++ b/frontend/src/react/components/ui/select.tsx@@ -0,0 +1,89 @@+import { Select as BaseSelect } from "@base-ui/react/select";+import { Check, ChevronDown } from "lucide-react";+import type { ComponentProps } from "react";+import { cn } from "@/react/lib/utils";++// ---- Root ----+const Select = BaseSelect.Root;++// ---- Trigger ----+function SelectTrigger({+ className,+ children,+ ref,+ ...props+}: ComponentProps<typeof BaseSelect.Trigger>) {+ return (+ <BaseSelect.Trigger+ ref={ref}+ className={cn(+ "inline-flex items-center justify-between gap-1 h-8 px-2 text-sm rounded-md border border-control-border bg-white text-control whitespace-nowrap",+ "hover:bg-control-bg focus:outline-hidden focus-visible:ring-2 focus-visible:ring-accent",+ "disabled:pointer-events-none disabled:opacity-50",+ className+ )}+ {...props}+ >+ {children}+ <BaseSelect.Icon>+ <ChevronDown className="w-3.5 h-3.5 opacity-50 shrink-0" />+ </BaseSelect.Icon>+ </BaseSelect.Trigger>+ );+}++// ---- Value ----+const SelectValue = BaseSelect.Value;++// ---- Portal + Positioner + Popup ----+function SelectContent({+ className,+ children,+ ref,+ ...props+}: ComponentProps<typeof BaseSelect.Popup>) {+ return (+ <BaseSelect.Portal>+ <BaseSelect.Positioner sideOffset={4}>+ <BaseSelect.Popup+ ref={ref}+ className={cn(+ "z-50 min-w-[var(--anchor-width)] max-h-60 overflow-auto rounded-md border border-control-border bg-white py-1 shadow-md",+ className+ )}+ {...props}+ >+ {children}+ </BaseSelect.Popup>+ </BaseSelect.Positioner>+ </BaseSelect.Portal>+ );+}++// ---- Item ----+function SelectItem({+ className,+ children,+ ref,+ ...props+}: ComponentProps<typeof BaseSelect.Item>) {+ return (+ <BaseSelect.Item+ ref={ref}+ className={cn(+ "relative flex items-center gap-2 px-2 py-1.5 pl-7 text-sm cursor-pointer select-none",+ "hover:bg-control-bg focus:bg-control-bg outline-hidden",+ "data-[highlighted]:bg-control-bg",+ className+ )}+ {...props}+ >+ <BaseSelect.ItemIndicator className="absolute left-1.5">+ <Check className="w-3.5 h-3.5" />+ </BaseSelect.ItemIndicator>+ <BaseSelect.ItemText>{children}</BaseSelect.ItemText>+ </BaseSelect.Item>+ );+}++export { Select, SelectTrigger, SelectValue, SelectContent, SelectItem };diff --git a/frontend/src/react/pages/settings/GlobalMaskingPage.tsx b/frontend/src/react/pages/settings/GlobalMaskingPage.tsxnew file mode 100644index 0000000000..ae683aba50--- /dev/null+++ b/frontend/src/react/pages/settings/GlobalMaskingPage.tsx@@ -0,0 +1,710 @@+import { create } from "@bufbuild/protobuf";+import {+ ChevronDown,+ ChevronUp,+ ListOrdered,+ Pencil,+ Plus,+ Trash2,+} from "lucide-react";+import {+ useCallback,+ useEffect,+ useMemo,+ useReducer,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import { v4 as uuidv4 } from "uuid";+import {+ factorOperatorOverrideMap,+ getClassificationLevelOptions,+} from "@/components/SensitiveData/components/utils";+import type { ConditionGroupExpr, Factor, SimpleExpr } from "@/plugins/cel";+import {+ buildCELExpr,+ emptySimpleExpr,+ resolveCELExpr,+ validateSimpleExpr,+ wrapAsGroup,+} from "@/plugins/cel";+import { ExprEditor, type OptionConfig } from "@/react/components/ExprEditor";+import { FeatureAttention } from "@/react/components/FeatureAttention";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/react/components/ui/select";+import { useVueState } from "@/react/hooks/useVueState";+import {+ pushNotification,+ useActuatorV1Store,+ usePolicyV1Store,+ useSettingV1Store,+ useSubscriptionV1Store,+} from "@/store";+import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";+import type {+ MaskingRulePolicy_MaskingRule,+ Policy,+} from "@/types/proto-es/v1/org_policy_service_pb";+import {+ MaskingRulePolicy_MaskingRuleSchema,+ MaskingRulePolicySchema,+ PolicyResourceType,+ PolicyType,+} from "@/types/proto-es/v1/org_policy_service_pb";+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import {+ arraySwap,+ batchConvertCELStringToParsedExpr,+ batchConvertParsedExprToCELString,+ getDatabaseIdOptionConfig,+ getEnvironmentIdOptions,+ getInstanceIdOptionConfig,+ getProjectIdOptionConfig,+ hasWorkspacePermissionV2,+} from "@/utils";+import {+ CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL,+ CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,+ CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,+ CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID,+ CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID,+ CEL_ATTRIBUTE_RESOURCE_PROJECT_ID,+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,+} from "@/utils/cel-attributes";++// ============================================================+// Types+// ============================================================++type MaskingRuleMode = "NORMAL" | "EDIT" | "CREATE";++interface MaskingRuleItem {+ mode: MaskingRuleMode;+ rule: MaskingRulePolicy_MaskingRule;+}++// ============================================================+// MaskingRuleConfig+// ============================================================++function MaskingRuleConfig({+ index,+ readonly,+ disabled,+ allowDelete,+ factorList,+ optionConfigMap,+ maskingRule,+ onCancel,+ onDelete,+ onConfirm,+}: {+ index: number;+ readonly: boolean;+ disabled: boolean;+ allowDelete: boolean;+ factorList: Factor[];+ optionConfigMap: Map<Factor, OptionConfig>;+ maskingRule: MaskingRulePolicy_MaskingRule;+ onCancel: () => void;+ onDelete: () => void;+ onConfirm: (rule: MaskingRulePolicy_MaskingRule) => void;+}) {+ const { t } = useTranslation();+ const settingStore = useSettingV1Store();++ const [title, setTitle] = useState(maskingRule.condition?.title ?? "");+ const [expr, setExpr] = useState<ConditionGroupExpr>(+ wrapAsGroup(emptySimpleExpr())+ );+ const [semanticType, setSemanticType] = useState<string | undefined>(+ maskingRule.semanticType || undefined+ );+ const [dirty, setDirty] = useState(false);+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);+ const [, forceUpdate] = useReducer((x: number) => x + 1, 0);++ const semanticTypeOptions = useVueState(() => {+ const setting = settingStore.getSettingByName(+ Setting_SettingName.SEMANTIC_TYPES+ );+ if (setting?.value?.value?.case === "semanticType") {+ return setting.value.value.value.types ?? [];+ }+ return [];+ });++ const resetIdRef = useRef(0);+ const resetToRule = useCallback(+ async (rule: MaskingRulePolicy_MaskingRule) => {+ const id = ++resetIdRef.current;+ let simpleExpr: SimpleExpr = emptySimpleExpr();+ if (rule.condition?.expression) {+ const parsedExprs = await batchConvertCELStringToParsedExpr([+ rule.condition.expression,+ ]);+ if (id !== resetIdRef.current) return;+ const celExpr = parsedExprs[0];+ if (celExpr) {+ simpleExpr = resolveCELExpr(celExpr);+ }+ }+ if (id !== resetIdRef.current) return;+ setExpr(wrapAsGroup(simpleExpr));+ setTitle(rule.condition?.title ?? "");+ setSemanticType(rule.semanticType || undefined);+ setDirty(false);+ },+ []+ );++ useEffect(() => {+ resetToRule(maskingRule);+ }, [maskingRule, resetToRule]);++ const errorMessages = useMemo(() => {+ const msgs: string[] = [];+ if (!semanticType) {+ msgs.push(+ t("settings.sensitive-data.global-rules.error.missing-semantic-type")+ );+ }+ if (!validateSimpleExpr(expr)) {+ msgs.push(+ t("settings.sensitive-data.global-rules.error.invalid-condition")+ );+ }+ return msgs;+ }, [semanticType, expr, t]);++ const defaultTitle = `${t("settings.sensitive-data.global-rules.condition-order")} ${index}`;++ const handleCancel = async () => {+ await resetToRule(maskingRule);+ onCancel();+ };++ const handleConfirm = async () => {+ const celexpr = await buildCELExpr(expr);+ if (!celexpr) return;+ const expressions = await batchConvertParsedExprToCELString([celexpr]);+ onConfirm({+ ...maskingRule,+ semanticType: semanticType!,+ condition: create(ExprSchema, {+ expression: expressions[0],+ title,+ description: "",+ location: "",+ }),+ });+ setDirty(false);+ };++ const handleExprUpdate = useCallback(() => {+ setDirty(true);+ forceUpdate();+ }, []);++ return (+ <div className="flex flex-col gap-y-4 w-full">+ <div className="flex flex-col md:flex-row items-start md:items-stretch gap-x-4 gap-y-4">+ <div className="flex-1 flex flex-col gap-y-2 min-w-0">+ <div className="flex items-center h-9">+ {!readonly ? (+ <Input+ className="w-64 h-8 text-sm"+ placeholder={defaultTitle}+ value={title}+ disabled={disabled}+ onChange={(e) => {+ setTitle(e.target.value);+ setDirty(true);+ }}+ />+ ) : (+ <h3 className="font-medium text-sm text-main">+ {title || defaultTitle}+ </h3>+ )}+ </div>+ <ExprEditor+ expr={expr}+ readonly={readonly}+ factorList={factorList}+ optionConfigMap={optionConfigMap}+ factorOperatorOverrideMap={factorOperatorOverrideMap}+ onUpdate={handleExprUpdate}+ />+ </div>+ <div>+ <h3 className="font-medium text-sm text-main py-2">+ {t("settings.sensitive-data.semantic-types.table.semantic-type")}+ </h3>+ <Select+ value={semanticType ?? ""}+ disabled={disabled || readonly}+ onValueChange={(val) => {+ setSemanticType(val || undefined);+ setDirty(true);+ }}+ >+ <SelectTrigger className="min-w-40">+ <SelectValue+ placeholder={t("settings.sensitive-data.semantic-types.select")}+ >+ {(value: string | null) => {+ if (!value) return null;+ const found = semanticTypeOptions.find(+ (st) => st.id === value+ );+ return found?.title ?? value;+ }}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {semanticTypeOptions.map((st) => (+ <SelectItem key={st.id} value={st.id}>+ {st.title}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>++ {!readonly && (+ <div className="flex justify-between items-center">+ {allowDelete ? (+ <div className="relative">+ {showDeleteConfirm ? (+ <div className="flex items-center gap-x-2">+ <span className="text-sm text-control">+ {t("settings.sensitive-data.global-rules.delete-rule-tip")}+ </span>+ <Button+ variant="destructive"+ size="sm"+ disabled={disabled}+ onClick={() => {+ setShowDeleteConfirm(false);+ onDelete();+ }}+ >+ {t("common.delete")}+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setShowDeleteConfirm(false)}+ >+ {t("common.cancel")}+ </Button>+ </div>+ ) : (+ <Button+ variant="ghost"+ size="sm"+ className="text-error hover:text-error"+ disabled={disabled}+ onClick={() => setShowDeleteConfirm(true)}+ >+ <Trash2 className="w-3.5 h-3.5" />+ {t("common.delete")}+ </Button>+ )}+ </div>+ ) : (+ <div />+ )}+ <div className="flex justify-end gap-x-2 ml-auto">+ <Button+ variant="outline"+ disabled={disabled}+ onClick={handleCancel}+ >+ {t("common.cancel")}+ </Button>+ <div className="relative group">+ <Button+ disabled={errorMessages.length !== 0 || disabled || !dirty}+ onClick={handleConfirm}+ >+ {t("common.confirm")}+ </Button>+ {errorMessages.length > 0 && (+ <div className="absolute bottom-full mb-1 right-0 bg-gray-800 text-white text-xs rounded px-2 py-1 hidden group-hover:block whitespace-nowrap z-10">+ <ul className="list-disc pl-4">+ {errorMessages.map((msg, i) => (+ <li key={i}>{msg}</li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </div>+ </div>+ )}+ </div>+ );+}++// ============================================================+// GlobalMaskingPage (main)+// ============================================================++export function GlobalMaskingPage() {+ const { t } = useTranslation();+ const policyStore = usePolicyV1Store();+ const actuatorStore = useActuatorV1Store();+ const settingStore = useSettingV1Store();+ const subscriptionStore = useSubscriptionV1Store();++ const hasSensitiveDataFeature = useVueState(() =>+ subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING)+ );++ const hasPermission = hasWorkspacePermissionV2(+ "bb.policies.updateMaskingRulePolicy"+ );++ const [items, setItems] = useState<MaskingRuleItem[]>([]);+ const [processing, setProcessing] = useState(false);+ const [reorderRules, setReorderRules] = useState(false);++ const factorList = useMemo(+ (): Factor[] => [+ CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID,+ CEL_ATTRIBUTE_RESOURCE_PROJECT_ID,+ CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID,+ CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,+ CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,+ CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL,+ ],+ []+ );++ // Subscribe to reactive store data so the memo recomputes when settings load.+ const environmentOptions = useVueState(() => getEnvironmentIdOptions());+ const classificationOptions = useVueState(() =>+ getClassificationLevelOptions()+ );++ const factorOptionsMap = useMemo((): Map<Factor, OptionConfig> => {+ const workspaceName = actuatorStore.workspaceResourceName;+ return factorList.reduce((map, factor) => {+ switch (factor) {+ case CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID:+ map.set(factor, { options: environmentOptions });+ break;+ case CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID:+ map.set(factor, getInstanceIdOptionConfig());+ break;+ case CEL_ATTRIBUTE_RESOURCE_PROJECT_ID:+ map.set(factor, getProjectIdOptionConfig());+ break;+ case CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL:+ map.set(factor, { options: classificationOptions });+ break;+ case CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME:+ map.set(factor, getDatabaseIdOptionConfig(workspaceName));+ break;+ default:+ map.set(factor, { options: [] });+ }+ return map;+ }, new Map<Factor, OptionConfig>());+ }, [environmentOptions, classificationOptions]);++ useEffect(() => {+ const load = async () => {+ const policy = await policyStore.getOrFetchPolicyByParentAndType({+ parentPath: actuatorStore.workspaceResourceName,+ policyType: PolicyType.MASKING_RULE,+ });+ if (policy) {+ const rules =+ policy.policy?.case === "maskingRulePolicy"+ ? policy.policy.value.rules+ : [];+ setItems(rules.map((rule) => ({ mode: "NORMAL", rule })));+ }+ await Promise.all([+ settingStore.getOrFetchSettingByName(+ Setting_SettingName.SEMANTIC_TYPES,+ true+ ),+ settingStore.getOrFetchSettingByName(+ Setting_SettingName.DATA_CLASSIFICATION,+ true+ ),+ ]);+ };+ load();+ }, []);++ const upsertPolicy = useCallback(async (currentItems: MaskingRuleItem[]) => {+ const patch: Partial<Policy> = {+ type: PolicyType.MASKING_RULE,+ resourceType: PolicyResourceType.WORKSPACE,+ policy: {+ case: "maskingRulePolicy",+ value: create(MaskingRulePolicySchema, {+ rules: currentItems+ .filter((item) => item.mode === "NORMAL")+ .map((item) => item.rule),+ }),+ },+ };+ await policyStore.upsertPolicy({+ parentPath: actuatorStore.workspaceResourceName,+ policy: patch,+ });+ }, []);++ const addNewRule = () => {+ const newItem: MaskingRuleItem = {+ mode: "CREATE",+ rule: create(MaskingRulePolicy_MaskingRuleSchema, { id: uuidv4() }),+ };+ setItems((prev) => [...prev, newItem]);+ };++ const onEdit = (index: number) => {+ setItems((prev) => {+ const next = [...prev];+ next[index] = { ...next[index], mode: "EDIT" };+ return next;+ });+ };++ const onCancel = (index: number) => {+ setItems((prev) => {+ const next = [...prev];+ const item = next[index];+ if (item.mode === "CREATE") {+ next.splice(index, 1);+ } else {+ next[index] = { ...item, mode: "NORMAL" };+ }+ return next;+ });+ };++ const onConfirm = async (rule: MaskingRulePolicy_MaskingRule) => {+ if (processing) return;+ const index = items.findIndex((item) => item.rule.id === rule.id);+ if (index < 0) return;++ const isCreate = items[index].mode === "CREATE";+ const nextItems: MaskingRuleItem[] = items.map((item, i) =>+ i === index ? { mode: "NORMAL", rule } : item+ );++ setProcessing(true);+ setItems(nextItems);+ try {+ await upsertPolicy(nextItems);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t(`common.${isCreate ? "created" : "updated"}`),+ });+ } finally {+ setProcessing(false);+ }+ };++ const onRuleDelete = async (index: number) => {+ const item = items[index];+ const nextItems = items.filter((_, i) => i !== index);+ setItems(nextItems);+ if (item.mode === "CREATE") return;++ await upsertPolicy(nextItems);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.deleted"),+ });+ };++ const onReorder = (itemToMove: MaskingRuleItem, offset: number) => {+ setItems((prev) => {+ const idx = prev.findIndex((it) => it.rule.id === itemToMove.rule.id);+ if (idx < 0) return prev;+ const next = [...prev];+ arraySwap(next, idx, idx + offset);+ return next;+ });+ };++ const onReorderSubmit = async () => {+ await upsertPolicy(items);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ setReorderRules(false);+ };++ return (+ <div className="w-full px-4 py-4 flex flex-col gap-y-4">+ <FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} />+ {hasSensitiveDataFeature && (+ <div className="rounded-md border border-blue-200 bg-blue-50 text-blue-800 px-4 py-3 text-sm">+ {t("custom-approval.rule.first-match-wins")}+ </div>+ )}++ {/* Toolbar */}+ <div className="flex flex-row items-center justify-end">+ {reorderRules ? (+ <div className="flex items-center gap-x-2">+ <Button+ variant="outline"+ disabled={processing}+ onClick={() => {+ setReorderRules(false);+ policyStore+ .getOrFetchPolicyByParentAndType({+ parentPath: actuatorStore.workspaceResourceName,+ policyType: PolicyType.MASKING_RULE,+ })+ .then((policy) => {+ if (policy) {+ const rules =+ policy.policy?.case === "maskingRulePolicy"+ ? policy.policy.value.rules+ : [];+ setItems(rules.map((rule) => ({ mode: "NORMAL", rule })));+ }+ });+ }}+ >+ {t("common.cancel")}+ </Button>+ <Button disabled={processing} onClick={onReorderSubmit}>+ {t("common.confirm")}+ </Button>+ </div>+ ) : (+ <div className="flex items-center gap-x-2">+ <Button+ variant="outline"+ disabled={+ !hasPermission || !hasSensitiveDataFeature || items.length <= 1+ }+ onClick={() => setReorderRules(true)}+ >+ <ListOrdered className="h-4 w-4" />+ {t("settings.sensitive-data.global-rules.re-order")}+ </Button>+ <Button+ disabled={!hasPermission || !hasSensitiveDataFeature}+ onClick={addNewRule}+ >+ <Plus className="h-4 w-4" />+ {t("common.add")}+ </Button>+ </div>+ )}+ </div>++ {/* Description */}+ <div className="textinfolabel">+ {t("settings.sensitive-data.global-rules.description")}{" "}+ <a+ href="https://docs.bytebase.com/security/data-masking/overview/?source=console"+ target="_blank"+ rel="noopener noreferrer"+ className="text-accent hover:underline"+ >+ {t("common.learn-more")}+ </a>+ </div>++ {/* Empty state */}+ {items.length === 0 && (+ <div className="py-12 border rounded-sm flex items-center justify-center text-control-placeholder text-sm">+ {t("common.no-data")}+ </div>+ )}++ {/* Rule list */}+ {items.map((item, index) => (+ <div key={item.rule.id} className="flex items-start gap-x-5">+ {item.mode === "NORMAL" &&+ hasPermission &&+ hasSensitiveDataFeature && (+ <div>+ {reorderRules ? (+ <div className="pt-2 flex flex-col">+ {index > 0 && (+ <button+ type="button"+ className="w-6 h-6 flex items-center justify-center rounded hover:bg-gray-100"+ onClick={() => onReorder(item, -1)}+ >+ <ChevronUp className="w-4 h-4" />+ </button>+ )}+ {index !== items.length - 1 && (+ <button+ type="button"+ className="w-6 h-6 flex items-center justify-center rounded hover:bg-gray-100"+ onClick={() => onReorder(item, 1)}+ >+ <ChevronDown className="w-4 h-4" />+ </button>+ )}+ </div>+ ) : (+ <div className="pt-2">+ <button+ type="button"+ className="w-6 h-6 flex items-center justify-center rounded hover:bg-gray-100"+ onClick={() => onEdit(index)}+ >+ <Pencil className="w-4 h-4" />+ </button>+ </div>+ )}+ </div>+ )}++ <div+ className={`pb-5 w-full ${+ item.mode === "NORMAL" ? "" : "ml-10.5"+ } ${index === items.length - 1 ? "" : "border-b"}`}+ >+ <MaskingRuleConfig+ key={`expr-${item.rule.id}`}+ index={index + 1}+ disabled={processing}+ maskingRule={item.rule}+ readonly={item.mode === "NORMAL" || reorderRules}+ factorList={factorList}+ optionConfigMap={factorOptionsMap}+ allowDelete={item.mode === "EDIT"}+ onCancel={() => onCancel(index)}+ onDelete={() => onRuleDelete(index)}+ onConfirm={(rule) => onConfirm(rule)}+ />+ </div>+ </div>+ ))}+ </div>+ );+}diff --git a/frontend/src/react/pages/settings/SemanticTypesPage.tsx b/frontend/src/react/pages/settings/SemanticTypesPage.tsxindex 56479eb88d..b8aa035a4b 100644--- a/frontend/src/react/pages/settings/SemanticTypesPage.tsx+++ b/frontend/src/react/pages/settings/SemanticTypesPage.tsx@@ -3,16 +3,16 @@ import { Check, Info, Pencil, Plus, Trash2, Undo2, X } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";+import { FeatureAttention } from "@/react/components/FeatureAttention";import { Button } from "@/react/components/ui/button";import { Input } from "@/react/components/ui/input";import { useVueState } from "@/react/hooks/useVueState";import {pushNotification,- useActuatorV1Store,useSettingV1Store,useSubscriptionV1Store,} from "@/store";-import { getSemanticTemplateList, instanceLimitFeature } from "@/types";+import { getSemanticTemplateList } from "@/types";import type {Algorithm,SemanticTypeSetting_SemanticType,@@ -29,10 +29,7 @@ import {Setting_SettingName,SettingValueSchema as SettingSettingValueSchema,} from "@/types/proto-es/v1/setting_service_pb";-import {- PlanFeature,- PlanType,-} from "@/types/proto-es/v1/subscription_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import { hasWorkspacePermissionV2 } from "@/utils";type SemanticItemMode = "NORMAL" | "CREATE" | "EDIT";@@ -104,17 +101,11 @@ export function SemanticTypesPage() {const settingStore = useSettingV1Store();const subscriptionStore = useSubscriptionV1Store();- const actuatorStore = useActuatorV1Store();const hasPermission = hasWorkspacePermissionV2("bb.policies.update");const hasSensitiveDataFeature = useVueState(() =>subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING));- const existInstanceWithoutLicense = useVueState(- () =>- actuatorStore.totalInstanceCount > actuatorStore.activatedInstanceCount &&- instanceLimitFeature.has(PlanFeature.FEATURE_DATA_MASKING)- );const isReadonly = !hasPermission || !hasSensitiveDataFeature;const [items, setItems] = useState<SemanticItem[]>([]);@@ -370,10 +361,7 @@ export function SemanticTypesPage() {return (<div className="w-full px-4 py-4 flex flex-col gap-y-4">- <FeatureAttentionBanner- hasFeature={hasSensitiveDataFeature}- existInstanceWithoutLicense={existInstanceWithoutLicense}- />+ <FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} /><div className="flex justify-end"><div className="flex items-center gap-x-2"><Button@@ -470,71 +458,6 @@ export function SemanticTypesPage() {);}-// --- FeatureAttentionBanner -----function FeatureAttentionBanner({- hasFeature,- existInstanceWithoutLicense,-}: {- hasFeature: boolean;- existInstanceWithoutLicense: boolean;-}) {- const { t } = useTranslation();- const subscriptionStore = useSubscriptionV1Store();-- const showBanner = !hasFeature || existInstanceWithoutLicense;- if (!showBanner) return null;-- const isWarning = !hasFeature;- // eslint-disable-next-line @intlify/vue-i18n/no-missing-keys- const featureDesc = t(- "dynamic.subscription.features.FEATURE_DATA_MASKING.desc"- );-- let description: string;- if (!hasFeature) {- const startTrial = subscriptionStore.isTrialing- ? ""- : t("subscription.trial-for-days", {- days: subscriptionStore.trialingDays,- });- const requiredPlan = subscriptionStore.getMinimumRequiredPlan(- PlanFeature.FEATURE_DATA_MASKING- );- if (- requiredPlan === PlanType.FREE &&- subscriptionStore.hasFeature(PlanFeature.FEATURE_DATA_MASKING)- ) {- description = `${featureDesc}\n${startTrial}`;- } else {- const trialText = t("subscription.required-plan-with-trial", {- requiredPlan: t(- `subscription.plan.${PlanType[requiredPlan].toLowerCase()}.title`- ),- startTrial,- });- description = `${featureDesc}\n${trialText}`;- }- } else {- const attention = t(- "subscription.instance-assignment.missing-license-attention"- );- description = `${featureDesc}\n${attention}`;- }-- return (- <div- className={`rounded-md border px-4 py-3 text-sm whitespace-pre-line ${- isWarning- ? "border-yellow-300 bg-yellow-50 text-yellow-800"- : "border-blue-200 bg-blue-50 text-blue-800"- }`}- >- {description}- </div>- );-}-// --- MaskingAlgorithmDrawer (React) ---interface MaskingAlgorithmDrawerProps {diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.tsindex 1784c8b1b3..45cfd05219 100644--- a/frontend/src/router/dashboard/workspace.ts+++ b/frontend/src/router/dashboard/workspace.ts@@ -261,8 +261,8 @@ const workspaceRoutes: RouteRecordRaw[] = [title: () => t("settings.sidebar.global-masking"),requiredPermissionList: () => ["bb.policies.getMaskingRulePolicy"],},- component: () => import("@/views/SettingWorkspaceDataMasking.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: () => ({ page: "GlobalMaskingPage" }),},{path: "semantic-types",diff --git a/frontend/src/views/SettingWorkspaceDataMasking.vue b/frontend/src/views/SettingWorkspaceDataMasking.vuedeleted file mode 100644index efd466b540..0000000000--- a/frontend/src/views/SettingWorkspaceDataMasking.vue+++ /dev/null@@ -1,19 +0,0 @@-<template>- <div class="w-full px-4 py-4 flex flex-col gap-y-4">- <FeatureAttention- :feature="PlanFeature.FEATURE_DATA_MASKING"- />- <BBAttention v-if="hasSensitiveDataFeature" type="info" :description="$t('custom-approval.rule.first-match-wins')" />- <GlobalMaskingRulesView />- </div>-</template>--<script lang="ts" setup>-import { BBAttention } from "@/bbkit";-import { FeatureAttention } from "@/components/FeatureGuard";-import { GlobalMaskingRulesView } from "@/components/SensitiveData";-import { featureToRef } from "@/store";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";--const hasSensitiveDataFeature = featureToRef(PlanFeature.FEATURE_DATA_MASKING);-</script>