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: support load more for selector (#18538)
ecmadao27ed0a1e1842
diff --git a/frontend/src/components/Member/MembersBindingSelect.vue b/frontend/src/components/Member/MembersBindingSelect.vueindex e8ab29e7a1..e028dc6350 100644--- a/frontend/src/components/Member/MembersBindingSelect.vue+++ b/frontend/src/components/Member/MembersBindingSelect.vue@@ -28,9 +28,9 @@</template></i18n-t><div+ v-if="memberType === 'USERS'":class="['w-full flex flex-col gap-y-2',- memberType !== 'USERS' ? 'hidden' : '',]"><div class="flex text-main items-center gap-x-1">@@ -50,12 +50,12 @@/></div><div+ v-else:class="['w-full flex flex-col gap-y-2',- memberType !== 'GROUPS' ? 'hidden' : '',]">- <div class="flex font-medium text-main items-center gap-x-1">+ <div class="flex text-main items-center gap-x-1">{{ $t("settings.members.select-group", 2 /* multiply*/) }}<RequiredStar v-if="required" /></div>@@ -78,7 +78,11 @@ import { NRadio, NRadioGroup } from "naive-ui";import { computed, ref } from "vue";import RequiredStar from "@/components/RequiredStar.vue";import { GroupSelect, UserSelect } from "@/components/v2";-import { extractGroupEmail, extractUserId, useGroupStore } from "@/store";+import {+ ensureGroupIdentifier,+ extractGroupEmail,+ extractUserId,+} from "@/store";import { groupNamePrefix } from "@/store/modules/v1/common";import {getGroupEmailInBinding,@@ -115,8 +119,17 @@ const emit = defineEmits<{(event: "update:value", memberList: string[]): void;}>();-const memberType = ref<MemberType>("USERS");-const groupStore = useGroupStore();+const initMemberType = computed((): MemberType => {+ for (const binding of props.value) {+ if (binding.startsWith(groupBindingPrefix)) {+ return "GROUPS";+ }+ return "USERS";+ }+ return "USERS";+});++const memberType = ref<MemberType>(initMemberType.value);const onTypeChange = (type: MemberType) => {emit("update:value", []);@@ -128,11 +141,7 @@ const memberList = computed(() => {for (const binding of props.value) {if (binding.startsWith(groupBindingPrefix)) {- const group = groupStore.getGroupByIdentifier(binding);- if (!group) {- continue;- }- list.push(group.name);+ list.push(ensureGroupIdentifier(binding));} else {// For users, extract email from binding format "user:{email}"const email = extractUserId(binding);diff --git a/frontend/src/components/SQLReview/SQLReviewInfo.vue b/frontend/src/components/SQLReview/SQLReviewInfo.vueindex 429cdbaa7d..eeb5cac664 100644--- a/frontend/src/components/SQLReview/SQLReviewInfo.vue+++ b/frontend/src/components/SQLReview/SQLReviewInfo.vue@@ -65,7 +65,7 @@required:database-name="attachedResources[0]":disabled="!allowChangeAttachedResource"- :filter="(db: Database, _: number) => filterResource(db.name)"+ :filter="(db: Database) => filterResource(db.name)"@update:database-names="$emit('attached-resources-change', $event)"/></div>@@ -86,7 +86,6 @@@update:value="emit('name-change', $event)"/><ResourceIdField- ref="resourceIdField"class="mt-1"editing-class="mt-6"resource-type="review-config"@@ -116,7 +115,7 @@<script lang="ts" setup>import { NRadio, NRadioGroup } from "naive-ui";-import { computed, ref, watch } from "vue";+import { computed, watch } from "vue";import { BBAttention, BBTextField } from "@/bbkit";import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";import { useResourceByName } from "@/components/v2/ResourceOccupiedModal/useResourceByName";@@ -169,6 +168,4 @@ const filterResource = (name: string): boolean => {}return !sqlReviewStore.getReviewPolicyByResouce(name);};--const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();</script>diff --git a/frontend/src/components/SyncDatabaseSchemaV1/DatabaseSchemaSelector.vue b/frontend/src/components/SyncDatabaseSchemaV1/DatabaseSchemaSelector.vueindex 0a4e34068b..b9d2bd5ac8 100644--- a/frontend/src/components/SyncDatabaseSchemaV1/DatabaseSchemaSelector.vue+++ b/frontend/src/components/SyncDatabaseSchemaV1/DatabaseSchemaSelector.vue@@ -15,11 +15,11 @@@update:environment-name="handleEnvironmentSelect"/><DatabaseSelect+ :placeholder="$t('database.select')":project-name="project.name":database-name="state.databaseName":environment-name="state.environmentName":allowed-engine-type-list="ALLOWED_ENGINES"- :fallback-option="false"@update:database-name="handleDatabaseSelect"/></div>diff --git a/frontend/src/components/TransferDatabaseForm/TransferDatabaseForm.vue b/frontend/src/components/TransferDatabaseForm/TransferDatabaseForm.vueindex ecf2b97042..89cfaf242e 100644--- a/frontend/src/components/TransferDatabaseForm/TransferDatabaseForm.vue+++ b/frontend/src/components/TransferDatabaseForm/TransferDatabaseForm.vue@@ -14,9 +14,9 @@v-if="state.transferSource == 'OTHER'"class="w-48!":include-all="false"+ :include-default-project="true":project-name="state.fromProjectName":filter="filterSourceProject"- :default-select-first="true"@update:project-name="changeProjectFilter"/><template@@ -160,7 +160,6 @@ const filter = computed(() => ({? formatEnvironmentName(state.environmentFilter.id): undefined,query: state.searchText,- excludeUnassigned: state.transferSource !== "DEFAULT",}));const allowTransfer = computed(() => state.selectedDatabaseNameList.length > 0);diff --git a/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue b/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vueindex 4ba9d09c3d..8ed27058aa 100644--- a/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue+++ b/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue@@ -29,7 +29,8 @@<InstanceSelectclass="w-40!":project-name="sourceProjectName"- :instance="instance?.name ?? ''"+ :instance-name="instance?.name ?? ''"+ :environment-name="environment?.name"@update:instance-name="changeInstanceFilter"/><SearchBoxdiff --git a/frontend/src/components/TransferOutDatabaseForm/TransferOutDatabaseForm.vue b/frontend/src/components/TransferOutDatabaseForm/TransferOutDatabaseForm.vueindex 30c438ce06..943b86037d 100644--- a/frontend/src/components/TransferOutDatabaseForm/TransferOutDatabaseForm.vue+++ b/frontend/src/components/TransferOutDatabaseForm/TransferOutDatabaseForm.vue@@ -35,7 +35,6 @@<ProjectSelectv-if="transfer === 'project'"v-model:project-name="targetProjectName"- :default-select-first="true":allowed-project-role-list="[PresetRoleType.PROJECT_OWNER]"/></div>diff --git a/frontend/src/components/User/Settings/CreateGroupDrawer.vue b/frontend/src/components/User/Settings/CreateGroupDrawer.vueindex baa4c46662..dc2abdfda8 100644--- a/frontend/src/components/User/Settings/CreateGroupDrawer.vue+++ b/frontend/src/components/User/Settings/CreateGroupDrawer.vue@@ -63,13 +63,7 @@:size="'medium'":include-all="false":disabled="!allowEdit"- :filter="- (user, _) =>- !state.group.members.find(- (member) =>- member.member === `${userNamePrefix}${user.email}`- )- "+ :filter="(user) => userFilter(user, member.member)"@update:user="(email) => updateMemberEmail(i, email)"/><GroupMemberRoleSelect@@ -169,6 +163,7 @@ import {GroupMemberSchema,GroupSchema,} from "@/types/proto-es/v1/group_service_pb";+import { type User } from "@/types/proto-es/v1/user_service_pb";import { hasWorkspacePermissionV2, isValidEmail } from "@/utils";import RemoveGroupButton from "./RemoveGroupButton.vue";import GroupMemberRoleSelect from "./UserDataTableByGroup/cells/GroupMemberRoleSelect.vue";@@ -214,6 +209,15 @@ const state = reactive<LocalState>({},});+const userFilter = (user: User, member: string) => {+ if (extractUserId(member) === user.email) {+ return true;+ }+ return !state.group.members.find(+ (member) => member.member === `${userNamePrefix}${user.email}`+ );+};+const isCreating = computed(() => !props.group);const isGroupOwner = computed(() => {diff --git a/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue b/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vueindex b944664419..fc1c11a575 100644--- a/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue+++ b/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue@@ -14,9 +14,17 @@}"class="normal-link font-medium">- {{ group.title }}+ <HighlightLabelText+ :text="group.title"+ :keyword="keyword"+ /></router-link>- <span v-else class="font-medium">{{ group.title }}</span>+ <HighlightLabelText+ v-else+ class="font-medium"+ :text="group.title"+ :keyword="keyword"+ /></div><NTag v-if="deleted" size="small" round type="error">{{ $t("common.deleted") }}@@ -31,9 +39,12 @@</span><UserRolesCell v-if="role" :role="role" /></div>- <span v-if="showEmail && group.email" class="textinfolabel text-sm">- {{ group.email }}- </span>+ <HighlightLabelText+ v-if="showEmail && group.email"+ class="textinfolabel text-sm"+ :text="group.email"+ :keyword="keyword"+ /></div></div></template>@@ -44,6 +55,7 @@ import { NTag } from "naive-ui";import { computed } from "vue";import UserRolesCell from "@/components/Member/MemberDataTable/cells/UserRolesCell.vue";import type { MemberRole } from "@/components/Member/types";+import { HighlightLabelText } from "@/components/v2";import { WORKSPACE_ROUTE_USERS } from "@/router/dashboard/workspaceRoutes";import { extractUserId, useCurrentUserV1 } from "@/store";import type { Group } from "@/types/proto-es/v1/group_service_pb";@@ -57,6 +69,7 @@ const props = withDefaults(showEmail?: boolean;link?: boolean;deleted?: boolean;+ keyword?: string;}>(),{showIcon: true,@@ -64,6 +77,7 @@ const props = withDefaults(role: undefined,link: true,deleted: false,+ keyword: "",});diff --git a/frontend/src/components/v2/Model/RichDatabaseName.vue b/frontend/src/components/v2/Model/RichDatabaseName.vueindex 57f53043eb..a206d1a423 100644--- a/frontend/src/components/v2/Model/RichDatabaseName.vue+++ b/frontend/src/components/v2/Model/RichDatabaseName.vue@@ -8,9 +8,9 @@:link="false"/>- <heroicons:chevron-right+ <ChevronRightIconv-if="showProject && showArrow"- class="text-control-light"+ class="w-3"/><div@@ -29,9 +29,9 @@/></div>- <heroicons:chevron-right+ <ChevronRightIconv-if="(showInstance || showEngineIcon) && showArrow"- class="text-control-light"+ class="w-3"/><div class="flex flex-row items-center gap-x-1">@@ -62,6 +62,7 @@</template><script setup lang="ts">+import { ChevronRightIcon } from "lucide-vue-next";import { NPopover } from "naive-ui";import type { ComposedDatabase } from "@/types";import DatabaseV1Name from "./DatabaseV1Name.vue";diff --git a/frontend/src/components/v2/Model/cells/UserNameCell.vue b/frontend/src/components/v2/Model/cells/UserNameCell.vueindex 9c73a88a6b..082722a334 100644--- a/frontend/src/components/v2/Model/cells/UserNameCell.vue+++ b/frontend/src/components/v2/Model/cells/UserNameCell.vue@@ -6,26 +6,31 @@<div class="flex flex-col"><div class="flex flex-row items-center gap-x-1"><div :class="isDeleted ? 'line-through' : ''">- <span- v-if="onClickUser"- class="normal-link truncate max-w-40"- @click="onClickUser(user, $event)"- >- {{ user.title }}- </span>- <span- v-else-if="permissionStore.onlyWorkspaceMember"+ <HighlightLabelText+ v-if="permissionStore.onlyWorkspaceMember"class="truncate max-w-[10em]"- >- {{ user.title }}- </span>- <router-link- v-else- :to="`/users/${user.email}`"- class="normal-link truncate max-w-[10em]"- >- {{ user.title }}- </router-link>+ :keyword="keyword"+ :text="user.title"+ />+ <template v-else>+ <HighlightLabelText+ v-if="onClickUser || !link"+ :class="['truncate max-w-40', link ? 'normal-link' : '']"+ :keyword="keyword"+ :text="user.title"+ @click="onClickUser ? onClickUser(user, $event) : null"+ />+ <router-link+ v-else+ :to="`/users/${user.email}`"+ class="normal-link truncate max-w-[10em]"+ >+ <HighlightLabelText+ :keyword="keyword"+ :text="user.title"+ />+ </router-link>+ </template></div><slot name="suffix"></slot>@@ -94,7 +99,7 @@ import SystemBotTag from "@/components/misc/SystemBotTag.vue";import WorkloadIdentityTag from "@/components/misc/WorkloadIdentityTag.vue";import YouTag from "@/components/misc/YouTag.vue";import UserAvatar from "@/components/User/UserAvatar.vue";-import { CopyButton } from "@/components/v2";+import { CopyButton, HighlightLabelText } from "@/components/v2";import { useCurrentUserV1, usePermissionStore } from "@/store";import { SYSTEM_BOT_USER_NAME } from "@/types";import { State } from "@/types/proto-es/v1/common_pb";@@ -105,10 +110,12 @@ const props = withDefaults(defineProps<{user: User;allowEdit?: boolean;+ keyword?: string;size?: "small" | "medium";+ link?: boolean;onClickUser?: (user: User, event: MouseEvent) => void;}>(),- { allowEdit: true, size: "medium" }+ { allowEdit: true, size: "medium", link: true, keyword: "" });defineEmits<{diff --git a/frontend/src/components/v2/Select/DatabaseGroupSelect.vue b/frontend/src/components/v2/Select/DatabaseGroupSelect.vueindex 10a3a7bbf5..b65e6fba36 100644--- a/frontend/src/components/v2/Select/DatabaseGroupSelect.vue+++ b/frontend/src/components/v2/Select/DatabaseGroupSelect.vue@@ -1,5 +1,5 @@<template>- <ResourceSelect+ <LocalResourceSelectorv-bind="$attrs":placeholder="$t('database-group.select')":value="selected"@@ -12,7 +12,7 @@<script lang="ts" setup>import { computed } from "vue";import { useDBGroupListByProject } from "@/store";-import ResourceSelect from "./ResourceSelect.vue";+import LocalResourceSelector from "./LocalResourceSelector.vue";const props = withDefaults(defineProps<{diff --git a/frontend/src/components/v2/Select/DatabaseSelect.vue b/frontend/src/components/v2/Select/DatabaseSelect.vueindex 13c1ca00a9..761451a6bb 100644--- a/frontend/src/components/v2/Select/DatabaseSelect.vue+++ b/frontend/src/components/v2/Select/DatabaseSelect.vue@@ -1,47 +1,29 @@<template>- <ResourceSelect+ <RemoteResourceSelectorv-bind="$attrs"class="bb-database-select"- :remote="true"- :loading="state.loading":multiple="multiple":value="databaseName":values="databaseNames"- :options="options":custom-label="renderLabel"- @search="handleSearch"+ :additional-data="additionalData"+ :search="handleSearch"+ :get-option="getOption"+ :filter="filter"@update:value="(val) => $emit('update:database-name', val)"@update:values="(val) => $emit('update:database-names', val)"/></template>-<script lang="ts" setup>-import { useDebounceFn } from "@vueuse/core";-import { computed, h, reactive, watch } from "vue";-import { useI18n } from "vue-i18n";+<script lang="tsx" setup>+import { computedAsync } from "@vueuse/core";+import { RichDatabaseName } from "@/components/v2";import { useDatabaseV1Store } from "@/store";import { workspaceNamePrefix } from "@/store/modules/v1/common";import type { ComposedDatabase } from "@/types";-import {- DEBOUNCE_SEARCH_DELAY,- isValidDatabaseName,- unknownDatabase,-} from "@/types";+import { isValidDatabaseName } from "@/types";import { type Engine } from "@/types/proto-es/v1/common_pb";-import {- getDefaultPagination,- instanceV1Name,- supportedEngineV1List,-} from "@/utils";-import { InstanceV1EngineIcon } from "../Model";-import ResourceSelect from "./ResourceSelect.vue";--interface LocalState {- loading: boolean;- rawDatabaseList: ComposedDatabase[];- // Track if initial fetch has been done to avoid redundant API calls- initialized: boolean;-}+import RemoteResourceSelector from "./RemoteResourceSelector.vue";const props = withDefaults(defineProps<{@@ -50,200 +32,84 @@ const props = withDefaults(environmentName?: string;projectName?: string;allowedEngineTypeList?: Engine[];- includeAll?: boolean;- autoReset?: boolean;- filter?: (database: ComposedDatabase, index: number) => boolean;+ filter?: (database: ComposedDatabase) => boolean;multiple?: boolean;clearable?: boolean;- defaultSelectFirst?: boolean;+ showInstance?: boolean;}>(),{databaseName: undefined,databaseNames: undefined,environmentName: undefined,projectName: undefined,- allowedEngineTypeList: () => supportedEngineV1List(),- includeAll: false,- autoReset: true,+ // empty equals no limit.+ allowedEngineTypeList: () => [],filter: undefined,multiple: false,clearable: false,- defaultSelectFirst: false,+ showInstance: true,});-const emit = defineEmits<{+defineEmits<{(event: "update:database-name", value: string | undefined): void;(event: "update:database-names", value: string[]): void;}>();-const { t } = useI18n();const databaseStore = useDatabaseV1Store();-const state = reactive<LocalState>({- loading: false,- rawDatabaseList: [],- initialized: false,-});+const additionalData = computedAsync(async () => {+ const data = [];++ let databaseNames: string[] = [];+ if (props.databaseName) {+ databaseNames = [props.databaseName];+ } else if (props.databaseNames) {+ databaseNames = props.databaseNames;+ }-const initSelectedDatabases = async (databaseNames: string[]) => {for (const databaseName of databaseNames) {if (isValidDatabaseName(databaseName)) {const db = await databaseStore.getOrFetchDatabaseByName(databaseName);- if (!state.rawDatabaseList.find((d) => d.name === db.name)) {- state.rawDatabaseList.unshift(db);- }+ data.push(db);}}-};-const searchDatabases = async (name: string) => {- const { databases } = await databaseStore.fetchDatabases({+ return data;+}, []);++const handleSearch = async (params: {+ search: string;+ pageToken: string;+ pageSize: number;+}) => {+ const { databases, nextPageToken } = await databaseStore.fetchDatabases({parent: props.projectName ?? `${workspaceNamePrefix}-`,filter: {environment: props.environmentName,engines: props.allowedEngineTypeList,- query: name,+ query: params.search,},- pageSize: getDefaultPagination(),+ pageToken: params.pageToken,+ pageSize: params.pageSize,});- return databases;-};--const initDatabaseList = async () => {- if (props.includeAll) {- const dummyAll = {- ...unknownDatabase(),- databaseName: t("database.all"),- };- if (!state.rawDatabaseList.find((d) => d.name === dummyAll.name)) {- state.rawDatabaseList.unshift(dummyAll);- }- }- if (props.databaseName) {- await initSelectedDatabases([props.databaseName]);- }- if (props.databaseNames) {- await initSelectedDatabases(props.databaseNames);- }+ return { nextPageToken, data: databases };};-const handleSearch = useDebounceFn(async (search: string) => {- // Skip if no search term and already initialized (lazy loading optimization)- if (!search && state.initialized) {- return;- }-- state.loading = true;- try {- const databases = await searchDatabases(search);- state.rawDatabaseList = databases;- if (!search) {- state.initialized = true;- await initDatabaseList();- }- } finally {- state.loading = false;- }-}, DEBOUNCE_SEARCH_DELAY);--// Only fetch selected database(s) on mount, not the entire list.-// The full list will be fetched lazily when dropdown is opened.-// Re-initialize when filter props change.-watch(- () => [props.environmentName, props.allowedEngineTypeList],- () => {- state.initialized = false;- state.rawDatabaseList = [];- initDatabaseList();- },- {- deep: true,- immediate: true,- }-);--const combinedDatabaseList = computed(() => {- if (props.filter) {- return state.rawDatabaseList.filter(props.filter);- }-- return state.rawDatabaseList;+const getOption = (database: ComposedDatabase) => ({+ value: database.name,+ label: database.databaseName,});-const options = computed(() => {- return combinedDatabaseList.value.map((database) => {- return {- resource: database,- value: database.name,- label: database.databaseName,- };- });-});--watch(- () => options.value,- () => {- if (!props.defaultSelectFirst || props.multiple) {- return;- }- if (options.value.length === 0) {- return;- }-- emit("update:database-name", options.value[0].value);- },- { immediate: true }-);--const renderLabel = (database: ComposedDatabase) => {- const children = [h("div", {}, [database.databaseName])];- if (isValidDatabaseName(database.name)) {- // prefix engine icon- children.unshift(- h(InstanceV1EngineIcon, {- class: "mr-1",- instance: database.instanceResource,- })- );- // suffix engine name- children.push(- h(- "div",- {- class: "text-xs opacity-60 ml-1",- },- [`(${instanceV1Name(database.instanceResource)})`]- )- );- }- return h(- "div",- {- class: "w-full flex flex-row justify-start items-center truncate",- },- children+const renderLabel = (database: ComposedDatabase, keyword: string) => {+ return (+ <RichDatabaseName+ database={database}+ keyword={keyword}+ showProject={false}+ showInstance={props.showInstance}+ showArrow={props.showInstance}+ />);};--// The database list might change if environment changes, and the previous selected id-// might not exist in the new list. In such case, we need to invalidate the selection-// and emit the event.-const resetInvalidSelection = () => {- if (!props.autoReset || props.multiple) return;- if (state.loading) return;- // Don't reset selection before the full database list has been fetched- if (!state.initialized) return;- if (- props.databaseName &&- !combinedDatabaseList.value.find((item) => item.name === props.databaseName)- ) {- emit("update:database-name", undefined);- }-};--watch(() => combinedDatabaseList.value, resetInvalidSelection, {- immediate: true,- deep: true,-});</script>diff --git a/frontend/src/components/v2/Select/EnvironmentSelect.vue b/frontend/src/components/v2/Select/EnvironmentSelect.vueindex f2c2e2d681..aa503a9e70 100644--- a/frontend/src/components/v2/Select/EnvironmentSelect.vue+++ b/frontend/src/components/v2/Select/EnvironmentSelect.vue@@ -1,5 +1,5 @@<template>- <ResourceSelect+ <LocalResourceSelectorv-bind="$attrs":placeholder="t('environment.select')":multiple="multiple"@@ -20,7 +20,7 @@ import { useEnvironmentV1Store } from "@/store";import { formatEnvironmentName } from "@/types";import type { Environment } from "@/types/v1/environment";import { EnvironmentV1Name } from "../Model";-import ResourceSelect from "./ResourceSelect.vue";+import LocalResourceSelector from "./LocalResourceSelector.vue";const { t } = useI18n();diff --git a/frontend/src/components/v2/Select/GroupSelect.vue b/frontend/src/components/v2/Select/GroupSelect.vueindex 56eddd6eb1..bc0bff46f8 100644--- a/frontend/src/components/v2/Select/GroupSelect.vue+++ b/frontend/src/components/v2/Select/GroupSelect.vue@@ -1,28 +1,25 @@<template>- <ResourceSelect+ <RemoteResourceSelectorv-bind="$attrs"- :remote="true"- :value="validSelectedGroup"- :values="validSelectedGroups"+ :value="group"+ :values="groups":disabled="disabled":multiple="multiple"- :options="options":custom-label="renderLabel"- @search="handleSearch"+ :additional-data="additionalData"+ :search="handleSearch"+ :get-option="getOption"@update:value="(val) => $emit('update:group', val)"@update:values="(val) => $emit('update:groups', val)"/></template><script lang="tsx" setup>-import { useDebounceFn } from "@vueuse/core";-import { computed, onMounted, reactive } from "vue";+import { computedAsync } from "@vueuse/core";import GroupNameCell from "@/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue";import { useGroupStore } from "@/store";-import { DEBOUNCE_SEARCH_DELAY } from "@/types";import type { Group } from "@/types/proto-es/v1/group_service_pb";-import { getDefaultPagination } from "@/utils";-import ResourceSelect from "./ResourceSelect.vue";+import RemoteResourceSelector from "./RemoteResourceSelector.vue";const props = withDefaults(defineProps<{@@ -31,16 +28,12 @@ const props = withDefaults(disabled?: boolean;multiple?: boolean;projectName?: string;- selectFirstAsDefault?: boolean;- size?: "tiny" | "small" | "medium" | "large";}>(),{group: undefined,groups: undefined,multiple: false,projectName: undefined,- selectFirstAsDefault: true,- size: "medium",});@@ -49,111 +42,59 @@ defineEmits<{(event: "update:groups", val: string[]): void;}>();-interface LocalState {- loading: boolean;- rawList: Group[];- // Track if initial fetch has been done to avoid redundant API calls- initialized: boolean;-}--const state = reactive<LocalState>({- loading: false,- rawList: [],- initialized: false,-});-const groupStore = useGroupStore();-const searchGroups = async (search: string) => {- const { groups } = await groupStore.fetchGroupList({- filter: {- query: search,- project: props.projectName,- },- pageSize: getDefaultPagination(),- });- return groups;-};--const initSelectedGroups = async (groupNames: string[]) => {- if (groupNames.length === 0) return;- const groups = await groupStore.batchFetchGroups(groupNames);- for (const group of groups) {- if (!state.rawList.find((g) => g.name === group.name)) {- state.rawList.unshift(group);- }- }-};--const handleSearch = useDebounceFn(async (search: string) => {- // Skip if no search term and already initialized (lazy loading optimization)- if (!search && state.initialized) {- return;- }+const additionalData = computedAsync(async () => {+ const data = [];- state.loading = true;- try {- const groups = await searchGroups(search);- state.rawList = groups;- if (!search) {- state.initialized = true;- if (props.group) {- await initSelectedGroups([props.group]);- }- if (props.groups) {- await initSelectedGroups(props.groups);- }- }- } finally {- state.loading = false;- }-}, DEBOUNCE_SEARCH_DELAY);--// Only fetch selected group(s) on mount, not the entire list.-// The full list will be fetched lazily when dropdown is opened.-onMounted(async () => {+ let groupNames: string[] = [];if (props.group) {- await initSelectedGroups([props.group]);+ groupNames = [props.group];} else if (props.groups) {- await initSelectedGroups(props.groups);+ groupNames = props.groups;}-});--const options = computed(() => {- return state.rawList.map((group) => ({- value: group.name,- label: group.title,- resource: group,- }));-});-const validSelectedGroup = computed(() => {- if (props.multiple) {- return undefined;- }- if (options.value.findIndex((o) => o.value === props.group) >= 0) {- return props.group;+ const groups = await groupStore.batchFetchGroups(groupNames);+ for (const group of groups) {+ data.push(group);}- return undefined;-});-const validSelectedGroups = computed(() => {- if (!props.multiple) {- return undefined;- }+ return data;+}, []);- return props.groups?.filter((v) => {- return options.value.findIndex((o) => o.value === v) >= 0;+const handleSearch = async (params: {+ search: string;+ pageToken: string;+ pageSize: number;+}) => {+ const { groups, nextPageToken } = await groupStore.fetchGroupList({+ filter: {+ query: params.search,+ project: props.projectName,+ },+ pageToken: params.pageToken,+ pageSize: params.pageSize,});++ return {+ nextPageToken,+ data: groups,+ };+};++const getOption = (group: Group) => ({+ value: group.name,+ label: group.title,});-const renderLabel = (group: Group) => {+const renderLabel = (group: Group, keyword: string) => {return (<GroupNameCellshowEmail={false}group={group}showIcon={false}link={false}+ keyword={keyword}/>);};diff --git a/frontend/src/components/v2/Select/InstanceSelect.vue b/frontend/src/components/v2/Select/InstanceSelect.vueindex 5fdc3a6d50..c49d56d7c4 100644--- a/frontend/src/components/v2/Select/InstanceSelect.vue+++ b/frontend/src/components/v2/Select/InstanceSelect.vue@@ -1,43 +1,32 @@<template>- <ResourceSelect+ <RemoteResourceSelectorv-bind="$attrs"- :remote="true"- :loading="state.loading":value="instanceName"- :options="options":custom-label="renderLabel"- :virtual-scroll="true"- :fallback-option="false":consistent-menu-width="false"class="bb-instance-select"- @search="handleSearch"+ :additional-data="additionalData"+ :search="handleSearch"+ :get-option="getOption"@update:value="(val) => $emit('update:instance-name', val)"/></template>-<script lang="ts" setup>-import { useDebounceFn } from "@vueuse/core";-import { computed, h, reactive, watch } from "vue";+<script lang="tsx" setup>+import { computedAsync } from "@vueuse/core";+import { ChevronRightIcon } from "lucide-vue-next";import { useI18n } from "vue-i18n";-import { useInstanceV1Store } from "@/store";+import { EnvironmentV1Name, InstanceV1Name } from "@/components/v2";+import { useEnvironmentV1Store, useInstanceV1Store } from "@/store";import {- DEBOUNCE_SEARCH_DELAY,isValidInstanceName,UNKNOWN_INSTANCE_NAME,unknownInstance,} from "@/types";import { type Engine } from "@/types/proto-es/v1/common_pb";import type { Instance } from "@/types/proto-es/v1/instance_service_pb";-import { getDefaultPagination, supportedEngineV1List } from "@/utils";-import { InstanceV1EngineIcon } from "../Model/Instance";-import ResourceSelect from "./ResourceSelect.vue";--interface LocalState {- loading: boolean;- rawInstanceList: Instance[];- // Track if initial fetch has been done to avoid redundant API calls- initialized: boolean;-}+import { supportedEngineV1List } from "@/utils";+import RemoteResourceSelector from "./RemoteResourceSelector.vue";const props = withDefaults(defineProps<{@@ -45,164 +34,93 @@ const props = withDefaults(environmentName?: string;projectName?: string;allowedEngineList?: Engine[];- autoReset?: boolean;}>(),{instanceName: undefined,environmentName: undefined,allowedEngineList: () => supportedEngineV1List(),- autoReset: true,});-const emit = defineEmits<{+defineEmits<{(event: "update:instance-name", value: string | undefined): void;}>();const { t } = useI18n();const instanceStore = useInstanceV1Store();-const state = reactive<LocalState>({- loading: false,- rawInstanceList: [],- initialized: false,-});+const environmentStore = useEnvironmentV1Store();-const initSelectedInstance = async (instanceName: string) => {- if (isValidInstanceName(instanceName)) {- const instance = await instanceStore.getOrFetchInstanceByName(instanceName);- if (!state.rawInstanceList.find((ins) => ins.name === instance.name)) {- state.rawInstanceList.unshift(instance);- }+const additionalData = computedAsync(async () => {+ const data = [];+ if (props.instanceName === UNKNOWN_INSTANCE_NAME) {+ const dummyAll = {+ ...unknownInstance(),+ title: t("instance.all"),+ };+ data.push(dummyAll);}-};-const searchInstances = async (name: string) => {- const { instances } = await instanceStore.fetchInstanceList({- pageSize: getDefaultPagination(),+ if (isValidInstanceName(props.instanceName)) {+ const instance = await instanceStore.getOrFetchInstanceByName(+ props.instanceName+ );+ data.push(instance);+ }+ return data;+}, []);++const handleSearch = async (params: {+ search: string;+ pageToken: string;+ pageSize: number;+}) => {+ const { instances, nextPageToken } = await instanceStore.fetchInstanceList({+ pageToken: params.pageToken,+ pageSize: params.pageSize,filter: {engines: props.allowedEngineList,- query: name,+ query: params.search,environment: props.environmentName,project: props.projectName,},});- return instances;-};-const initInstanceList = async () => {- if (props.instanceName === UNKNOWN_INSTANCE_NAME) {- const dummyAll = {- ...unknownInstance(),- title: t("instance.all"),- };- if (!state.rawInstanceList.find((ins) => ins.name === dummyAll.name)) {- state.rawInstanceList.unshift(dummyAll);- }- } else if (props.instanceName) {- await initSelectedInstance(props.instanceName);- }+ return {+ nextPageToken,+ data: instances,+ };};-const handleSearch = useDebounceFn(async (search: string) => {- // Skip if no search term and already initialized (lazy loading optimization)- if (!search && state.initialized) {- return;- }-- state.loading = true;- try {- const instances = await searchInstances(search);- state.rawInstanceList = instances;- if (!search) {- state.initialized = true;- await initInstanceList();- }- } finally {- state.loading = false;- }-}, DEBOUNCE_SEARCH_DELAY);--// Only fetch selected instance on mount, not the entire list.-// The full list will be fetched lazily when dropdown is opened.-// Re-initialize when filter props change.-watch(- [- () => props.allowedEngineList,- () => props.environmentName,- () => props.projectName,- ],- () => {- state.initialized = false;- state.rawInstanceList = [];- initInstanceList();- },- {- immediate: true,- }-);+const renderLabel = (instance: Instance, keyword: string) => {+ const isUnknown = instance.name === UNKNOWN_INSTANCE_NAME;+ const environment = environmentStore.getEnvironmentByName(+ instance.environment ?? ""+ );-const renderLabel = (instance: Instance) => {- if (instance.name === UNKNOWN_INSTANCE_NAME) {- return t("instance.all");- }- const icon = h(InstanceV1EngineIcon, {- instance,- class: "bb-instance-select--engine-icon shrink-0",- });- const text = h("span", {}, instance.title);- return h(- "div",- {- class: "flex items-center gap-x-2",- },- [icon, text]+ return (+ <div class="flex items-center gap-x-1">+ {isUnknown ? null : (+ <EnvironmentV1Name+ environment={environment}+ plain={true}+ link={false}+ />+ )}+ {isUnknown ? null : <ChevronRightIcon class="w-3" />}+ <InstanceV1Name+ instance={instance}+ keyword={keyword}+ plain={true}+ link={false}+ />+ </div>);};-const options = computed(() => {- return state.rawInstanceList.map((instance) => {- return {- resource: instance,- value: instance.name,- label: instance.title,- };- });+const getOption = (instance: Instance) => ({+ value: instance.name,+ label: instance.title,});--// The instance list might change if environment changes, and the previous selected id-// might not exist in the new list. In such case, we need to reset the selection-// and emit the event.-const resetInvalidSelection = () => {- if (!props.autoReset) {- return;- }- if (state.loading) {- return;- }- // Don't reset selection before the full instance list has been fetched- if (!state.initialized) {- return;- }- if (- props.instanceName &&- !state.rawInstanceList.find((item) => item.name === props.instanceName)- ) {- emit("update:instance-name", undefined);- }-};--watch(- [- () => state.loading,- () => props.instanceName,- () => state.rawInstanceList,- () => props.projectName,- ],- resetInvalidSelection,- {- immediate: true,- }-);</script><style lang="postcss" scoped>diff --git a/frontend/src/components/v2/Select/ResourceSelect.vue b/frontend/src/components/v2/Select/LocalResourceSelector.vuesimilarity index 83%rename from frontend/src/components/v2/Select/ResourceSelect.vuerename to frontend/src/components/v2/Select/LocalResourceSelector.vueindex 04550b1a94..94119fabba 100644--- a/frontend/src/components/v2/Select/ResourceSelect.vue+++ b/frontend/src/components/v2/Select/LocalResourceSelector.vue@@ -3,21 +3,20 @@v-bind="$attrs":filterable="true":clearable="true"+ :remote="false":virtual-scroll="true":multiple="multiple":value="selected":disabled="disabled":options="options"- :fallback-option="fallbackOption"+ :fallback-option="false":filter="filterResource":render-label="renderLabel":render-tag="renderTag"- :placeholder="placeholder ?? $t('common.search-for-more')"+ :placeholder="placeholder":size="size":consistent-menu-width="consistentMenuWidth"class="bb-user-select"- @search="handleSearch"- @click="() => handleSearch('')"@update:value="handleValueUpdated"><template v-if="$slots.empty" #empty>@@ -27,7 +26,7 @@</template><script lang="tsx" setup generic="T extends { name: string }">-import type { SelectOption, SelectProps } from "naive-ui";+import type { SelectOption } from "naive-ui";import { NCheckbox, NSelect, NTag } from "naive-ui";import type { SelectBaseOption } from "naive-ui/lib/select/src/interface";import { computed, type VNodeChild } from "vue";@@ -49,18 +48,13 @@ const props = withDefaults(consistentMenuWidth?: boolean;size?: "tiny" | "small" | "medium" | "large";options: ResourceSelectOption[];- fallbackOption?: SelectProps["fallbackOption"];showResourceName?: boolean;resourceNameClass?: string;customLabel?: (resource: T) => VNodeChild;- filter?: (pattern: string, resource: T) => boolean;}>(),{customLabel: undefined,- // eslint-disable-next-line @typescript-eslint/no-unused-vars- filter: (pattern: string, resource: T) => false,size: "medium",- fallbackOption: false,disabled: false,multiple: false,showResourceName: true,@@ -72,7 +66,6 @@ const props = withDefaults(const emit = defineEmits<{(event: "update:value", value: string | undefined): void;(event: "update:values", value: string[]): void;- (event: "search", value: string): void;}>();const selected = computed(() => {@@ -83,10 +76,6 @@ const selected = computed(() => {}});-const handleSearch = (search: string) => {- emit("search", search.trim().toLowerCase());-};-const renderLabel = (option: SelectOption, selected: boolean) => {const { resource, label } = option as ResourceSelectOption;const node = (@@ -139,8 +128,7 @@ const filterResource = (pattern: string, option: SelectOption) => {const search = pattern.trim().toLowerCase();return (resource.name.toLowerCase().includes(search) ||- (label as string).toLowerCase().includes(search) ||- props.filter(search, resource)+ (label as string).toLowerCase().includes(search));};diff --git a/frontend/src/components/v2/Select/ProjectSelect.vue b/frontend/src/components/v2/Select/ProjectSelect.vueindex 6790eb123d..e5f4c0e4e4 100644--- a/frontend/src/components/v2/Select/ProjectSelect.vue+++ b/frontend/src/components/v2/Select/ProjectSelect.vue@@ -1,43 +1,41 @@<template>- <ResourceSelect+ <RemoteResourceSelectorv-bind="$attrs"- :remote="true"- :loading="state.loading":multiple="multiple":disabled="disabled":value="projectName":values="projectNames"- :options="options":custom-label="renderLabel"class="bb-project-select"- @search="handleSearch"+ :additional-data="additionalData"+ :search="handleSearch"+ :get-option="getOption"+ :filter="filterProject"@update:value="(val) => $emit('update:project-name', val)"@update:values="(val) => $emit('update:project-names', val)"><template v-if="$slots.empty" #empty><slot name="empty" /></template>- </ResourceSelect>+ </RemoteResourceSelector></template><script lang="tsx" setup>-import { useDebounceFn } from "@vueuse/core";+import { computedAsync } from "@vueuse/core";import { intersection } from "lodash-es";-import { computed, reactive, watch, watchEffect } from "vue";+import { computed } from "vue";import { useI18n } from "vue-i18n";import { ProjectNameCell } from "@/components/v2/Model/cells";import { usePermissionStore, useProjectV1Store } from "@/store";import {- DEBOUNCE_SEARCH_DELAY,DEFAULT_PROJECT_NAME,- defaultProject,isValidProjectName,UNKNOWN_PROJECT_NAME,unknownProject,} from "@/types";import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { getDefaultPagination, hasWorkspacePermissionV2 } from "@/utils";-import ResourceSelect from "./ResourceSelect.vue";+import { hasWorkspacePermissionV2 } from "@/utils";+import RemoteResourceSelector from "./RemoteResourceSelector.vue";const props = withDefaults(defineProps<{@@ -49,8 +47,7 @@ const props = withDefaults(includeDefaultProject?: boolean;multiple?: boolean;renderSuffix?: (project: string) => string;- filter?: (project: Project, index: number) => boolean;- defaultSelectFirst?: boolean;+ filter?: (project: Project) => boolean;}>(),{disabled: false,@@ -62,178 +59,105 @@ const props = withDefaults(multiple: false,filter: () => true,renderSuffix: () => "",- defaultSelectFirst: false,});-const emit = defineEmits<{+defineEmits<{(event: "update:project-name", name: string | undefined): void;(event: "update:project-names", names: string[]): void;}>();-interface LocalState {- loading: boolean;- rawProjectList: Project[];- // Track if initial fetch has been done to avoid redundant API calls- initialized: boolean;-}-const { t } = useI18n();const permissionStore = usePermissionStore();const projectStore = useProjectV1Store();-const state = reactive<LocalState>({- loading: false,- rawProjectList: [],- initialized: false,-});--const initSelectedProjects = async (projectNames: string[]) => {- for (const projectName of projectNames) {- if (isValidProjectName(projectName)) {- const project = await projectStore.getOrFetchProjectByName(projectName);- if (!state.rawProjectList.find((p) => p.name === project.name)) {- state.rawProjectList.unshift(project);- }- }- }-};--const initProjectList = async () => {- if (props.projectName) {- await initSelectedProjects([props.projectName]);- }- if (props.projectNames) {- await initSelectedProjects(props.projectNames);- }-- if (- props.projectName === DEFAULT_PROJECT_NAME ||- props.includeDefaultProject- ) {- if (- !state.rawProjectList.find((proj) => proj.name === DEFAULT_PROJECT_NAME)- ) {- state.rawProjectList.unshift({ ...defaultProject() });- }- }-- if (props.projectName === UNKNOWN_PROJECT_NAME || props.includeAll) {- const dummyAll = {- ...unknownProject(),- title: t("project.all"),- };- state.rawProjectList.unshift(dummyAll);- }-};const hasWorkspaceManageProjectPermission = computed(() =>hasWorkspacePermissionV2("bb.projects.list"));-const combinedProjectList = computed(() => {- let list = [...state.rawProjectList];-- // If the current user is not workspace admin/DBA, filter the project list by the given role list.+const filterProject = (project: Project) => {if (!hasWorkspaceManageProjectPermission.value &&props.allowedProjectRoleList.length > 0) {- list = list.filter((project) => {- const roles = permissionStore.currentRoleListInProjectV1(project);- return intersection(props.allowedProjectRoleList, roles).length > 0;- });+ const roles = permissionStore.currentRoleListInProjectV1(project);+ if (intersection(props.allowedProjectRoleList, roles).length == 0) {+ return false;+ }}if (props.filter) {- list = list.filter(props.filter);+ return props.filter(project);}- return list;-});+ return true;+};-const handleSearch = useDebounceFn(async (search: string) => {- // Skip if no search term and already initialized (lazy loading optimization)- if (!search && state.initialized) {- return;- }+const additionalData = computedAsync(async () => {+ const data = [];- state.loading = true;- try {- const { projects } = await projectStore.fetchProjectList({- filter: {- query: search,- excludeDefault: !props.includeDefaultProject,- },- pageSize: getDefaultPagination(),- });- state.rawProjectList = projects;- if (!search) {- state.initialized = true;- await initProjectList();- }- } finally {- state.loading = false;+ if (props.projectName === UNKNOWN_PROJECT_NAME || props.includeAll) {+ const dummyAll = {+ ...unknownProject(),+ title: t("project.all"),+ };+ data.unshift(dummyAll);}-}, DEBOUNCE_SEARCH_DELAY);-watch(- () => props.projectName,- async (newVal) => {- if (newVal) {- await initSelectedProjects([newVal]);- }- },- { immediate: true }-);+ let projectNames: string[] = [];+ if (props.projectName) {+ projectNames = [props.projectName];+ } else if (props.projectNames) {+ projectNames = props.projectNames;+ }-watch(- () => props.projectNames,- async (newVal) => {- if (newVal) {- await initSelectedProjects(newVal);+ for (const projectName of projectNames) {+ if (isValidProjectName(projectName)) {+ const project = await projectStore.getOrFetchProjectByName(projectName);+ data.push(project);}- },- { immediate: true }-);--const options = computed(- (): {- resource: Project;- value: string;- label: string;- }[] => {- return combinedProjectList.value.map((project) => {- return {- resource: project,- value: project.name,- label:- project.name === DEFAULT_PROJECT_NAME- ? t("common.unassigned")- : project.name === UNKNOWN_PROJECT_NAME- ? t("project.all")- : project.title,- };- });}-);-watchEffect(() => {- if (!props.defaultSelectFirst || props.projectName || props.multiple) {- return;- }- if (options.value.length === 0) {- return;- }+ return data;+}, []);++const handleSearch = async (params: {+ search: string;+ pageToken: string;+ pageSize: number;+}) => {+ const { projects, nextPageToken } = await projectStore.fetchProjectList({+ filter: {+ query: params.search,+ excludeDefault: !props.includeDefaultProject,+ },+ pageToken: params.pageToken,+ pageSize: params.pageSize,+ });++ return {+ nextPageToken,+ data: projects,+ };+};- emit("update:project-name", options.value[0].value);+const getOption = (project: Project) => ({+ value: project.name,+ label:+ project.name === DEFAULT_PROJECT_NAME+ ? t("common.unassigned")+ : project.name === UNKNOWN_PROJECT_NAME+ ? t("project.all")+ : project.title,});-const renderLabel = (project: Project) => {+const renderLabel = (project: Project, keyword: string) => {if (!project) return null;return (<ProjectNameCellproject={project}mode="ALL_SHORT"+ keyword={keyword}suffix={props.renderSuffix(project.name)}>{{diff --git a/frontend/src/components/v2/Select/RemoteResourceSelector.vue b/frontend/src/components/v2/Select/RemoteResourceSelector.vuenew file mode 100644index 0000000000..ba19469f1e--- /dev/null+++ b/frontend/src/components/v2/Select/RemoteResourceSelector.vue@@ -0,0 +1,257 @@+<template>+ <NSelect+ v-bind="$attrs"+ v-model:show="show"+ :loading="isLoadingNextPage"+ :filterable="true"+ :clearable="true"+ :remote="true"+ :virtual-scroll="true"+ :multiple="multiple"+ :value="selected"+ :disabled="disabled"+ :options="options"+ :fallback-option="false"+ :render-label="renderLabel"+ :render-tag="renderTag"+ :placeholder="placeholder ?? $t('common.search-for-more')"+ :size="size"+ :consistent-menu-width="consistentMenuWidth"+ :reset-menu-on-options-change="false"+ @search="handleSearch"+ @click="onSelectorOpen"+ @update:value="handleValueUpdated"+ >+ <template #empty>+ <slot name="empty">+ <BBSpin v-if="isLoadingNextPage" />+ </slot>+ </template>+ <template #action>+ <NButton+ v-if="pageToken"+ class="w-full!"+ quaternary+ :loading="isLoadingNextPage"+ @click="() => onNextPage(true)">+ {{ $t("common.load-more") }}+ </NButton>+ </template>+ </NSelect>+</template>++<script lang="tsx" setup generic="T extends { name: string }">+import { useDebounceFn } from "@vueuse/core";+import type { SelectOption } from "naive-ui";+import { NButton, NCheckbox, NSelect, NTag } from "naive-ui";+import type { SelectBaseOption } from "naive-ui/lib/select/src/interface";+import { computed, nextTick, type Ref, ref, type VNodeChild, watch } from "vue";+import { BBSpin } from "@/bbkit";+import EllipsisText from "@/components/EllipsisText.vue";+import { HighlightLabelText } from "@/components/v2";+import { DEBOUNCE_SEARCH_DELAY } from "@/types";+import { getDefaultPagination } from "@/utils";++type ResourceSelectOption = SelectOption & {+ resource: T;+ value: string;+ label: string;+};++const props = withDefaults(+ defineProps<{+ placeholder?: string;+ multiple?: boolean;+ disabled?: boolean;+ value?: string | undefined | null;+ values?: string[] | undefined | null;+ consistentMenuWidth?: boolean;+ size?: "tiny" | "small" | "medium" | "large";+ showResourceName?: boolean;+ resourceNameClass?: string;+ additionalData?: T[];+ customLabel?: (resource: T, keyword: string) => VNodeChild;+ filter?: (resource: T) => boolean;+ search?: (params: {+ search: string;+ pageToken: string;+ pageSize: number;+ }) => Promise<{ nextPageToken: string | undefined; data: T[] }>;+ getOption: (resource: T) => { value: string; label: string };+ }>(),+ {+ customLabel: undefined,+ size: "medium",+ fallbackOption: false,+ disabled: false,+ multiple: false,+ showResourceName: true,+ resourceNameClass: "",+ consistentMenuWidth: true,+ additionalData: () => [],+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ filter: (resource: T) => true,+ }+);++const emit = defineEmits<{+ (event: "update:value", value: string | undefined): void;+ (event: "update:values", value: string[]): void;+}>();++const isLoadingNextPage = ref(false);+const pageToken = ref<string | undefined>("");+const searchText = ref("");+const show = ref(false);+const rawList = ref([]) as Ref<T[]>;++const appendDataToRawList = (data: T[]) => {+ for (const item of data) {+ if (!rawList.value.find((raw) => raw.name === item.name)) {+ rawList.value.push(item);+ }+ }+};++watch(+ [+ () => props.additionalData,+ () => isLoadingNextPage.value,+ () => searchText.value,+ ],+ ([additionalData, isLoadingNextPage, searchText]) => {+ if (!isLoadingNextPage && !searchText) {+ appendDataToRawList(additionalData);+ }+ },+ { deep: true }+);++const onNextPage = async (openOptions: boolean) => {+ if (!props.search) {+ return;+ }+ isLoadingNextPage.value = true;+ const { nextPageToken, data } = await props.search({+ pageToken: pageToken.value ?? "",+ pageSize: getDefaultPagination(),+ search: searchText.value,+ });++ if (!pageToken.value) {+ rawList.value = data;+ } else {+ appendDataToRawList(data);+ }++ pageToken.value = nextPageToken;+ isLoadingNextPage.value = false;++ if (openOptions) {+ nextTick(() => (show.value = true));+ }+};++const selected = computed(() => {+ if (props.multiple) {+ return props.values || [];+ } else {+ return props.value;+ }+});++const onSelectorOpen = async () => {+ if (props.disabled) {+ return;+ }+ await handleSearch("");+};++const handleSearch = useDebounceFn(+ async (search: string, openOptions: boolean = true) => {+ searchText.value = search.trim().toLowerCase();+ pageToken.value = "";+ await onNextPage(openOptions);+ },+ DEBOUNCE_SEARCH_DELAY+);++const renderLabel = (option: SelectOption, selected: boolean) => {+ const { resource, label } = option as ResourceSelectOption;+ const node = (+ <div class="py-1">+ {props.customLabel ? (+ props.customLabel(resource, searchText.value)+ ) : (+ <HighlightLabelText keyword={searchText.value} text={label} />+ )}+ {props.showResourceName && (+ <div>+ <EllipsisText+ class={`opacity-60 textinfolabel ${props.resourceNameClass}`}+ >+ <HighlightLabelText+ keyword={searchText.value}+ text={resource.name}+ />+ </EllipsisText>+ </div>+ )}+ </div>+ );+ if (props.multiple) {+ return (+ <div class="flex items-center gap-x-2 py-2">+ <NCheckbox checked={selected} size="small" />+ {node}+ </div>+ );+ }++ return node;+};++const renderTag = ({+ option,+ handleClose,+}: {+ option: SelectBaseOption;+ handleClose: () => void;+}) => {+ const { resource, label } = option as ResourceSelectOption;+ const node = props.customLabel ? props.customLabel(resource, "") : label;+ if (props.multiple) {+ return (+ <NTag size={props.size} closable={!props.disabled} onClose={handleClose}>+ {node}+ </NTag>+ );+ }+ return node;+};++const handleValueUpdated = (value: string | string[] | undefined | null) => {+ if (props.multiple) {+ if (!value) {+ // normalize value+ value = [];+ }+ emit("update:values", value as string[]);+ } else {+ if (value === null) {+ // normalize value+ value = "";+ }+ emit("update:value", value as string);+ }+};++const options = computed((): ResourceSelectOption[] => {+ return rawList.value.filter(props.filter).map((data) => {+ return {+ resource: data,+ ...props.getOption(data),+ };+ });+});+</script>diff --git a/frontend/src/components/v2/Select/UserSelect.vue b/frontend/src/components/v2/Select/UserSelect.vueindex 2a94e0c477..ba82e48e58 100644--- a/frontend/src/components/v2/Select/UserSelect.vue+++ b/frontend/src/components/v2/Select/UserSelect.vue@@ -1,31 +1,29 @@<template>- <ResourceSelect+ <RemoteResourceSelectorv-bind="$attrs"- :remote="true"- :loading="state.loading":multiple="multiple":value="user":values="users"- :size="size"- :options="options"+ :additional-data="additionalData":custom-label="renderLabel"- :filter="filterByEmail":show-resource-name="false"- @search="handleSearch"+ :search="handleSearch"+ :get-option="getOption"+ :filter="filter"@update:value="(val) => $emit('update:user', val)"@update:values="(val) => $emit('update:users', val)"/></template><script lang="tsx" setup>-import { useDebounceFn } from "@vueuse/core";-import { computed, onMounted, reactive, watch } from "vue";+import { computedAsync } from "@vueuse/core";+import { HighlightLabelText } from "@/components/v2";import { UserNameCell } from "@/components/v2/Model/cells";import { type UserFilter, useUserStore } from "@/store";-import { allUsersUser, DEBOUNCE_SEARCH_DELAY, isValidUserName } from "@/types";+import { allUsersUser, isValidUserName } from "@/types";import { type User, UserType } from "@/types/proto-es/v1/user_service_pb";-import { ensureUserFullName, getDefaultPagination } from "@/utils";-import ResourceSelect from "./ResourceSelect.vue";+import { ensureUserFullName } from "@/utils";+import RemoteResourceSelector from "./RemoteResourceSelector.vue";const props = withDefaults(defineProps<{@@ -38,9 +36,7 @@ const props = withDefaults(includeSystemBot?: boolean;includeServiceAccount?: boolean;includeWorkloadIdentity?: boolean;- autoReset?: boolean;- filter?: (user: User, index: number) => boolean;- size?: "tiny" | "small" | "medium" | "large";+ filter?: (user: User) => boolean;}>(),{multiple: false,@@ -51,30 +47,15 @@ const props = withDefaults(includeSystemBot: false,includeServiceAccount: false,includeWorkloadIdentity: false,- autoReset: true,- filter: (_1: User, _2: number) => true,- size: "medium",});-const emit = defineEmits<{+defineEmits<{(event: "update:user", value: string | undefined): void;(event: "update:users", value: string[]): void;}>();-interface LocalState {- loading: boolean;- rawUserList: User[];- // Track if initial fetch has been done to avoid redundant API calls- initialized: boolean;-}-const userStore = useUserStore();-const state = reactive<LocalState>({- loading: false,- rawUserList: [],- initialized: false,-});const getFilter = (search: string): UserFilter => {const filter = [];@@ -99,77 +80,62 @@ const getFilter = (search: string): UserFilter => {};};-const initSelectedUsers = async (userEmails: string[]) => {- for (const email of userEmails) {+const additionalData = computedAsync(async () => {+ const data = [];+ if (props.includeAllUsers) {+ data.unshift(allUsersUser());+ }++ let userNames: string[] = [];+ if (props.user) {+ userNames = [props.user];+ } else if (props.users) {+ userNames = props.users;+ }++ for (const email of userNames) {if (!email) continue;const userName = ensureUserFullName(email);if (isValidUserName(userName)) {const user = await userStore.getOrFetchUserByIdentifier(userName);- if (!state.rawUserList.find((u) => u.name === user.name)) {- state.rawUserList.unshift(user);- }+ data.push(user);}}-};-const searchUsers = async (search: string) => {- const { users } = await userStore.fetchUserList({- filter: getFilter(search),- pageSize: getDefaultPagination(),+ return data;+}, []);++const handleSearch = async (params: {+ search: string;+ pageToken: string;+ pageSize: number;+}) => {+ const { users, nextPageToken } = await userStore.fetchUserList({+ filter: getFilter(params.search),+ pageToken: params.pageToken,+ pageSize: params.pageSize,});- return users.filter(props.filter);+ return {+ nextPageToken,+ data: users,+ };};-const handleSearch = useDebounceFn(async (search: string) => {- // Skip if no search term and already initialized (lazy loading optimization)- if (!search && state.initialized) {- return;- }-- state.loading = true;- try {- const users = await searchUsers(search);- state.rawUserList = users;- if (!search) {- state.initialized = true;- if (props.includeAllUsers) {- state.rawUserList.unshift(allUsersUser());- }- if (props.user) {- await initSelectedUsers([props.user]);- }- if (props.users) {- await initSelectedUsers(props.users);- }- }- } finally {- state.loading = false;- }-}, DEBOUNCE_SEARCH_DELAY);--// Only fetch the selected user(s) on mount, not the entire user list.-// The full list will be fetched lazily when dropdown is opened.-onMounted(async () => {- let users: string[] = [];- if (props.user) {- users = [props.user];- } else if (props.users) {- users = props.users;- }- await initSelectedUsers(users);-});--const renderLabel = (user: User) => {+const renderLabel = (user: User, keyword: string) => {return (<UserNameCelluser={user}allowEdit={false}+ link={false}size="small"+ keyword={keyword}onClickUser={() => {}}>{{suffix: () => (- <span class="textinfolabel truncate">{`(${user.email})`}</span>+ <span class="textinfolabel truncate">+ (<HighlightLabelText keyword={keyword} text={user.email} />)+ </span>),footer: () => <div />,}}@@ -177,47 +143,8 @@ const renderLabel = (user: User) => {);};-const options = computed(() => {- return state.rawUserList.map((user) => {- return {- resource: user,- value: user.email,- label: user.title,- };- });+const getOption = (user: User) => ({+ value: user.email,+ label: user.title,});--const filterByEmail = (pattern: string, user: User) => {- return user.email.includes(pattern);-};--// The user list might change if props change, and the previous selected id-// might not exist in the new list. In such case, we need to invalidate the selection-// and emit the event.-const resetInvalidSelection = () => {- if (!props.autoReset || props.multiple) {- return;- }- if (state.loading) {- return;- }- // Don't reset selection before the full user list has been fetched- if (!state.initialized) {- return;- }- if (- props.user &&- !state.rawUserList.find((user) => user.email === props.user)- ) {- emit("update:user", undefined);- }-};--watch(- [() => state.loading, () => props.user, state.rawUserList],- resetInvalidSelection,- {- immediate: true,- }-);</script>diff --git a/frontend/src/store/modules/v1/group.ts b/frontend/src/store/modules/v1/group.tsindex 55cfe49e0d..d910a53668 100644--- a/frontend/src/store/modules/v1/group.ts+++ b/frontend/src/store/modules/v1/group.ts@@ -41,7 +41,7 @@ export const extractGroupEmail = (emailResource: string) => {return matches?.[1] ?? emailResource;};-const ensureGroupIdentifier = (id: string) => {+export const ensureGroupIdentifier = (id: string) => {const email = extractGroupEmail(id);return `${groupNamePrefix}${email}`;};diff --git a/frontend/src/views/project/ProjectMaskingExemption.vue b/frontend/src/views/project/ProjectMaskingExemption.vueindex 8609f8c0bd..b105fbf9d0 100644--- a/frontend/src/views/project/ProjectMaskingExemption.vue+++ b/frontend/src/views/project/ProjectMaskingExemption.vue@@ -3,14 +3,13 @@<divclass="flex flex-col lg:flex-row gap-y-4 justify-between items-end lg:items-center gap-x-2">- <NInputGroup style="width: auto">- <DatabaseSelect- style="max-width: max-content"- :include-all="false"- :project-name="project.name"- v-model:database-name="state.selectedDatabaseName"- />- </NInputGroup>+ <DatabaseSelect+ style="max-width: max-content"+ :placeholder="$t('database.select')"+ :project-name="project.name"+ :show-instance="false"+ v-model:database-name="state.selectedDatabaseName"+ /><div class="flex-1 flex flex-row items-center justify-end gap-x-2"><SearchBox@@ -63,7 +62,7 @@<script lang="tsx" setup>import { ShieldCheckIcon } from "lucide-vue-next";-import { NButton, NInputGroup } from "naive-ui";+import { NButton } from "naive-ui";import { computed, reactive } from "vue";import { useRouter } from "vue-router";import { FeatureBadge, FeatureModal } from "@/components/FeatureGuard";