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): migrate database groups pages to React (#19855)
Danny Xuf6f3ffa48658
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vuedeleted file mode 100644index dfa2db68ac..0000000000--- a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue+++ /dev/null@@ -1,253 +0,0 @@-<template>- <div class="flex-1 flex flex-col">- <div class="flex-1 mb-6">- <div class="w-full">- <p class="font-medium text-main mb-2">{{ $t("common.name") }}</p>- <NInput- v-model:value="state.placeholder"- :disabled="readonly"- :maxlength="200"- />- <div class="mt-2">- <ResourceIdField- ref="resourceIdField"- editing-class="mt-4"- resource-type="database-group"- :readonly="!isCreating"- :value="state.resourceId"- :resource-title="state.placeholder"- :fetch-resource="- (id) =>- dbGroupStore.getOrFetchDBGroupByName(- `${props.project.name}/${databaseGroupNamePrefix}${id}`,- { silent: true, view: DatabaseGroupView.FULL }- )- "- />- </div>- </div>- <NDivider />- <div class="w-full grid grid-cols-5 gap-x-6">- <div class="col-span-3">- <p class="pl-1 font-medium text-main mb-2">- {{ $t("database-group.condition.self") }}- </p>- <ExprEditor- :expr="state.expr"- :readonly="readonly"- :factor-list="FactorList"- :option-config-map="getDatabaseGroupOptionConfigMap(project.name)"- />- </div>- <div class="col-span-2">- <MatchedDatabaseView- :project="project.name"- :expr="state.expr"- :matched-database-names="readonly ? matchedDatabaseNames : undefined"- />- </div>- </div>- </div>-- <div v-if="!readonly" class="sticky bottom-0 z-10">- <div- class="flex justify-end w-full py-4 border-t border-block-border bg-white gap-x-3"- >- <NButton @click="$emit('dismiss')">{{ $t("common.cancel") }}</NButton>- <NButton type="primary" :disabled="!allowConfirm" @click="doConfirm">- {{ isCreating ? $t("common.save") : $t("common.confirm") }}- </NButton>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { cloneDeep, head, isEqual } from "lodash-es";-import { NButton, NDivider, NInput } from "naive-ui";-import { computed, reactive, ref, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import ExprEditor from "@/components/ExprEditor";-import type { ConditionGroupExpr } from "@/plugins/cel";-import {- buildCELExpr,- emptySimpleExpr,- resolveCELExpr,- validateSimpleExpr,- wrapAsGroup,-} from "@/plugins/cel";-import { pushNotification, useDBGroupStore } from "@/store";-import {- databaseGroupNamePrefix,- getProjectNameAndDatabaseGroupName,-} from "@/store/modules/v1/common";-import { isValidDatabaseGroupName } from "@/types";-import type { Expr as CELExpr } from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";-import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";-import {- type DatabaseGroup,- DatabaseGroupSchema,- DatabaseGroupView,-} from "@/types/proto-es/v1/database_group_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import {- batchConvertCELStringToParsedExpr,- batchConvertParsedExprToCELString,-} from "@/utils";-import { ResourceIdField } from "../v2";-import MatchedDatabaseView from "./MatchedDatabaseView.vue";-import { FactorList, getDatabaseGroupOptionConfigMap } from "./utils";--const props = defineProps<{- readonly: boolean;- project: Project;- databaseGroup?: DatabaseGroup;-}>();--const emit = defineEmits<{- (event: "dismiss"): void;- (event: "created", databaseGroupName: string): void;-}>();--type LocalState = {- resourceId: string;- placeholder: string;- selectedDatabaseGroupId?: string;- expr: ConditionGroupExpr;-};--const { t } = useI18n();-const dbGroupStore = useDBGroupStore();-const state = reactive<LocalState>({- resourceId: "",- placeholder: "",- expr: wrapAsGroup(emptySimpleExpr()),-});-const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();--const isCreating = computed(() => props.databaseGroup === undefined);--const matchedDatabaseNames = computed(() => {- return props.databaseGroup?.matchedDatabases.map((db) => db.name) ?? [];-});--watchEffect(async () => {- const databaseGroup = props.databaseGroup;- if (!databaseGroup || !isValidDatabaseGroupName(databaseGroup.name)) {- return;- }-- const databaseGroupEntity = databaseGroup;- const [, databaseGroupName] = getProjectNameAndDatabaseGroupName(- databaseGroup.name- );- state.resourceId = databaseGroupName;- state.placeholder = databaseGroupEntity.title;-- if (databaseGroup.databaseExpr?.expression) {- // Convert CEL expression to simple expression- const expressions = [databaseGroup.databaseExpr.expression];- const exprList = await batchConvertCELStringToParsedExpr(expressions);- if (exprList.length > 0) {- const simpleExpr = resolveCELExpr(exprList[0]);- state.expr = cloneDeep(wrapAsGroup(simpleExpr));- }- }-});--const allowConfirm = computed(() => {- return (- resourceIdField.value?.resourceId &&- state.placeholder &&- validateSimpleExpr(state.expr)- );-});--const doConfirm = async () => {- const formState = {- ...state,- resourceId: resourceIdField.value?.resourceId || "",- };- if (!formState || !allowConfirm.value) {- return;- }-- let celExpr: CELExpr | undefined = undefined;- try {- celExpr = await buildCELExpr(formState.expr);- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: `CEL expression error occurred`,- description: (error as Error).message,- });- return;- }-- const celStrings = await batchConvertParsedExprToCELString([celExpr!]);- const celString = head(celStrings);- if (!celString) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: `CEL expression error occurred`,- description: "CEL expression is empty",- });- return;- }-- if (isCreating.value) {- const resourceId = formState.resourceId;- await dbGroupStore.createDatabaseGroup({- projectName: props.project.name,- databaseGroup: create(DatabaseGroupSchema, {- name: `${props.project.name}/databaseGroups/${resourceId}`,- title: formState.placeholder,- databaseExpr: create(ExprSchema, {- expression: celString,- }),- }),- databaseGroupId: resourceId,- });- emit("created", resourceId);- } else {- if (!props.databaseGroup) {- return;- }-- const updateMask: string[] = [];- if (!isEqual(props.databaseGroup.title, formState.placeholder)) {- updateMask.push("title");- }- if (- !isEqual(- props.databaseGroup.databaseExpr,- create(ExprSchema, {- expression: celString,- })- )- ) {- updateMask.push("database_expr");- }- await dbGroupStore.updateDatabaseGroup(- {- ...props.databaseGroup,- title: formState.placeholder,- databaseExpr: create(ExprSchema, {- expression: celString,- }),- },- updateMask- );- }-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: isCreating.value ? t("common.created") : t("common.updated"),- });- emit("dismiss");-};-</script>diff --git a/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue b/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vuedeleted file mode 100644index ca7d556859..0000000000--- a/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue+++ /dev/null@@ -1,266 +0,0 @@-<template>- <div class="mb-2 flex flex-row items-center">- <span class="font-medium text-main mr-2">{{ $t("common.databases") }}</span>- <BBSpin v-if="state.loading" :size="20" class="opacity-60" />- </div>-- <p- v-if="state.matchingError"- class="my-2 text-sm border border-red-600 px-2 py-1 rounded-lg bg-red-50 text-red-600"- >- {{ state.matchingError }}- </p>-- <NCollapse- class="border p-2 rounded-lg"- v-model:expanded-names="state.collapseExpandedNames"- >- <NCollapseItem- v-for="item in state.databaseMatchLists"- :key="item.name"- :title="item.title"- :disabled="item.databaseList.length === 0"- :name="item.name"- >- <template #header-extra>{{ item.getTotal ? item.getTotal() : undefined }}</template>- <div class="flex flex-col gap-y-2 w-full max-h-48 overflow-y-auto">- <div class="">- <div- v-for="database in item.databaseList"- :key="database.name"- class="w-full flex flex-row justify-between items-center px-2 py-1 gap-x-2"- >- <DatabaseV1Name :database="database" />- <div class="flex-1 flex flex-row justify-end items-center shrink-0">- <InstanceV1Name- :instance="getInstanceResource(database)"- :link="false"- />- <EnvironmentV1Name- class="ml-1 text-sm text-gray-400 max-w-31"- :environment="getDatabaseEnvironment(database)"- :link="false"- />- </div>- </div>- </div>- <NButton- v-if="checkHasNext(item)"- size="small"- quaternary- :loading="item.loading"- @click="loadMore(item)"- >- {{ $t("common.load-more") }}- </NButton>- </div>- </NCollapseItem>- </NCollapse>-</template>--<script lang="ts" setup>-import type { ConnectError } from "@connectrpc/connect";-import { useDebounceFn } from "@vueuse/core";-import { NButton, NCollapse, NCollapseItem } from "naive-ui";-import { computed, reactive, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { BBSpin } from "@/bbkit";-import {- DatabaseV1Name,- EnvironmentV1Name,- InstanceV1Name,-} from "@/components/v2";-import type { ConditionGroupExpr } from "@/plugins/cel";-import { validateSimpleExpr } from "@/plugins/cel";-import { useDatabaseV1Store, useDBGroupStore } from "@/store";-import { DEBOUNCE_SEARCH_DELAY, isValidDatabaseName } from "@/types";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import {- getDatabaseEnvironment,- getDefaultPagination,- getInstanceResource,-} from "@/utils";--interface DatabaseMatchList<T> {- token: T;- loading: boolean;- getTotal?: () => number;- databaseList: Database[];- name: "matched" | "unmatched";- title: string;- hasNext: (token: T) => boolean;- loadMore: (token: T) => Promise<{ databases: Database[]; token: T }>;-}--type AnyDatabaseMatchList =- | DatabaseMatchList<number>- | DatabaseMatchList<string>;--const checkHasNext = (item: AnyDatabaseMatchList): boolean => {- return (item.hasNext as (token: number | string) => boolean)(item.token);-};--interface LocalState {- loading: boolean;- matchingError?: string;- databaseMatchLists: AnyDatabaseMatchList[];- collapseExpandedNames: string[];-}--const props = defineProps<{- project: string;- expr: ConditionGroupExpr;- // When provided (in readonly mode), skip the validateOnly API call- // and use these pre-fetched matched database names directly- matchedDatabaseNames?: string[];-}>();--const { t } = useI18n();-const matchedDatabaseNameList = ref<string[]>([]);-const pageSize = computed(() => getDefaultPagination());-const dbGroupStore = useDBGroupStore();-const databaseStore = useDatabaseV1Store();--const loadMoreMatched = async (index: number) => {- const previous = index;- const next = previous + pageSize.value;- const databaseNames = matchedDatabaseNameList.value.slice(previous, next);- await databaseStore.batchGetOrFetchDatabases(databaseNames);-- return {- databases: databaseNames.map(databaseStore.getDatabaseByName),- token: next,- };-};--const loadMoreUnmatched = async (token: string) => {- let unmatched: Database[] = [];- let pageToken = token;- while (true) {- const { databases, nextPageToken } = await databaseStore.fetchDatabases({- pageToken,- pageSize: pageSize.value,- parent: props.project,- silent: true,- });- pageToken = nextPageToken;- unmatched = databases.filter(- (db) => !matchedDatabaseNameList.value.includes(db.name)- );- if (unmatched.length > 0 || !pageToken) {- break;- }- }- return {- databases: unmatched,- token: pageToken,- };-};--const getMatched = (title: string): DatabaseMatchList<number> => ({- token: 0,- loading: false,- databaseList: [],- title,- getTotal: () => matchedDatabaseNameList.value.length,- name: "matched",- hasNext: (token: number) => token < matchedDatabaseNameList.value.length,- loadMore: loadMoreMatched,-});--const getUnMatched = (title: string): DatabaseMatchList<string> => ({- token: "",- loading: false,- databaseList: [],- title,- name: "unmatched",- hasNext: (token: string) => !!token,- loadMore: loadMoreUnmatched,-});--const getInitialState = () => [- getMatched(t("database-group.matched-database")),- getUnMatched(t("database-group.unmatched-database")),-];--const state = reactive<LocalState>({- loading: false,- databaseMatchLists: getInitialState(),- collapseExpandedNames: [],-});--// biome-ignore format: ESLint requires trailing comma for generic type parameter-const loadMoreDatabase = async <T,>(item: DatabaseMatchList<T>) => {- item.loading = true;- try {- const { databases, token } = await item.loadMore(item.token);- item.token = token;- item.databaseList.push(- ...databases.filter((database) => isValidDatabaseName(database.name))- );- } finally {- item.loading = false;- }-};--const loadMore = (item: AnyDatabaseMatchList) => {- if (item.name === "matched") {- return loadMoreDatabase(item as DatabaseMatchList<number>);- }- return loadMoreDatabase(item as DatabaseMatchList<string>);-};--watch(- [- () => state.databaseMatchLists[0].databaseList.length,- () => state.databaseMatchLists[1].databaseList.length,- ],- ([matchedLength, unmatchedLength]) => {- state.collapseExpandedNames = [];- if (matchedLength > 0) {- state.collapseExpandedNames.push("matched");- }- if (unmatchedLength > 0) {- state.collapseExpandedNames.push("unmatched");- }- },- {- immediate: true,- }-);--const updateDatabaseMatchingState = useDebounceFn(async () => {- if (!validateSimpleExpr(props.expr)) {- state.matchingError = undefined;- state.databaseMatchLists = getInitialState();- return;- }-- state.loading = true;- try {- // When matchedDatabaseNames is provided (readonly mode), use it directly- // instead of calling createDatabaseGroup with validateOnly- const matchedDatabaseList = props.matchedDatabaseNames- ? props.matchedDatabaseNames- : await dbGroupStore.fetchDatabaseGroupMatchList({- projectName: props.project,- expr: props.expr,- });-- state.matchingError = undefined;- state.databaseMatchLists = getInitialState();- matchedDatabaseNameList.value = matchedDatabaseList;- await Promise.all(state.databaseMatchLists.map((item) => loadMore(item)));- } catch (error) {- state.matchingError = (error as ConnectError).message;- } finally {- state.loading = false;- }-}, DEBOUNCE_SEARCH_DELAY);--watch(- [() => props.project, () => props.expr, () => props.matchedDatabaseNames],- () => updateDatabaseMatchingState(),- { deep: true, immediate: true }-);-</script>diff --git a/frontend/src/components/DatabaseGroup/ProjectDatabaseGroupPanel.vue b/frontend/src/components/DatabaseGroup/ProjectDatabaseGroupPanel.vuedeleted file mode 100644index e83878fd52..0000000000--- a/frontend/src/components/DatabaseGroup/ProjectDatabaseGroupPanel.vue+++ /dev/null@@ -1,93 +0,0 @@-<template>- <DatabaseGroupDataTable- :database-group-list="filteredDbGroupList"- :loading="!ready"- :show-actions="allowDelete"- :on-row-click="handleDatabaseGroupClick"- @delete="handleDelete"- />-</template>--<script lang="ts" setup>-import { useDialog } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import DatabaseGroupDataTable from "@/components/DatabaseGroup/DatabaseGroupDataTable.vue";-import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/router/dashboard/projectV1";-import {- useDBGroupListByProject,- useDBGroupStore,- useGracefulRequest,-} from "@/store";-import { getProjectNameAndDatabaseGroupName } from "@/store/modules/v1/common";-import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { hasProjectPermissionV2 } from "@/utils";--const props = defineProps<{- project: Project;- filter: string;-}>();--const router = useRouter();-const { t } = useI18n();-const dialog = useDialog();-const dbGroupStore = useDBGroupStore();--const { dbGroupList, ready } = useDBGroupListByProject(- computed(() => props.project.name)-);--const allowDelete = computed(() => {- return hasProjectPermissionV2(props.project, "bb.databaseGroups.delete");-});--const filteredDbGroupList = computed(() => {- const filter = props.filter.trim().toLowerCase();- if (!filter) {- return dbGroupList.value;- }- return dbGroupList.value.filter((group) => {- return (- group.name.toLowerCase().includes(filter) ||- group.title.toLowerCase().includes(filter)- );- });-});--const handleDatabaseGroupClick = (- event: MouseEvent,- databaseGroup: DatabaseGroup-) => {- const [projectId, databaseGroupName] = getProjectNameAndDatabaseGroupName(- databaseGroup.name- );- const url = router.resolve({- name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,- params: {- projectId,- databaseGroupName,- },- }).fullPath;- if (event.ctrlKey || event.metaKey) {- window.open(url, "_blank");- } else {- router.push(url);- }-};--const handleDelete = (databaseGroup: DatabaseGroup) => {- dialog.warning({- title: t("database-group.delete-group", { name: databaseGroup.title }),- content: t("common.cannot-undo-this-action"),- negativeText: t("common.cancel"),- positiveText: t("common.delete"),- onPositiveClick: () => {- useGracefulRequest(() =>- dbGroupStore.deleteDatabaseGroup(databaseGroup.name)- );- },- });-};-</script>diff --git a/frontend/src/react/ProjectAuditLogPageMount.vue b/frontend/src/react/ProjectAuditLogPageMount.vuedeleted file mode 100644index cd8962f2d2..0000000000--- a/frontend/src/react/ProjectAuditLogPageMount.vue+++ /dev/null@@ -1,49 +0,0 @@-<template>- <div ref="container" class="h-full" />-</template>--<script lang="ts" setup>-import { onMounted, onUnmounted, ref, watch } from "vue";-import { useI18n } from "vue-i18n";--const props = defineProps<{- projectId: string;-}>();--const { locale } = useI18n();-const container = ref<HTMLElement>();-// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import-let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any--async function render() {- if (!container.value) return;- const [{ mountReactPage, updateReactPage }, i18nModule] = await Promise.all([- import("./mount"),- import("./i18n"),- ]);- if (i18nModule.default.language !== locale.value) {- await i18nModule.default.changeLanguage(locale.value);- }- const pageProps = { projectId: props.projectId };- if (!root) {- root = await mountReactPage(- container.value,- "ProjectAuditLogPage",- pageProps- );- } else {- await updateReactPage(root, "ProjectAuditLogPage", pageProps);- }-}--onMounted(() => render());-watch(locale, () => render());-watch(- () => props.projectId,- () => render()-);-onUnmounted(() => {- root?.unmount();- root = null;-});-</script>diff --git a/frontend/src/react/ProjectDatabasesPageMount.vue b/frontend/src/react/ProjectDatabasesPageMount.vuedeleted file mode 100644index 64456ea947..0000000000--- a/frontend/src/react/ProjectDatabasesPageMount.vue+++ /dev/null@@ -1,49 +0,0 @@-<template>- <div ref="container" class="h-full" />-</template>--<script lang="ts" setup>-import { onMounted, onUnmounted, ref, watch } from "vue";-import { useI18n } from "vue-i18n";--const props = defineProps<{- projectId: string;-}>();--const { locale } = useI18n();-const container = ref<HTMLElement>();-// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import-let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any--async function render() {- if (!container.value) return;- const [{ mountReactPage, updateReactPage }, i18nModule] = await Promise.all([- import("./mount"),- import("./i18n"),- ]);- if (i18nModule.default.language !== locale.value) {- await i18nModule.default.changeLanguage(locale.value);- }- const pageProps = { projectId: props.projectId };- if (!root) {- root = await mountReactPage(- container.value,- "ProjectDatabasesPage",- pageProps- );- } else {- await updateReactPage(root, "ProjectDatabasesPage", pageProps);- }-}--onMounted(() => render());-watch(locale, () => render());-watch(- () => props.projectId,- () => render()-);-onUnmounted(() => {- root?.unmount();- root = null;-});-</script>diff --git a/frontend/src/react/ProjectGitOpsPageMount.vue b/frontend/src/react/ProjectGitOpsPageMount.vuedeleted file mode 100644index 55cf5da2f3..0000000000--- a/frontend/src/react/ProjectGitOpsPageMount.vue+++ /dev/null@@ -1,49 +0,0 @@-<template>- <div ref="container" class="h-full" />-</template>--<script lang="ts" setup>-import { onMounted, onUnmounted, ref, watch } from "vue";-import { useI18n } from "vue-i18n";--const props = defineProps<{- projectId: string;-}>();--const { locale } = useI18n();-const container = ref<HTMLElement>();-// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import-let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any--async function render() {- if (!container.value) return;- const [{ mountReactPage, updateReactPage }, i18nModule] = await Promise.all([- import("./mount"),- import("./i18n"),- ]);- if (i18nModule.default.language !== locale.value) {- await i18nModule.default.changeLanguage(locale.value);- }- const pageProps = { projectId: props.projectId };- if (!root) {- root = await mountReactPage(- container.value,- "ProjectGitOpsPage",- pageProps- );- } else {- await updateReactPage(root, "ProjectGitOpsPage", pageProps);- }-}--onMounted(() => render());-watch(locale, () => render());-watch(- () => props.projectId,- () => render()-);-onUnmounted(() => {- root?.unmount();- root = null;-});-</script>diff --git a/frontend/src/react/ReactPageMount.vue b/frontend/src/react/ReactPageMount.vueindex 5d86074ec9..83fd12a1b1 100644--- a/frontend/src/react/ReactPageMount.vue+++ b/frontend/src/react/ReactPageMount.vue@@ -3,18 +3,26 @@</template><script lang="ts" setup>-import { onMounted, onUnmounted, ref, watch } from "vue";+defineOptions({ inheritAttrs: false });++import { computed, onMounted, onUnmounted, ref, useAttrs, watch } from "vue";import { useI18n } from "vue-i18n";const props = defineProps<{page: string;}>();+const attrs = useAttrs();const { locale } = useI18n();const container = ref<HTMLElement>();// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic importlet root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any+const pageProps = computed(() => {+ const a = attrs as Record<string, unknown>;+ return Object.keys(a).length > 0 ? { ...a } : undefined;+});+async function render() {if (!container.value) return;const [{ mountReactPage, updateReactPage }, i18nModule] = await Promise.all([@@ -25,18 +33,15 @@ async function render() {await i18nModule.default.changeLanguage(locale.value);}if (!root) {- root = await mountReactPage(container.value, props.page);+ root = await mountReactPage(container.value, props.page, pageProps.value);} else {- await updateReactPage(root, props.page);+ await updateReactPage(root, props.page, pageProps.value);}}onMounted(() => render());watch(locale, () => render());-watch(- () => props.page,- () => render()-);+watch([() => props.page, pageProps], () => render());onUnmounted(() => {root?.unmount();root = null;diff --git a/frontend/src/react/SQLReviewDetailPageMount.vue b/frontend/src/react/SQLReviewDetailPageMount.vuedeleted file mode 100644index fde86ce020..0000000000--- a/frontend/src/react/SQLReviewDetailPageMount.vue+++ /dev/null@@ -1,49 +0,0 @@-<template>- <div ref="container" class="h-full" />-</template>--<script lang="ts" setup>-import { onMounted, onUnmounted, ref, watch } from "vue";-import { useI18n } from "vue-i18n";--const props = defineProps<{- sqlReviewPolicySlug: string;-}>();--const { locale } = useI18n();-const container = ref<HTMLElement>();-// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import-let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any--async function render() {- if (!container.value) return;- const [{ mountReactPage, updateReactPage }, i18nModule] = await Promise.all([- import("./mount"),- import("./i18n"),- ]);- if (i18nModule.default.language !== locale.value) {- await i18nModule.default.changeLanguage(locale.value);- }- const pageProps = { sqlReviewPolicySlug: props.sqlReviewPolicySlug };- if (!root) {- root = await mountReactPage(- container.value,- "SQLReviewDetailPage",- pageProps- );- } else {- await updateReactPage(root, "SQLReviewDetailPage", pageProps);- }-}--onMounted(() => render());-watch(locale, () => render());-watch(- () => props.sqlReviewPolicySlug,- () => render()-);-onUnmounted(() => {- root?.unmount();- root = null;-});-</script>diff --git a/frontend/src/react/components/CustomApproval/RuleEditDialog.tsx b/frontend/src/react/components/CustomApproval/RuleEditDialog.tsxindex 4207e542e5..cef8791d0b 100644--- a/frontend/src/react/components/CustomApproval/RuleEditDialog.tsx+++ b/frontend/src/react/components/CustomApproval/RuleEditDialog.tsx@@ -1,6 +1,6 @@import { create } from "@bufbuild/protobuf";import { cloneDeep } from "lodash-es";-import { useEffect, useMemo, useReducer, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import type { ConditionGroupExpr } from "@/plugins/cel";import {@@ -62,8 +62,6 @@ export function RuleEditDialog({onSave,}: RuleEditDialogProps) {const { t } = useTranslation();- const [, forceUpdate] = useReducer((x: number) => x + 1, 0);-const [title, setTitle] = useState("");const [description, setDescription] = useState("");const [conditionExpr, setConditionExpr] = useState<ConditionGroupExpr>(@@ -248,7 +246,7 @@ export function RuleEditDialog({readonly={!allowAdmin}factorList={factorList}optionConfigMap={optionConfigMap}- onUpdate={forceUpdate}+ onUpdate={setConditionExpr}/></div>diff --git a/frontend/src/react/components/DatabaseGroupForm.tsx b/frontend/src/react/components/DatabaseGroupForm.tsxnew file mode 100644index 0000000000..1abce8f848--- /dev/null+++ b/frontend/src/react/components/DatabaseGroupForm.tsx@@ -0,0 +1,262 @@+import { create } from "@bufbuild/protobuf";+import { cloneDeep, head, isEqual } from "lodash-es";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ FactorList,+ getDatabaseGroupOptionConfigMap,+} from "@/components/DatabaseGroup/utils";+import type { ConditionGroupExpr } from "@/plugins/cel";+import {+ buildCELExpr,+ emptySimpleExpr,+ resolveCELExpr,+ validateSimpleExpr,+ wrapAsGroup,+} from "@/plugins/cel";+import { ExprEditor } from "@/react/components/ExprEditor";+import { MatchedDatabaseView } from "@/react/components/MatchedDatabaseView";+import { ResourceIdField } from "@/react/components/ResourceIdField";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { pushNotification, useDBGroupStore } from "@/store";+import {+ databaseGroupNamePrefix,+ getProjectNameAndDatabaseGroupName,+} from "@/store/modules/v1/common";+import type { ValidatedMessage } from "@/types";+import { isValidDatabaseGroupName } from "@/types";+import type { Expr as CELExpr } from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";+import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";+import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";+import {+ DatabaseGroupSchema,+ DatabaseGroupView,+} from "@/types/proto-es/v1/database_group_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import {+ batchConvertCELStringToParsedExpr,+ batchConvertParsedExprToCELString,+} from "@/utils";++interface DatabaseGroupFormProps {+ readonly: boolean;+ project: Project;+ databaseGroup?: DatabaseGroup;+ className?: string;+ onDismiss: () => void;+ onCreated?: (databaseGroupName: string) => void;+}++export function DatabaseGroupForm({+ readonly,+ project,+ databaseGroup,+ className,+ onDismiss,+ onCreated,+}: DatabaseGroupFormProps) {+ const { t } = useTranslation();+ const dbGroupStore = useDBGroupStore();++ const [title, setTitle] = useState("");+ const [resourceId, setResourceId] = useState("");+ const [resourceIdValid, setResourceIdValid] = useState(false);+ const [expr, setExpr] = useState<ConditionGroupExpr>(+ wrapAsGroup(emptySimpleExpr())+ );++ const isCreating = databaseGroup === undefined;++ const matchedDatabaseNames = useMemo(+ () => databaseGroup?.matchedDatabases.map((db) => db.name) ?? [],+ [databaseGroup]+ );++ // Initialize state from databaseGroup in editing mode+ useEffect(() => {+ if (!databaseGroup || !isValidDatabaseGroupName(databaseGroup.name)) {+ return;+ }++ const [, groupName] = getProjectNameAndDatabaseGroupName(+ databaseGroup.name+ );+ setResourceId(groupName);+ setTitle(databaseGroup.title);++ if (databaseGroup.databaseExpr?.expression) {+ batchConvertCELStringToParsedExpr([+ databaseGroup.databaseExpr.expression,+ ]).then((exprList) => {+ if (exprList.length > 0) {+ const simpleExpr = resolveCELExpr(exprList[0]);+ setExpr(cloneDeep(wrapAsGroup(simpleExpr)));+ }+ });+ }+ }, [databaseGroup]);++ // In edit mode, ResourceIdField is readonly and never fires onValidationChange,+ // so skip the resourceIdValid gate when editing.+ const allowConfirm = useMemo(() => {+ const idOk = isCreating ? resourceIdValid : true;+ return idOk && title.trim() !== "" && validateSimpleExpr(expr);+ }, [isCreating, resourceIdValid, title, expr]);++ // Duplicate-ID validation for creation: try to fetch the group and fail if it exists.+ const validateResourceId = useCallback(+ async (id: string): Promise<ValidatedMessage[]> => {+ try {+ const name = `${project.name}/${databaseGroupNamePrefix}${id}`;+ await dbGroupStore.getOrFetchDBGroupByName(name, {+ silent: true,+ view: DatabaseGroupView.FULL,+ });+ // If fetch succeeded, the group already exists+ return [{ type: "error", message: `${id} already exists` }];+ } catch {+ // Not found — ID is available+ return [];+ }+ },+ [project.name, dbGroupStore]+ );++ const doConfirm = async () => {+ if (!allowConfirm) return;++ let celExpr: CELExpr | undefined;+ try {+ celExpr = await buildCELExpr(expr);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "CEL expression error occurred",+ description: (error as Error).message,+ });+ return;+ }++ const celStrings = await batchConvertParsedExprToCELString([celExpr!]);+ const celString = head(celStrings);+ if (!celString) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "CEL expression error occurred",+ description: "CEL expression is empty",+ });+ return;+ }++ if (isCreating) {+ await dbGroupStore.createDatabaseGroup({+ projectName: project.name,+ databaseGroup: create(DatabaseGroupSchema, {+ name: `${project.name}/databaseGroups/${resourceId}`,+ title: title,+ databaseExpr: create(ExprSchema, { expression: celString }),+ }),+ databaseGroupId: resourceId,+ });+ onCreated?.(resourceId);+ } else {+ if (!databaseGroup) return;++ const updateMask: string[] = [];+ if (!isEqual(databaseGroup.title, title)) {+ updateMask.push("title");+ }+ if (+ !isEqual(+ databaseGroup.databaseExpr,+ create(ExprSchema, { expression: celString })+ )+ ) {+ updateMask.push("database_expr");+ }+ await dbGroupStore.updateDatabaseGroup(+ {+ ...databaseGroup,+ title,+ databaseExpr: create(ExprSchema, { expression: celString }),+ },+ updateMask+ );+ }++ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: isCreating ? t("common.created") : t("common.updated"),+ });+ onDismiss();+ };++ return (+ <div className={`flex-1 flex flex-col ${className ?? ""}`}>+ <div className="flex-1 mb-6 px-4">+ <div className="w-full">+ <p className="font-medium text-main mb-2">{t("common.name")}</p>+ <Input+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ disabled={readonly}+ maxLength={200}+ />+ <div className="mt-2">+ <ResourceIdField+ value={resourceId}+ resourceType="database-group"+ resourceName="database-group"+ resourceTitle={title}+ readonly={!isCreating}+ validate={isCreating ? validateResourceId : undefined}+ onChange={setResourceId}+ onValidationChange={setResourceIdValid}+ />+ </div>+ </div>++ <hr className="my-6" />++ <div className="w-full grid grid-cols-5 gap-x-6">+ <div className="col-span-3">+ <p className="pl-1 font-medium text-main mb-2">+ {t("database-group.condition.self")}+ </p>+ <ExprEditor+ expr={expr}+ readonly={readonly}+ factorList={FactorList}+ optionConfigMap={getDatabaseGroupOptionConfigMap(project.name)}+ onUpdate={setExpr}+ />+ </div>+ <div className="col-span-2">+ <MatchedDatabaseView+ project={project.name}+ expr={expr}+ matchedDatabaseNames={readonly ? matchedDatabaseNames : undefined}+ />+ </div>+ </div>+ </div>++ {!readonly && (+ <div className="sticky bottom-0 z-10">+ <div className="flex justify-end w-full py-4 border-t border-block-border bg-white gap-x-3">+ <Button variant="outline" onClick={onDismiss}>+ {t("common.cancel")}+ </Button>+ <Button disabled={!allowConfirm} onClick={doConfirm}>+ {isCreating ? t("common.save") : t("common.confirm")}+ </Button>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/react/components/ExprEditor.tsx b/frontend/src/react/components/ExprEditor.tsxindex 57394d3af3..23e6bbb1ed 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 { TFunction } from "i18next";+import { HelpCircle, Plus, Trash2, X } from "lucide-react";import type { ReactNode } from "react";import {createContext,@@ -12,20 +13,18 @@ import {} from "react";import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";-import {- factorText,- getOperatorListByFactor,-} from "@/components/ExprEditor/components/common";-import type { OptionConfig } from "@/components/ExprEditor/context";import type {ConditionExpr,ConditionGroupExpr,+ ConditionOperator,Factor,+ LogicalOperator,Operator,RawStringExpr,} from "@/plugins/cel";import {ExprType,+ getOperatorListByFactor as getRawOperatorListByFactor,isBooleanFactor,isCollectionOperator,isConditionExpr,@@ -50,8 +49,58 @@ import {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";+// ============================================================+// OptionConfig type+// ============================================================++export type OptionConfig = {+ search?: (params: {+ search: string;+ pageToken: string;+ pageSize: number;+ }) => Promise<{+ nextPageToken: string;+ options: { value: string; label: string }[];+ }>;+ fetch?: (names: string[]) => Promise<{ value: string; label: string }[]>;+ fallback?: (value: string) => { value: string; label: string };+ options: { value: string; label: string }[];+};++// ============================================================+// Helpers+// ============================================================++function factorText(factor: Factor, t: TFunction): string {+ const key = `cel.factor.${factor.replace(/\./g, "_")}`;+ const translated = t(key);+ return translated === key ? factor : translated;+}++function getOperatorListByFactor(+ factor: Factor,+ overrideMap?: Map<Factor, Operator[]>+): Operator[] {+ return overrideMap?.get(factor) ?? getRawOperatorListByFactor(factor);+}++function 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 "";+}++// Clone root, apply a mutation to the clone, return the clone.+function updateExpr(+ root: ConditionGroupExpr,+ mutate: (clone: ConditionGroupExpr) => void+): ConditionGroupExpr {+ const clone = structuredClone(root);+ mutate(clone);+ return clone;+}// ============================================================// Context@@ -63,6 +112,8 @@ interface ExprEditorContextValue {factorList: Factor[];optionConfigMap: Map<Factor, OptionConfig>;factorOperatorOverrideMap: Map<Factor, Operator[]> | undefined;+ root: ConditionGroupExpr;+ onUpdate: (expr: ConditionGroupExpr) => void;}const ExprEditorContext = createContext<ExprEditorContextValue>({@@ -71,6 +122,8 @@ const ExprEditorContext = createContext<ExprEditorContextValue>({factorList: [],optionConfigMap: new Map(),factorOperatorOverrideMap: undefined,+ root: { type: ExprType.ConditionGroup, operator: "_&&_", args: [] },+ onUpdate: () => {},});function useExprEditorCtx() {@@ -78,8 +131,47 @@ function useExprEditorCtx() {}// ============================================================-// PortaledDropdown — renders dropdown via portal to avoid-// overflow clipping and z-index issues inside dialogs+// Path-based immutable update helpers+// ============================================================++// A "path" is a list of indices into the tree, used to locate an operand.+// e.g. [0, 2] means root.args[0].args[2] (where root.args[0] is a ConditionGroup).++type Path = number[];++function getGroupAtPath(+ root: ConditionGroupExpr,+ path: Path+): ConditionGroupExpr {+ let node: ConditionGroupExpr = root;+ for (const idx of path) {+ const child = node.args[idx];+ if (!child || child.type !== ExprType.ConditionGroup) {+ throw new Error("Invalid path");+ }+ node = child;+ }+ return node;+}++function useImmutableUpdate(groupPath: Path) {+ const { root, onUpdate } = useExprEditorCtx();++ return useCallback(+ (mutate: (group: ConditionGroupExpr) => void) => {+ onUpdate(+ updateExpr(root, (clone) => {+ const group = getGroupAtPath(clone, groupPath);+ mutate(group);+ })+ );+ },+ [root, onUpdate, groupPath]+ );+}++// ============================================================+// PortaledDropdown// ============================================================function useClickOutside(@@ -133,14 +225,12 @@ function PortaledDropdown({updatePosition();window.addEventListener("scroll", updatePosition, true);window.addEventListener("resize", updatePosition);-const anchor = anchorRef.current;let ro: ResizeObserver | undefined;if (anchor) {ro = new ResizeObserver(updatePosition);ro.observe(anchor);}-return () => {window.removeEventListener("scroll", updatePosition, true);window.removeEventListener("resize", updatePosition);@@ -157,7 +247,7 @@ function PortaledDropdown({}// ============================================================-// SearchableSelect — async searchable dropdown+// SearchableSelect// ============================================================interface SearchableSelectOption {@@ -213,7 +303,10 @@ function SearchableSelect({[optionConfig]);+ const initializedRef = useRef(false);useEffect(() => {+ if (initializedRef.current) return;+ initializedRef.current = true;if (!value) return;if (optionConfig.fetch) {optionConfig.fetch([value]).then((opts) => {@@ -222,7 +315,7 @@ function SearchableSelect({} else if (optionConfig.search) {doSearch(value);}- }, []);+ }, [value, optionConfig, doSearch]);const handleOpen = () => {setOpen(true);@@ -264,7 +357,7 @@ function SearchableSelect({</SelectTrigger><SelectContent>{optionConfig.options.map((o) => (- <SelectItem key={o.value as string} value={o.value as string}>+ <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>))}@@ -331,7 +424,7 @@ function SearchableSelect({}// ============================================================-// MultiSearchableSelect — async searchable multi-select+// MultiSearchableSelect// ============================================================function MultiSearchableSelect({@@ -399,7 +492,10 @@ function MultiSearchableSelect({[optionConfig]);+ const multiInitRef = useRef(false);useEffect(() => {+ if (multiInitRef.current) return;+ multiInitRef.current = true;if (value.length === 0) return;if (optionConfig.fetch) {optionConfig.fetch(value).then((opts) => {@@ -408,7 +504,7 @@ function MultiSearchableSelect({} else if (optionConfig.search) {doSearch("");}- }, []);+ }, [value, optionConfig, doSearch]);const handleOpen = () => {setOpen(true);@@ -475,7 +571,7 @@ function MultiSearchableSelect({removeValue(v);}}>- ×+ <X className="w-3 h-3" /></button>)}</span>@@ -532,7 +628,7 @@ function MultiSearchableSelect({}// ============================================================-// TagInput — multi-value tag input (no dropdown)+// TagInput// ============================================================function TagInput({@@ -586,7 +682,7 @@ function TagInput({className="text-gray-400 hover:text-gray-600"onClick={() => removeTag(tag)}>- ×+ <X className="w-3 h-3" /></button>)}</span>@@ -609,7 +705,7 @@ function TagInput({}// ============================================================-// MultiCheckSelect — dropdown with checkboxes + "All" toggle+// MultiCheckSelect// ============================================================function MultiCheckSelect({@@ -681,7 +777,7 @@ function MultiCheckSelect({onChange(value.filter((x) => x !== v));}}>- ×+ <X className="w-3 h-3" /></span>)}</span>@@ -736,19 +832,29 @@ function MultiCheckSelect({function FactorSelect({expr,- onUpdate,+ groupPath,+ operandIndex,}: {expr: ConditionExpr;- onUpdate: () => void;+ groupPath: Path;+ operandIndex: number;}) {- const { readonly, factorList } = useExprEditorCtx();+ const { t } = useTranslation();+ const {+ readonly,+ factorList,+ factorOperatorOverrideMap: overrideMap,+ } = useExprEditorCtx();+ const doUpdate = useImmutableUpdate(groupPath);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();+ doUpdate((group) => {+ const cond = group.args[operandIndex] as ConditionExpr;+ (cond.args as unknown[])[0] = factorList[0];+ });}}, [factor, factorList]);@@ -757,21 +863,29 @@ function FactorSelect({value={factor}disabled={readonly}onValueChange={(val) => {- (expr.args as unknown[])[0] = val as Factor;- onUpdate();+ doUpdate((group) => {+ const cond = group.args[operandIndex] as ConditionExpr;+ (cond.args as unknown[])[0] = val as Factor;+ // Reset operator when factor changes+ const newFactor = val as Factor;+ const operators = getOperatorListByFactor(newFactor, overrideMap);+ if (operators.length > 0 && !operators.includes(cond.operator)) {+ cond.operator = operators[0] as ConditionOperator;+ }+ });}}><SelectTrigger className="shrink-0"><SelectValue>{(value: string | null) =>- value ? factorText(value as Factor) : null+ value ? factorText(value as Factor, t) : null}</SelectValue></SelectTrigger><SelectContent>{factorList.map((f) => (<SelectItem key={f} value={f}>- {factorText(f)}+ {factorText(f, t)}</SelectItem>))}</SelectContent>@@ -783,19 +897,18 @@ function FactorSelect({// OperatorSelect// ============================================================-function operatorLabel(op: string): string {- return operatorDisplayLabel(op);-}-function OperatorSelect({expr,- onUpdate,+ groupPath,+ operandIndex,}: {expr: ConditionExpr;- onUpdate: () => void;+ groupPath: Path;+ operandIndex: number;}) {const { readonly, factorOperatorOverrideMap: overrideMap } =useExprEditorCtx();+ const doUpdate = useImmutableUpdate(groupPath);const factor = expr.args[0] as Factor;const operators = useMemo(@@ -806,8 +919,10 @@ function OperatorSelect({useEffect(() => {if (operators.length === 0) return;if (!operators.includes(expr.operator)) {- expr.operator = operators[0] as typeof expr.operator;- onUpdate();+ doUpdate((group) => {+ const cond = group.args[operandIndex] as ConditionExpr;+ cond.operator = operators[0] as ConditionOperator;+ });}}, [operators, expr.operator]);@@ -816,19 +931,23 @@ function OperatorSelect({value={expr.operator}disabled={readonly}onValueChange={(val) => {- expr.operator = val as typeof expr.operator;- onUpdate();+ doUpdate((group) => {+ const cond = group.args[operandIndex] as ConditionExpr;+ cond.operator = val as ConditionOperator;+ });}}><SelectTrigger className="shrink-0"><SelectValue>- {(value: string | null) => (value ? operatorLabel(value) : null)}+ {(value: string | null) =>+ value ? operatorDisplayLabel(value) : null+ }</SelectValue></SelectTrigger><SelectContent>{operators.map((op) => (<SelectItem key={op} value={op}>- {operatorLabel(op)}+ {operatorDisplayLabel(op)}</SelectItem>))}</SelectContent>@@ -842,13 +961,16 @@ function OperatorSelect({function ValueInput({expr,- onUpdate,+ groupPath,+ operandIndex,}: {expr: ConditionExpr;- onUpdate: () => void;+ groupPath: Path;+ operandIndex: number;}) {const { t } = useTranslation();const { readonly, optionConfigMap } = useExprEditorCtx();+ const doUpdate = useImmutableUpdate(groupPath);const factor = expr.args[0] as Factor;const operator = expr.operator;@@ -879,7 +1001,6 @@ function ValueInput({if (isArrayValue) {inputType = hasOption ? "MULTI-SELECT" : "MULTI-INPUT";} else if (isStringOperator(operator)) {- // String operators (startsWith, contains, etc.) always use text inputinputType = "INPUT";} else if (hasOption) {inputType = "SINGLE-SELECT";@@ -889,7 +1010,7 @@ function ValueInput({const isNumberValue = isNumberFactor(factor);- // Reset value when factor or operator changes, matching Vue's watch([factor, operator]) behavior.+ // Reset value when factor or operator changesconst prevRef = useRef({ factor, operator });useEffect(() => {const prev = prevRef.current;@@ -897,22 +1018,20 @@ function ValueInput({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;+ doUpdate((group) => {+ const cond = group.args[operandIndex] as ConditionExpr;+ if (isNumberFactor(cond.args[0] as Factor)) {+ (cond.args as unknown[])[1] = isCollectionOperator(cond.operator)+ ? []+ : 0;+ } else if (isBooleanFactor(cond.args[0] as Factor)) {+ (cond.args as unknown[])[1] = true;+ } else if (isStringFactor(cond.args[0] as Factor)) {+ (cond.args as unknown[])[1] = isCollectionOperator(cond.operator)+ ? []+ : "";}- } 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 = () => {@@ -929,21 +1048,28 @@ function ValueInput({};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();+ doUpdate((group) => {+ const cond = group.args[operandIndex] as ConditionExpr;+ (cond.args as unknown[])[1] = isNumberFactor(cond.args[0] as Factor)+ ? Number(v)+ : v;+ });};const setNumberValue = (v: number) => {- (expr.args as unknown[])[1] = v;- onUpdate();+ doUpdate((group) => {+ const cond = group.args[operandIndex] as ConditionExpr;+ (cond.args as unknown[])[1] = v;+ });};const setArrayValue = (v: string[]) => {- if (isNumberFactor(factor)) {- (expr.args as unknown[])[1] = v.map(Number);- } else {- (expr.args as unknown[])[1] = v;- }- onUpdate();+ doUpdate((group) => {+ const cond = group.args[operandIndex] as ConditionExpr;+ if (isNumberFactor(cond.args[0] as Factor)) {+ (cond.args as unknown[])[1] = v.map(Number);+ } else {+ (cond.args as unknown[])[1] = v;+ }+ });};if (inputType === "INPUT") {@@ -1001,8 +1127,8 @@ function ValueInput({</SelectTrigger><SelectContent>{optionConfig.options.map((o) => (- <SelectItem key={o.value as string} value={o.value as string}>- {renderOptionValue(o.value as string, o.label)}+ <SelectItem key={o.value} value={o.value}>+ {renderOptionValue(o.value, o.label)}</SelectItem>))}</SelectContent>@@ -1050,29 +1176,46 @@ function ValueInput({function ConditionRow({expr,- onRemove,- onUpdate,+ groupPath,+ operandIndex,}: {expr: ConditionExpr;- onRemove: () => void;- onUpdate: () => void;+ groupPath: Path;+ operandIndex: number;}) {const { readonly } = useExprEditorCtx();+ const doUpdate = useImmutableUpdate(groupPath);return (<div className="w-full flex items-center gap-x-1">- <FactorSelect expr={expr} onUpdate={onUpdate} />- <OperatorSelect expr={expr} onUpdate={onUpdate} />+ <FactorSelect+ expr={expr}+ groupPath={groupPath}+ operandIndex={operandIndex}+ />+ <OperatorSelect+ expr={expr}+ groupPath={groupPath}+ operandIndex={operandIndex}+ /><div className="flex-1 min-w-0">- <ValueInput expr={expr} onUpdate={onUpdate} />+ <ValueInput+ expr={expr}+ groupPath={groupPath}+ operandIndex={operandIndex}+ /></div>{!readonly && (<buttontype="button"className="shrink-0 w-7 h-7 flex items-center justify-center rounded-xs text-control-placeholder hover:text-control hover:bg-gray-100"- onClick={onRemove}+ onClick={() =>+ doUpdate((group) => {+ group.args.splice(operandIndex, 1);+ })+ }>- <X className="w-4 h-4" />+ <Trash2 className="w-3.5 h-3.5" /></button>)}</div>@@ -1085,14 +1228,15 @@ function ConditionRow({function RawStringEditor({expr,- onRemove,- onUpdate,+ groupPath,+ operandIndex,}: {expr: RawStringExpr;- onRemove: () => void;- onUpdate: () => void;+ groupPath: Path;+ operandIndex: number;}) {const { readonly } = useExprEditorCtx();+ const doUpdate = useImmutableUpdate(groupPath);return (<div className="w-full flex items-start gap-x-1">@@ -1103,17 +1247,24 @@ function RawStringEditor({disabled={readonly}rows={2}onChange={(e) => {- expr.content = e.target.value;- onUpdate();+ const newContent = e.target.value;+ doUpdate((group) => {+ const raw = group.args[operandIndex] as RawStringExpr;+ raw.content = newContent;+ });}}/>{!readonly && (<buttontype="button"className="shrink-0 w-7 h-7 flex items-center justify-center rounded-xs text-control-placeholder hover:text-control hover:bg-gray-100"- onClick={onRemove}+ onClick={() =>+ doUpdate((group) => {+ group.args.splice(operandIndex, 1);+ })+ }>- <X className="w-4 h-4" />+ <Trash2 className="w-3.5 h-3.5" /></button>)}</div>@@ -1127,13 +1278,13 @@ function RawStringEditor({function ConditionGroup({expr,root = false,- onRemove,- onUpdate,+ groupPath,+ operandIndex,}: {expr: ConditionGroupExpr;root?: boolean;- onRemove?: () => void;- onUpdate: () => void;+ groupPath: Path;+ operandIndex?: number;}) {const { t } = useTranslation();const {@@ -1143,6 +1294,11 @@ function ConditionGroup({factorOperatorOverrideMap: overrideMap,} = useExprEditorCtx();+ // For root, groupPath is []; for nested groups, it includes the operandIndex+ const selfPath = root ? groupPath : [...groupPath, operandIndex!];+ const doUpdate = useImmutableUpdate(selfPath);+ const parentDoUpdate = useImmutableUpdate(groupPath);+const operator = expr.operator;const args = expr.args;@@ -1152,50 +1308,38 @@ function ConditionGroup({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();+ doUpdate((group) => {+ group.args.push({+ type: ExprType.Condition,+ operator: op,+ args: [factor, getDefaultValue(factor)],+ } as ConditionExpr);+ });};const addConditionGroup = () => {- args.push({- type: ExprType.ConditionGroup,- operator: LogicalOperatorList[0],- args: [],+ doUpdate((group) => {+ group.args.push({+ type: ExprType.ConditionGroup,+ operator: LogicalOperatorList[0],+ args: [],+ });});- onUpdate();};const addRawString = () => {- args.push({- type: ExprType.RawString,- content: "",+ doUpdate((group) => {+ group.args.push({+ type: ExprType.RawString,+ content: "",+ });});- onUpdate();- };-- const removeOperand = (index: number) => {- args.splice(index, 1);- onUpdate();};return (@@ -1229,9 +1373,13 @@ function ConditionGroup({<buttontype="button"className="w-[22px] h-[22px] flex items-center justify-center rounded-xs hover:bg-gray-100"- onClick={onRemove}+ onClick={() =>+ parentDoUpdate((group) => {+ group.args.splice(operandIndex!, 1);+ })+ }>- <X className="w-3.5 h-3.5" />+ <Trash2 className="w-3.5 h-3.5" /></button></div>)}@@ -1257,8 +1405,9 @@ function ConditionGroup({value={operator}disabled={readonly}onValueChange={(val) => {- expr.operator = val as typeof expr.operator;- onUpdate();+ doUpdate((group) => {+ group.operator = val as LogicalOperator;+ });}}><SelectTrigger className="h-7 px-1.5">@@ -1284,22 +1433,22 @@ function ConditionGroup({<ConditionGroupkey={i}expr={operand}- onRemove={() => removeOperand(i)}- onUpdate={onUpdate}+ groupPath={selfPath}+ operandIndex={i}/>)}{isConditionExpr(operand) && (<ConditionRowexpr={operand}- onRemove={() => removeOperand(i)}- onUpdate={onUpdate}+ groupPath={selfPath}+ operandIndex={i}/>)}{isRawStringExpr(operand) && (<RawStringEditorexpr={operand}- onRemove={() => removeOperand(i)}- onUpdate={onUpdate}+ groupPath={selfPath}+ operandIndex={i}/>)}</div>@@ -1342,12 +1491,18 @@ function ConditionGroup({</button><buttontype="button"- className="inline-flex items-center gap-1 text-sm px-1.5 py-0.5 rounded-xs hover:bg-gray-100 disabled:opacity-50"+ className="inline-flex items-center gap-1 text-sm px-1.5 py-0.5 rounded-xs hover:bg-gray-100 disabled:opacity-50 group relative"disabled={readonly}onClick={addConditionGroup}><Plus className="w-4 h-4" />{t("cel.condition.add-group")}+ <span className="relative">+ <HelpCircle className="ml-1 w-3 h-3 text-gray-400" />+ <span className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 hidden group-hover:block w-72 p-2 text-xs bg-gray-800 text-white rounded shadow-lg z-50">+ {t("cel.condition.group.tooltip")}+ </span>+ </span></button>{enableRawExpression && (<button@@ -1377,7 +1532,7 @@ export interface ExprEditorProps {factorList: Factor[];optionConfigMap?: Map<Factor, OptionConfig>;factorOperatorOverrideMap?: Map<Factor, Operator[]>;- onUpdate: () => void;+ onUpdate: (expr: ConditionGroupExpr) => void;}export function ExprEditor({@@ -1396,14 +1551,24 @@ export function ExprEditor({factorList,optionConfigMap,factorOperatorOverrideMap: overrideMap,+ root: expr,+ onUpdate,}),- [readonly, enableRawExpression, factorList, optionConfigMap, overrideMap]+ [+ readonly,+ enableRawExpression,+ factorList,+ optionConfigMap,+ overrideMap,+ expr,+ onUpdate,+ ]);return (<ExprEditorContext.Provider value={ctxValue}><div className="bb-risk-expr-editor text-sm w-full">- <ConditionGroup expr={expr} root onUpdate={onUpdate} />+ <ConditionGroup expr={expr} root groupPath={[]} /></div></ExprEditorContext.Provider>);diff --git a/frontend/src/react/components/MatchedDatabaseView.tsx b/frontend/src/react/components/MatchedDatabaseView.tsxnew file mode 100644index 0000000000..a3ba5233d9--- /dev/null+++ b/frontend/src/react/components/MatchedDatabaseView.tsx@@ -0,0 +1,368 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import type { ConditionGroupExpr } from "@/plugins/cel";+import { validateSimpleExpr } from "@/plugins/cel";+import { useDatabaseV1Store, useDBGroupStore } from "@/store";+import { DEBOUNCE_SEARCH_DELAY, isValidDatabaseName } from "@/types";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import {+ getDatabaseEnvironment,+ getDefaultPagination,+ getInstanceResource,+} from "@/utils";++interface MatchedDatabaseViewProps {+ project: string;+ expr: ConditionGroupExpr;+ matchedDatabaseNames?: string[];+}++interface SectionState {+ databases: Database[];+ loading: boolean;+}++export function MatchedDatabaseView({+ project,+ expr,+ matchedDatabaseNames: presetNames,+}: MatchedDatabaseViewProps) {+ const { t } = useTranslation();++ const [loading, setLoading] = useState(false);+ const [matchingError, setMatchingError] = useState<string>();+ const [matchedNames, setMatchedNames] = useState<string[]>([]);+ const [matchedDbs, setMatchedDbs] = useState<SectionState>({+ databases: [],+ loading: false,+ });+ const [unmatchedDbs, setUnmatchedDbs] = useState<SectionState>({+ databases: [],+ loading: false,+ });+ const [matchedToken, setMatchedToken] = useState(0);+ const [unmatchedToken, setUnmatchedToken] = useState("");+ const [expandedSections, setExpandedSections] = useState<Set<string>>(+ new Set()+ );++ // Refs for stable references across closures+ const matchedNamesRef = useRef<string[]>([]);+ matchedNamesRef.current = matchedNames;++ const pageSize = getDefaultPagination();+ const dbGroupStore = useDBGroupStore();+ const databaseStore = useDatabaseV1Store();++ const toggleSection = useCallback((name: string) => {+ setExpandedSections((prev) => {+ const next = new Set(prev);+ if (next.has(name)) {+ next.delete(name);+ } else {+ next.add(name);+ }+ return next;+ });+ }, []);++ const loadMoreMatched = useCallback(+ async (currentToken: number, currentDbs: Database[]) => {+ const names = matchedNamesRef.current;+ const next = currentToken + pageSize;+ const slice = names.slice(currentToken, next);+ if (slice.length === 0) return;++ setMatchedDbs((prev) => ({ ...prev, loading: true }));+ try {+ await databaseStore.batchGetOrFetchDatabases(slice);+ const newDbs = slice+ .map((n) => databaseStore.getDatabaseByName(n))+ .filter((db) => isValidDatabaseName(db.name));+ setMatchedDbs({+ databases: [...currentDbs, ...newDbs],+ loading: false,+ });+ setMatchedToken(next);+ } catch {+ setMatchedDbs((prev) => ({ ...prev, loading: false }));+ }+ },+ [databaseStore, pageSize]+ );++ const loadMoreUnmatched = useCallback(+ async (token: string, currentDbs: Database[]) => {+ const names = matchedNamesRef.current;+ setUnmatchedDbs((prev) => ({ ...prev, loading: true }));+ try {+ let unmatched: Database[] = [];+ let pageToken = token;+ while (true) {+ const { databases, nextPageToken } =+ await databaseStore.fetchDatabases({+ pageToken,+ pageSize,+ parent: project,+ silent: true,+ });+ pageToken = nextPageToken;+ unmatched = databases.filter((db) => !names.includes(db.name));+ if (unmatched.length > 0 || !pageToken) {+ break;+ }+ }+ const validDbs = unmatched.filter((db) => isValidDatabaseName(db.name));+ setUnmatchedDbs({+ databases: [...currentDbs, ...validDbs],+ loading: false,+ });+ setUnmatchedToken(pageToken);+ } catch {+ setUnmatchedDbs((prev) => ({ ...prev, loading: false }));+ }+ },+ [databaseStore, pageSize, project]+ );++ // Debounced expression validation and data loading+ const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ useEffect(() => {+ clearTimeout(timerRef.current);+ timerRef.current = setTimeout(async () => {+ if (!validateSimpleExpr(expr)) {+ setMatchingError(undefined);+ setMatchedNames([]);+ setMatchedDbs({ databases: [], loading: false });+ setUnmatchedDbs({ databases: [], loading: false });+ setMatchedToken(0);+ setUnmatchedToken("");+ setExpandedSections(new Set());+ return;+ }++ setLoading(true);+ try {+ const names = presetNames+ ? presetNames+ : await dbGroupStore.fetchDatabaseGroupMatchList({+ projectName: project,+ expr,+ });++ setMatchingError(undefined);+ matchedNamesRef.current = names;+ setMatchedNames(names);++ // Reset and load initial batches+ const matchedNext = Math.min(pageSize, names.length);+ const matchedSlice = names.slice(0, matchedNext);++ let newMatchedDbs: Database[] = [];+ if (matchedSlice.length > 0) {+ await databaseStore.batchGetOrFetchDatabases(matchedSlice);+ newMatchedDbs = matchedSlice+ .map((n) => databaseStore.getDatabaseByName(n))+ .filter((db) => isValidDatabaseName(db.name));+ }+ setMatchedDbs({ databases: newMatchedDbs, loading: false });+ setMatchedToken(matchedNext);++ // Load unmatched+ let unmatchedList: Database[] = [];+ let pageToken = "";+ while (true) {+ const { databases, nextPageToken } =+ await databaseStore.fetchDatabases({+ pageToken,+ pageSize,+ parent: project,+ silent: true,+ });+ pageToken = nextPageToken;+ unmatchedList = databases.filter((db) => !names.includes(db.name));+ if (unmatchedList.length > 0 || !pageToken) {+ break;+ }+ }+ const validUnmatched = unmatchedList.filter((db) =>+ isValidDatabaseName(db.name)+ );+ setUnmatchedDbs({ databases: validUnmatched, loading: false });+ setUnmatchedToken(pageToken);++ // Auto-expand sections that have data+ const expanded = new Set<string>();+ if (newMatchedDbs.length > 0) expanded.add("matched");+ if (validUnmatched.length > 0) expanded.add("unmatched");+ setExpandedSections(expanded);+ } catch (error) {+ setMatchingError(+ error instanceof Error ? error.message : String(error)+ );+ } finally {+ setLoading(false);+ }+ }, DEBOUNCE_SEARCH_DELAY);+ return () => clearTimeout(timerRef.current);+ }, [expr, project, presetNames, dbGroupStore, databaseStore, pageSize]);++ const hasMoreMatched = matchedToken < matchedNames.length;+ const hasMoreUnmatched = !!unmatchedToken;++ const sections = useMemo(+ () => [+ {+ name: "matched",+ title: t("database-group.matched-database"),+ databases: matchedDbs.databases,+ sectionLoading: matchedDbs.loading,+ total: matchedNames.length,+ showTotal: true,+ hasMore: hasMoreMatched,+ onLoadMore: () => loadMoreMatched(matchedToken, matchedDbs.databases),+ },+ {+ name: "unmatched",+ title: t("database-group.unmatched-database"),+ databases: unmatchedDbs.databases,+ sectionLoading: unmatchedDbs.loading,+ hasMore: hasMoreUnmatched,+ showTotal: false,+ onLoadMore: () =>+ loadMoreUnmatched(unmatchedToken, unmatchedDbs.databases),+ },+ ],+ [+ t,+ matchedDbs,+ unmatchedDbs,+ matchedNames.length,+ hasMoreMatched,+ hasMoreUnmatched,+ matchedToken,+ unmatchedToken,+ loadMoreMatched,+ loadMoreUnmatched,+ ]+ );++ return (+ <div>+ <div className="mb-2 flex flex-row items-center">+ <span className="font-medium text-main mr-2">+ {t("common.databases")}+ </span>+ {loading && (+ <svg+ className="animate-spin h-5 w-5 opacity-60"+ xmlns="http://www.w3.org/2000/svg"+ fill="none"+ viewBox="0 0 24 24"+ >+ <circle+ className="opacity-25"+ cx="12"+ cy="12"+ r="10"+ stroke="currentColor"+ strokeWidth="4"+ />+ <path+ className="opacity-75"+ fill="currentColor"+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"+ />+ </svg>+ )}+ </div>++ {matchingError && (+ <p className="my-2 text-sm border border-red-600 px-2 py-1 rounded-lg bg-red-50 text-red-600">+ {matchingError}+ </p>+ )}++ <div className="border p-2 rounded-lg">+ {sections.map((section) => {+ const isExpanded = expandedSections.has(section.name);+ const isEmpty = section.databases.length === 0;++ return (+ <div key={section.name}>+ <button+ type="button"+ className={`w-full flex items-center justify-between py-2 px-1 text-left text-sm ${+ isEmpty+ ? "cursor-default text-gray-400"+ : "cursor-pointer hover:bg-gray-50"+ }`}+ disabled={isEmpty}+ onClick={() => toggleSection(section.name)}+ >+ <div className="flex items-center gap-x-1">+ <svg+ className={`h-4 w-4 transition-transform ${+ isExpanded ? "rotate-90" : ""+ } ${isEmpty ? "text-gray-300" : ""}`}+ fill="none"+ viewBox="0 0 24 24"+ stroke="currentColor"+ strokeWidth={2}+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ d="M9 5l7 7-7 7"+ />+ </svg>+ <span>{section.title}</span>+ </div>+ {section.showTotal && (+ <span className="text-gray-500 text-xs">{section.total}</span>+ )}+ </button>++ {isExpanded && !isEmpty && (+ <div className="flex flex-col gap-y-2 w-full max-h-48 overflow-y-auto">+ <div>+ {section.databases.map((database) => {+ const instance = getInstanceResource(database);+ const env = getDatabaseEnvironment(database);+ const dbName = database.name.split("/").pop();++ return (+ <div+ key={database.name}+ className="w-full flex flex-row justify-between items-center px-2 py-1 gap-x-2"+ >+ <span className="truncate">{dbName}</span>+ <div className="flex-1 flex flex-row justify-end items-center shrink-0">+ <span className="text-sm">{instance.title}</span>+ <span className="ml-1 text-sm text-gray-400 max-w-31 truncate">+ {env.title}+ </span>+ </div>+ </div>+ );+ })}+ </div>+ {section.hasMore && (+ <button+ type="button"+ className="self-start px-2 py-1 text-sm text-blue-600 hover:text-blue-800 disabled:opacity-50"+ disabled={section.sectionLoading}+ onClick={section.onLoadMore}+ >+ {section.sectionLoading ? "..." : t("common.load-more")}+ </button>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex 3fbbed6aac..3b6526f977 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -51,7 +51,8 @@},"or": {"description": "Any of the following are true..."- }+ },+ "tooltip": "A condition group is a collection of conditions connected by operators \"And\" and \"Or\"."},"input-value": "Input value","input-value-press-enter": "Input value, press Enter to confirm",@@ -91,6 +92,7 @@"discard-changes": "Discard changes","edit": "Edit","email": "Email",+ "empty": "Empty","enable": "Enable","enabled": "Enabled","environment": "Environment",@@ -245,6 +247,7 @@"edit-environment": "Edit Environment","edit-labels": "Edit Labels","engine": "Engine",+ "expression": "Expression","filter-database": "Filter database","selected-n-databases": "{{n}} database(s) selected","successfully-transferred-databases": "Successfully transferred databases",@@ -1150,7 +1153,15 @@"enabled": "2FA Enabled"},"database-group": {- "select": "Select database group"+ "condition": {+ "self": "Condition"+ },+ "create": "New database group",+ "delete-group": "Delete the database group {{name}}",+ "matched-database": "Matched database",+ "no-matched-databases": "No matched databases",+ "select": "Select database group",+ "unmatched-database": "Unmatched database"},"gitops": {"checklist": {diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex c549d535fe..1adc203c52 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -51,7 +51,8 @@},"or": {"description": "Cualquiera de los siguientes es verdadero..."- }+ },+ "tooltip": "A condition group is a collection of conditions connected by operators \"And\" and \"Or\"."},"input-value": "Valor de entrada","input-value-press-enter": "Ingrese el valor, presione Enter para confirmar",@@ -91,6 +92,7 @@"discard-changes": "Descartar cambios","edit": "Editar","email": "Correo electrónico",+ "empty": "Empty","enable": "Enable","enabled": "Enabled","environment": "Entorno",@@ -245,6 +247,7 @@"edit-environment": "Editar entorno","edit-labels": "Editar etiquetas","engine": "Motor",+ "expression": "Expression","filter-database": "Filtrar base de datos","selected-n-databases": "{{n}} base(s) de datos seleccionada(s)","successfully-transferred-databases": "Bases de datos transferidas exitosamente",@@ -1150,7 +1153,15 @@"enabled": "2FA habilitado"},"database-group": {- "select": "Seleccionar grupo de bases de datos"+ "condition": {+ "self": "Condition"+ },+ "create": "New database group",+ "delete-group": "Delete the database group {{name}}",+ "matched-database": "Matched database",+ "no-matched-databases": "No matched databases",+ "select": "Select database group",+ "unmatched-database": "Unmatched database"},"gitops": {"checklist": {diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex cc7d8a96da..80b45e2c47 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -51,7 +51,8 @@},"or": {"description": "次のいずれかが当てはまります…"- }+ },+ "tooltip": "A condition group is a collection of conditions connected by operators \"And\" and \"Or\"."},"input-value": "入力値","input-value-press-enter": "値を入力し、Enter キーを押して確定します",@@ -91,6 +92,7 @@"discard-changes": "変更をキャンセルする","edit": "編集","email": "メールアドレス",+ "empty": "Empty","enable": "Enable","enabled": "Enabled","environment": "環境",@@ -245,6 +247,7 @@"edit-environment": "環境の編集","edit-labels": "ラベルを編集","engine": "エンジン",+ "expression": "Expression","filter-database": "データベースをフィルター","selected-n-databases": "{{n}} 個のデータベースが選択されました","successfully-transferred-databases": "データベースの転送に成功しました",@@ -1150,7 +1153,15 @@"enabled": "二要素認証がオンになっています"},"database-group": {- "select": "データベースグループを選択"+ "condition": {+ "self": "Condition"+ },+ "create": "New database group",+ "delete-group": "Delete the database group {{name}}",+ "matched-database": "Matched database",+ "no-matched-databases": "No matched databases",+ "select": "Select database group",+ "unmatched-database": "Unmatched database"},"gitops": {"checklist": {diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 59003dda8b..f57eab0ba7 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -51,7 +51,8 @@},"or": {"description": "Bất kỳ điều nào sau đây là đúng..."- }+ },+ "tooltip": "A condition group is a collection of conditions connected by operators \"And\" and \"Or\"."},"input-value": "Nhập giá trị","input-value-press-enter": "Nhập giá trị, nhấn Enter để xác nhận",@@ -91,6 +92,7 @@"discard-changes": "Hủy thay đổi","edit": "Chỉnh sửa","email": "Email",+ "empty": "Empty","enable": "Enable","enabled": "Enabled","environment": "Môi trường",@@ -245,6 +247,7 @@"edit-environment": "Chỉnh sửa Môi trường","edit-labels": "Chỉnh sửa nhãn","engine": "Engine",+ "expression": "Expression","filter-database": "Lọc cơ sở dữ liệu","selected-n-databases": "Đã chọn {{n}} cơ sở dữ liệu","successfully-transferred-databases": "Chuyển cơ sở dữ liệu thành công",@@ -1150,7 +1153,15 @@"enabled": "Đã bật 2FA"},"database-group": {- "select": "Chọn nhóm cơ sở dữ liệu"+ "condition": {+ "self": "Condition"+ },+ "create": "New database group",+ "delete-group": "Delete the database group {{name}}",+ "matched-database": "Matched database",+ "no-matched-databases": "No matched databases",+ "select": "Select database group",+ "unmatched-database": "Unmatched database"},"gitops": {"checklist": {diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex b8df754e9e..b325c80fbb 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -51,7 +51,8 @@},"or": {"description": "以下任一为真…"- }+ },+ "tooltip": "A condition group is a collection of conditions connected by operators \"And\" and \"Or\"."},"input-value": "输入值","input-value-press-enter": "输入值,按回车确认",@@ -91,6 +92,7 @@"discard-changes": "取消修改","edit": "编辑","email": "邮箱",+ "empty": "Empty","enable": "Enable","enabled": "开启","environment": "环境",@@ -245,6 +247,7 @@"edit-environment": "编辑环境","edit-labels": "编辑标签","engine": "引擎",+ "expression": "Expression","filter-database": "筛选数据库","selected-n-databases": "已选择 {{n}} 个数据库","successfully-transferred-databases": "成功转移数据库",@@ -1150,7 +1153,15 @@"enabled": "双重认证已开启"},"database-group": {- "select": "选择数据库分组"+ "condition": {+ "self": "Condition"+ },+ "create": "New database group",+ "delete-group": "Delete the database group {{name}}",+ "matched-database": "Matched database",+ "no-matched-databases": "No matched databases",+ "select": "Select database group",+ "unmatched-database": "Unmatched database"},"gitops": {"checklist": {diff --git a/frontend/src/react/pages/project/ProjectDatabaseGroupCreatePage.tsx b/frontend/src/react/pages/project/ProjectDatabaseGroupCreatePage.tsxnew file mode 100644index 0000000000..2a3d4ceeb7--- /dev/null+++ b/frontend/src/react/pages/project/ProjectDatabaseGroupCreatePage.tsx@@ -0,0 +1,33 @@+import { DatabaseGroupForm } from "@/react/components/DatabaseGroupForm";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/router/dashboard/projectV1";+import { useProjectV1Store } from "@/store";+import { projectNamePrefix } from "@/store/modules/v1/common";++export function ProjectDatabaseGroupCreatePage({+ projectId,+}: {+ projectId: string;+}) {+ const projectStore = useProjectV1Store();+ const projectName = `${projectNamePrefix}${projectId}`;+ const project = useVueState(() => projectStore.getProjectByName(projectName));++ if (!project) return null;++ return (+ <DatabaseGroupForm+ className="py-4 h-full"+ readonly={false}+ project={project}+ onDismiss={() => router.back()}+ onCreated={(databaseGroupName) => {+ router.push({+ name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,+ params: { databaseGroupName },+ });+ }}+ />+ );+}diff --git a/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx b/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsxnew file mode 100644index 0000000000..a650fa1074--- /dev/null+++ b/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx@@ -0,0 +1,199 @@+import { Edit, EllipsisVertical } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { preCreateIssue } from "@/components/Plan/logic/issue";+import { DatabaseGroupForm } from "@/react/components/DatabaseGroupForm";+import { FeatureAttention } from "@/react/components/FeatureAttention";+import { Button } from "@/react/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from "@/react/components/ui/dialog";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { PROJECT_V1_ROUTE_DATABASE_GROUPS } from "@/router/dashboard/projectV1";+import { hasFeature, useDBGroupStore, useProjectV1Store } from "@/store";+import {+ databaseGroupNamePrefix,+ projectNamePrefix,+} from "@/store/modules/v1/common";+import { isValidDatabaseGroupName } from "@/types";+import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import {+ hasProjectPermissionV2,+ PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE,+} from "@/utils";++export function ProjectDatabaseGroupDetailPage({+ projectId,+ databaseGroupName,+}: {+ projectId: string;+ databaseGroupName: string;+}) {+ const { t } = useTranslation();+ const projectStore = useProjectV1Store();+ const dbGroupStore = useDBGroupStore();++ const projectName = `${projectNamePrefix}${projectId}`;+ const project = useVueState(() => projectStore.getProjectByName(projectName));++ const resourceName = `${projectName}/${databaseGroupNamePrefix}${databaseGroupName}`;++ const databaseGroup = useVueState(() =>+ dbGroupStore.getDBGroupByName(resourceName)+ );++ const [editing, setEditing] = useState(false);+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);+ const [showDropdown, setShowDropdown] = useState(false);++ // Fetch the database group on mount+ useEffect(() => {+ dbGroupStore.getOrFetchDBGroupByName(resourceName, {+ skipCache: true,+ view: DatabaseGroupView.FULL,+ });+ }, [resourceName, dbGroupStore]);++ const hasDatabaseGroupFeature = useVueState(() =>+ hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)+ );++ const hasMatchedDatabases = useMemo(+ () => (databaseGroup?.matchedDatabases.length ?? 0) > 0,+ [databaseGroup]+ );++ const canUpdate = useMemo(+ () =>+ project+ ? hasProjectPermissionV2(project, "bb.databaseGroups.update")+ : false,+ [project]+ );++ const canDelete = useMemo(+ () =>+ project+ ? hasProjectPermissionV2(project, "bb.databaseGroups.delete")+ : false,+ [project]+ );++ const canChangeDatabase = useMemo(+ () =>+ project+ ? PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE.every((p) =>+ hasProjectPermissionV2(project, p)+ )+ : false,+ [project]+ );++ const handleDelete = useCallback(async () => {+ await dbGroupStore.deleteDatabaseGroup(resourceName);+ router.push({ name: PROJECT_V1_ROUTE_DATABASE_GROUPS });+ setShowDeleteDialog(false);+ }, [resourceName, dbGroupStore]);++ if (!databaseGroup || !project) return null;+ if (!isValidDatabaseGroupName(databaseGroup.name)) return null;++ return (+ <div className="min-h-full flex-1 relative flex flex-col gap-y-4 px-4 pt-4">+ <FeatureAttention feature={PlanFeature.FEATURE_DATABASE_GROUPS} />++ {hasDatabaseGroupFeature && !editing && (+ <div className="flex flex-row justify-end items-center flex-wrap shrink gap-x-2 gap-y-2">+ <Button+ variant="outline"+ disabled={!canChangeDatabase || !hasMatchedDatabases}+ onClick={() => preCreateIssue(project.name, [resourceName])}+ title={+ !hasMatchedDatabases+ ? t("database-group.no-matched-databases")+ : undefined+ }+ >+ {t("database.change-database")}+ </Button>++ <Button disabled={!canUpdate} onClick={() => setEditing(true)}>+ <Edit className="w-4 h-4 mr-1" />+ {t("common.configure")}+ </Button>++ {canDelete && (+ <div className="relative">+ <Button+ variant="ghost"+ size="sm"+ className="px-1!"+ onClick={() => setShowDropdown((v) => !v)}+ >+ <EllipsisVertical className="w-4 h-4" />+ </Button>+ {showDropdown && (+ <>+ <div+ className="fixed inset-0 z-10"+ onClick={() => setShowDropdown(false)}+ />+ <div className="absolute right-0 top-full z-20 mt-1 bg-white border rounded shadow-md min-w-[100px]">+ <button+ type="button"+ className="w-full text-left px-3 py-1.5 text-sm hover:bg-gray-50 text-error"+ onClick={() => {+ setShowDropdown(false);+ setShowDeleteDialog(true);+ }}+ >+ {t("common.delete")}+ </button>+ </div>+ </>+ )}+ </div>+ )}+ </div>+ )}++ <DatabaseGroupForm+ readonly={!editing}+ project={project}+ databaseGroup={databaseGroup}+ onDismiss={() => setEditing(false)}+ />++ <Dialog+ open={showDeleteDialog}+ onOpenChange={(open) => {+ if (!open) setShowDeleteDialog(false);+ }}+ >+ <DialogContent>+ <DialogTitle>+ {t("database-group.delete-group", { name: databaseGroup.title })}+ </DialogTitle>+ <p className="text-sm text-control-light">+ {t("common.cannot-undo-this-action")}+ </p>+ <div className="flex justify-end gap-x-2 mt-4">+ <Button+ variant="outline"+ onClick={() => setShowDeleteDialog(false)}+ >+ {t("common.cancel")}+ </Button>+ <Button variant="destructive" onClick={handleDelete}>+ {t("common.delete")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx b/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsxnew file mode 100644index 0000000000..6037832772--- /dev/null+++ b/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx@@ -0,0 +1,328 @@+import { EllipsisVertical, Plus } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { FeatureAttention } from "@/react/components/FeatureAttention";+import { FeatureBadge } from "@/react/components/FeatureBadge";+import { Button } from "@/react/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from "@/react/components/ui/dialog";+import { Input } from "@/react/components/ui/input";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import {+ PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,+ PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE,+} from "@/router/dashboard/projectV1";+import { useDBGroupStore, useProjectV1Store } from "@/store";+import {+ getProjectNameAndDatabaseGroupName,+ projectNamePrefix,+} from "@/store/modules/v1/common";+import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";+import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import { hasProjectPermissionV2 } from "@/utils";++export function ProjectDatabaseGroupsPage({+ projectId,+}: {+ projectId: string;+}) {+ const { t } = useTranslation();+ const projectStore = useProjectV1Store();+ const dbGroupStore = useDBGroupStore();++ const projectName = `${projectNamePrefix}${projectId}`;+ const project = useVueState(() => projectStore.getProjectByName(projectName));++ const [searchText, setSearchText] = useState("");+ const [dbGroupList, setDbGroupList] = useState<DatabaseGroup[]>([]);+ const [loading, setLoading] = useState(true);+ const [deleteTarget, setDeleteTarget] = useState<DatabaseGroup | null>(null);++ // Fetch database groups+ useEffect(() => {+ setLoading(true);+ setDbGroupList([]);+ dbGroupStore+ .fetchDBGroupListByProjectName(projectName, DatabaseGroupView.BASIC)+ .then((list) => {+ setDbGroupList(list);+ setLoading(false);+ });+ }, [projectName, dbGroupStore]);++ const canCreate = useMemo(+ () =>+ project+ ? hasProjectPermissionV2(project, "bb.databaseGroups.create")+ : false,+ [project]+ );++ const canDelete = useMemo(+ () =>+ project+ ? hasProjectPermissionV2(project, "bb.databaseGroups.delete")+ : false,+ [project]+ );++ const filteredList = useMemo(() => {+ const filter = searchText.trim().toLowerCase();+ if (!filter) return dbGroupList;+ return dbGroupList.filter(+ (group) =>+ group.name.toLowerCase().includes(filter) ||+ group.title.toLowerCase().includes(filter)+ );+ }, [dbGroupList, searchText]);++ const handleCreate = useCallback(() => {+ router.push({ name: PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE });+ }, []);++ const handleRowClick = useCallback(+ (e: React.MouseEvent, group: DatabaseGroup) => {+ const [pid, groupName] = getProjectNameAndDatabaseGroupName(group.name);+ const url = router.resolve({+ name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,+ params: { projectId: pid, databaseGroupName: groupName },+ }).fullPath;+ if (e.ctrlKey || e.metaKey) {+ window.open(url, "_blank");+ } else {+ router.push(url);+ }+ },+ []+ );++ const handleDelete = useCallback(async () => {+ if (!deleteTarget) return;+ await dbGroupStore.deleteDatabaseGroup(deleteTarget.name);+ setDbGroupList((prev) => prev.filter((g) => g.name !== deleteTarget.name));+ setDeleteTarget(null);+ }, [deleteTarget, dbGroupStore]);++ return (+ <div className="py-4 flex flex-col">+ <div className="px-4 flex flex-col gap-y-2 pb-2">+ <FeatureAttention feature={PlanFeature.FEATURE_DATABASE_GROUPS} />+ <div className="flex flex-row items-center justify-end gap-x-2">+ <Input+ className="max-w-full"+ placeholder={t("common.filter-by-name")}+ value={searchText}+ onChange={(e) => setSearchText(e.target.value)}+ />+ <Button disabled={!canCreate} onClick={handleCreate}>+ <Plus className="w-4 h-4 mr-1" />+ <FeatureBadge+ feature={PlanFeature.FEATURE_DATABASE_GROUPS}+ className="text-white"+ />+ {t("database-group.create")}+ </Button>+ </div>+ </div>++ <DatabaseGroupTable+ databaseGroupList={filteredList}+ loading={loading}+ showActions={canDelete}+ onRowClick={handleRowClick}+ onDelete={setDeleteTarget}+ />++ {/* Delete confirmation dialog */}+ <Dialog+ open={deleteTarget !== null}+ onOpenChange={(open) => {+ if (!open) setDeleteTarget(null);+ }}+ >+ <DialogContent>+ <DialogTitle>+ {deleteTarget+ ? t("database-group.delete-group", {+ name: deleteTarget.title,+ })+ : ""}+ </DialogTitle>+ <p className="text-sm text-control-light">+ {t("common.cannot-undo-this-action")}+ </p>+ <div className="flex justify-end gap-x-2 mt-4">+ <Button variant="outline" onClick={() => setDeleteTarget(null)}>+ {t("common.cancel")}+ </Button>+ <Button variant="destructive" onClick={handleDelete}>+ {t("common.delete")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </div>+ );+}++// ---------------------------------------------------------------------------+// DatabaseGroupTable+// ---------------------------------------------------------------------------+function DatabaseGroupTable({+ databaseGroupList,+ loading,+ showActions,+ onRowClick,+ onDelete,+}: {+ databaseGroupList: DatabaseGroup[];+ loading: boolean;+ showActions: boolean;+ onRowClick: (e: React.MouseEvent, group: DatabaseGroup) => void;+ onDelete: (group: DatabaseGroup) => void;+}) {+ const { t } = useTranslation();+ const PAGE_SIZE = 20;+ const [page, setPage] = useState(0);++ // Reset page when list changes+ useEffect(() => {+ setPage(0);+ }, [databaseGroupList.length]);++ const totalPages = Math.ceil(databaseGroupList.length / PAGE_SIZE);+ const pagedList = databaseGroupList.slice(+ page * PAGE_SIZE,+ (page + 1) * PAGE_SIZE+ );++ if (loading) {+ return (+ <div className="flex justify-center py-8 text-control-light">+ {t("common.loading")}+ </div>+ );+ }++ if (databaseGroupList.length === 0) {+ return (+ <div className="flex justify-center py-8 text-control-light">+ {t("common.no-data")}+ </div>+ );+ }++ return (+ <div className="px-4">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b text-left text-control-light">+ <th className="py-2 pr-4 font-medium w-64">{t("common.name")}</th>+ <th className="py-2 pr-4 font-medium">+ {t("database.expression")}+ </th>+ {showActions && <th className="py-2 font-medium w-12" />}+ </tr>+ </thead>+ <tbody>+ {pagedList.map((group) => (+ <tr+ key={group.name}+ className="border-b cursor-pointer hover:bg-gray-50"+ onClick={(e) => onRowClick(e, group)}+ >+ <td className="py-2 pr-4 truncate max-w-64">{group.title}</td>+ <td className="py-2 pr-4 truncate text-control-light">+ {group.databaseExpr?.expression || (+ <span className="italic">{t("common.empty")}</span>+ )}+ </td>+ {showActions && (+ <td className="py-2">+ <ActionDropdown group={group} onDelete={onDelete} />+ </td>+ )}+ </tr>+ ))}+ </tbody>+ </table>++ {totalPages > 1 && (+ <div className="flex justify-end items-center gap-x-2 mt-3">+ <Button+ variant="outline"+ size="sm"+ disabled={page === 0}+ onClick={() => setPage((p) => p - 1)}+ >+ {t("common.previous")}+ </Button>+ <span className="text-sm text-control-light">+ {page + 1} / {totalPages}+ </span>+ <Button+ variant="outline"+ size="sm"+ disabled={page >= totalPages - 1}+ onClick={() => setPage((p) => p + 1)}+ >+ {t("common.next")}+ </Button>+ </div>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// ActionDropdown+// ---------------------------------------------------------------------------+function ActionDropdown({+ group,+ onDelete,+}: {+ group: DatabaseGroup;+ onDelete: (group: DatabaseGroup) => void;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);++ return (+ <div className="relative flex justify-end">+ <button+ type="button"+ className="p-1 rounded hover:bg-gray-100"+ onClick={(e) => {+ e.stopPropagation();+ setOpen((v) => !v);+ }}+ >+ <EllipsisVertical className="w-4 h-4" />+ </button>+ {open && (+ <>+ {/* backdrop */}+ <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />+ <div className="absolute right-0 top-full z-20 mt-1 bg-white border rounded shadow-md min-w-[100px]">+ <button+ type="button"+ className="w-full text-left px-3 py-1.5 text-sm hover:bg-gray-50 text-error"+ onClick={(e) => {+ e.stopPropagation();+ setOpen(false);+ onDelete(group);+ }}+ >+ {t("common.delete")}+ </button>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/frontend/src/react/pages/settings/GlobalMaskingPage.tsx b/frontend/src/react/pages/settings/GlobalMaskingPage.tsxindex 33869169b3..276de8af5e 100644--- a/frontend/src/react/pages/settings/GlobalMaskingPage.tsx+++ b/frontend/src/react/pages/settings/GlobalMaskingPage.tsx@@ -7,14 +7,7 @@ import {Plus,Trash2,} from "lucide-react";-import {- useCallback,- useEffect,- useMemo,- useReducer,- useRef,- useState,-} from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";import {@@ -131,7 +124,6 @@ function MaskingRuleConfig({);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(@@ -210,9 +202,9 @@ function MaskingRuleConfig({setDirty(false);};- const handleExprUpdate = useCallback(() => {+ const handleExprUpdate = useCallback((newExpr: ConditionGroupExpr) => {+ setExpr(newExpr);setDirty(true);- forceUpdate();}, []);return (diff --git a/frontend/src/router/dashboard/projectV1.ts b/frontend/src/router/dashboard/projectV1.tsindex cdf38aaa01..74e9091084 100644--- a/frontend/src/router/dashboard/projectV1.ts+++ b/frontend/src/router/dashboard/projectV1.ts@@ -1,4 +1,4 @@-import type { RouteRecordRaw } from "vue-router";+import type { RouteLocationNormalized, RouteRecordRaw } from "vue-router";import ProjectSidebarV1 from "@/components/Project/ProjectSidebarV1.vue";import { t } from "@/plugins/i18n";import { PROJECT_V1_ROUTE_DASHBOARD } from "./workspaceRoutes";@@ -157,8 +157,11 @@ const projectV1Routes: RouteRecordRaw[] = [title: () => t("common.databases"),requiredPermissionList: () => ["bb.databases.list"],},- component: () => import("@/react/ProjectDatabasesPageMount.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "ProjectDatabasesPage",+ ...route.params,+ }),},{path: "access-grants",@@ -217,9 +220,11 @@ const projectV1Routes: RouteRecordRaw[] = [{path: "",name: PROJECT_V1_ROUTE_DATABASE_GROUPS,- component: () =>- import("@/views/project/ProjectDatabaseGroupDashboard.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "ProjectDatabaseGroupsPage",+ ...route.params,+ }),meta: {requiredPermissionList: () => ["bb.databaseGroups.list"],},@@ -233,16 +238,20 @@ const projectV1Routes: RouteRecordRaw[] = ["bb.databases.list",],},- component: () =>- import("@/views/project/ProjectDatabaseGroupCreate.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "ProjectDatabaseGroupCreatePage",+ ...route.params,+ }),},{path: ":databaseGroupName",name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,- component: () =>- import("@/views/project/ProjectDatabaseGroupDetail.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "ProjectDatabaseGroupDetailPage",+ ...route.params,+ }),meta: {requiredPermissionList: () => ["bb.databaseGroups.get",@@ -296,8 +305,11 @@ const projectV1Routes: RouteRecordRaw[] = [title: () => t("settings.sidebar.audit-log"),requiredPermissionList: () => ["bb.auditLogs.search"],},- component: () => import("@/react/ProjectAuditLogPageMount.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "ProjectAuditLogPage",+ ...route.params,+ }),},{path: "webhooks",@@ -472,8 +484,11 @@ const projectV1Routes: RouteRecordRaw[] = ["bb.databases.list",],},- component: () => import("@/react/ProjectGitOpsPageMount.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "ProjectGitOpsPage",+ ...route.params,+ }),},...planRoutes,...issueRoutes,diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.tsindex 7b0002d6b5..3424948e0c 100644--- a/frontend/src/router/dashboard/workspace.ts+++ b/frontend/src/router/dashboard/workspace.ts@@ -1,4 +1,4 @@-import type { RouteRecordRaw } from "vue-router";+import type { RouteLocationNormalized, RouteRecordRaw } from "vue-router";import DummyRootView from "@/DummyRootView";import { t } from "@/plugins/i18n";import {@@ -203,8 +203,11 @@ const workspaceRoutes: RouteRecordRaw[] = ["bb.policies.get",],},- component: () => import("@/react/SQLReviewDetailPageMount.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "SQLReviewDetailPage",+ ...route.params,+ }),},],},diff --git a/frontend/src/views/project/ProjectDatabaseGroupCreate.vue b/frontend/src/views/project/ProjectDatabaseGroupCreate.vuedeleted file mode 100644index 342bc3b8e9..0000000000--- a/frontend/src/views/project/ProjectDatabaseGroupCreate.vue+++ /dev/null@@ -1,34 +0,0 @@-<template>- <DatabaseGroupForm- class="py-4 h-full"- :readonly="false"- :project="project"- @dismiss="() => router.back()"- @created="(databaseGroupName: string) => {- router.push({- name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,- params: {- databaseGroupName,- },- });- }"- />-</template>--<script lang="tsx" setup>-import { computed } from "vue";-import { useRouter } from "vue-router";-import DatabaseGroupForm from "@/components/DatabaseGroup/DatabaseGroupForm.vue";-import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/router/dashboard/projectV1";-import { useProjectByName } from "@/store";-import { projectNamePrefix } from "@/store/modules/v1/common";--const props = defineProps<{- projectId: string;-}>();--const { project } = useProjectByName(- computed(() => `${projectNamePrefix}${props.projectId}`)-);-const router = useRouter();-</script>diff --git a/frontend/src/views/project/ProjectDatabaseGroupDashboard.vue b/frontend/src/views/project/ProjectDatabaseGroupDashboard.vuedeleted file mode 100644index dc56ec8ffa..0000000000--- a/frontend/src/views/project/ProjectDatabaseGroupDashboard.vue+++ /dev/null@@ -1,92 +0,0 @@-<template>- <div class="py-4 flex flex-col">- <div class="px-4 flex flex-col gap-y-2 pb-2">- <FeatureAttention :feature="PlanFeature.FEATURE_DATABASE_GROUPS" />- <div class="flex flex-row items-center justify-end gap-x-2">- <SearchBox- v-model:value="state.searchText"- style="max-width: 100%"- :placeholder="$t('common.filter-by-name')"- />- <PermissionGuardWrapper- v-slot="slotProps"- :project="project"- :permissions="['bb.databaseGroups.create']"- >- <NButton- type="primary"- :disabled="slotProps.disabled"- @click="- () => {- if (!hasDBGroupFeature) {- state.showFeatureModal = true;- return;- }- router.push({- name: PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE,- });- }- "- >- <template #icon>- <PlusIcon class="w-4" />- <FeatureBadge- :feature="PlanFeature.FEATURE_DATABASE_GROUPS"- class="text-white"- />- </template>- {{ $t("database-group.create") }}- </NButton>- </PermissionGuardWrapper>- </div>- </div>- <ProjectDatabaseGroupPanel :project="project" :filter="state.searchText" />- </div>-- <FeatureModal- :open="state.showFeatureModal"- :feature="PlanFeature.FEATURE_DATABASE_GROUPS"- @cancel="state.showFeatureModal = false"- />-</template>--<script setup lang="ts">-import { PlusIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, reactive } from "vue";-import { useRouter } from "vue-router";-import ProjectDatabaseGroupPanel from "@/components/DatabaseGroup/ProjectDatabaseGroupPanel.vue";-import {- FeatureAttention,- FeatureBadge,- FeatureModal,-} from "@/components/FeatureGuard";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import { SearchBox } from "@/components/v2";-import { PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE } from "@/router/dashboard/projectV1";-import { hasFeature, useProjectByName } from "@/store";-import { projectNamePrefix } from "@/store/modules/v1/common";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";--interface LocalState {- showFeatureModal: boolean;- searchText: string;-}--const props = defineProps<{- projectId: string;-}>();--const { project } = useProjectByName(- computed(() => `${projectNamePrefix}${props.projectId}`)-);-const router = useRouter();-const state = reactive<LocalState>({- showFeatureModal: false,- searchText: "",-});--const hasDBGroupFeature = computed(() =>- hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)-);-</script>diff --git a/frontend/src/views/project/ProjectDatabaseGroupDetail.vue b/frontend/src/views/project/ProjectDatabaseGroupDetail.vuedeleted file mode 100644index 2c9e4d6136..0000000000--- a/frontend/src/views/project/ProjectDatabaseGroupDetail.vue+++ /dev/null@@ -1,189 +0,0 @@-<template>- <div- v-if="databaseGroup"- v-bind="$attrs"- class="min-h-full flex-1 relative flex flex-col gap-y-4 px-4 pt-4"- >- <FeatureAttention- :feature="PlanFeature.FEATURE_DATABASE_GROUPS"- class="mb-4"- />-- <div- v-if="hasDatabaseGroupFeature && !state.editing"- class="flex flex-row justify-end items-center flex-wrap shrink gap-x-2 gap-y-2"- >- <PermissionGuardWrapper- v-slot="slotProps"- :project="project"- :permissions="[- ...PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE- ]"- >- <NTooltip- :disabled="slotProps.disabled || hasMatchedDatabases"- >- <template #trigger>- <NButton- :disabled="slotProps.disabled || !hasMatchedDatabases"- @click="() => {- preCreateIssue(project.name, [databaseGroupResourceName])- }"- >- {{ $t("database.change-database") }}- </NButton>- </template>- {{ $t("database-group.no-matched-databases") }}- </NTooltip>- </PermissionGuardWrapper>-- <PermissionGuardWrapper- v-slot="slotProps"- :project="project"- :permissions="[- 'bb.databaseGroups.update',- ]"- >- <NButton type="primary" :disabled="slotProps.disabled" @click="state.editing = true">- <template #icon>- <EditIcon class="w-4 h-4" />- </template>- {{ $t("common.configure") }}- </NButton>- </PermissionGuardWrapper>-- <NDropdown- v-if="dropdownOptions.length > 0"- trigger="click"- :options="dropdownOptions"- @select="handleDropdownSelect"- >- <NButton size="small" quaternary class="px-1!">- <template #icon>- <EllipsisVerticalIcon class="w-4 h-4" />- </template>- </NButton>- </NDropdown>- </div>-- <DatabaseGroupForm- :readonly="!state.editing"- :project="project"- :database-group="databaseGroup"- @dismiss="state.editing = false"- />- </div>-</template>--<script lang="ts" setup>-import { EditIcon, EllipsisVerticalIcon } from "lucide-vue-next";-import type { DropdownOption } from "naive-ui";-import { NButton, NDropdown, NTooltip, useDialog } from "naive-ui";-import { computed, reactive, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import DatabaseGroupForm from "@/components/DatabaseGroup/DatabaseGroupForm.vue";-import FeatureAttention from "@/components/FeatureGuard/FeatureAttention.vue";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import { preCreateIssue } from "@/components/Plan/logic/issue";-import { PROJECT_V1_ROUTE_DATABASE_GROUPS } from "@/router/dashboard/projectV1";-import {- featureToRef,- useDBGroupStore,- useGracefulRequest,- useProjectByName,-} from "@/store";-import {- databaseGroupNamePrefix,- projectNamePrefix,-} from "@/store/modules/v1/common";-import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import {- hasProjectPermissionV2,- PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE,-} from "@/utils";--interface LocalState {- editing: boolean;-}--const props = defineProps<{- projectId: string;- databaseGroupName: string;- allowEdit: boolean;-}>();--const dbGroupStore = useDBGroupStore();-const { project } = useProjectByName(- computed(() => `${projectNamePrefix}${props.projectId}`)-);-const { t } = useI18n();-const dialog = useDialog();-const router = useRouter();-const state = reactive<LocalState>({- editing: false,-});--const databaseGroupResourceName = computed(() => {- return `${project.value.name}/${databaseGroupNamePrefix}${props.databaseGroupName}`;-});--const databaseGroup = computed(() => {- return dbGroupStore.getDBGroupByName(databaseGroupResourceName.value);-});--const hasMatchedDatabases = computed(- () => (databaseGroup.value?.matchedDatabases.length ?? 0) > 0-);--const hasDatabaseGroupFeature = featureToRef(- PlanFeature.FEATURE_DATABASE_GROUPS-);--const allowDelete = computed(() => {- return hasProjectPermissionV2(project.value, "bb.databaseGroups.delete");-});--const dropdownOptions = computed((): DropdownOption[] => {- if (!allowDelete.value) {- return [];- }- return [- {- key: "delete",- label: t("common.delete"),- },- ];-});--const handleDropdownSelect = (key: string) => {- if (key === "delete" && databaseGroup.value) {- dialog.warning({- title: t("database-group.delete-group", {- name: databaseGroup.value.title,- }),- content: t("common.cannot-undo-this-action"),- negativeText: t("common.cancel"),- positiveText: t("common.delete"),- onPositiveClick: () => {- useGracefulRequest(async () => {- await dbGroupStore.deleteDatabaseGroup(- databaseGroupResourceName.value- );- router.push({- name: PROJECT_V1_ROUTE_DATABASE_GROUPS,- });- });- },- });- }-};--watchEffect(async () => {- await dbGroupStore.getOrFetchDBGroupByName(databaseGroupResourceName.value, {- skipCache: true,- view: DatabaseGroupView.FULL,- });-});-</script>