Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(frontend): migrate roles page to React (#19774)
Danny Xub86b0fee6a1e
diff --git a/frontend/src/components/Role/RoleSetting.vue b/frontend/src/components/Role/RoleSetting.vuedeleted file mode 100644index a85aa57704..0000000000--- a/frontend/src/components/Role/RoleSetting.vue+++ /dev/null@@ -1,156 +0,0 @@-<template>- <div class="flex flex-col gap-y-4">- <div class="textinfolabel">- {{ $t("role.setting.description") }}- <LearnMoreLink- url="https://docs.bytebase.com/administration/roles?source=console"- />- </div>- <div class="w-full flex flex-row justify-end items-center">- <PermissionGuardWrapper- v-slot="slotProps"- :permissions="['bb.roles.create']"- >- <NButton- type="primary"- class="capitalize"- :disabled="slotProps.disabled"- @click="addRole"- >- <template #icon>- <PlusIcon class="h-4 w-4" />- <FeatureBadge- :feature="PlanFeature.FEATURE_CUSTOM_ROLES"- class="mr-1 text-white"- />- </template>- {{ $t("role.setting.add") }}- </NButton>- </PermissionGuardWrapper>- </div>- <RoleDataTable- :role-list="filteredRoleList"- :show-placeholder="state.ready"- @select-role="selectRole($event, 'EDIT')"- />-- <div- v-if="!state.ready"- class="relative flex flex-col h-32 items-center justify-center"- >- <BBSpin />- </div>-- <RolePanel- :role="state.detail.role"- :mode="state.detail.mode"- @close="state.detail.role = undefined"- />-- <FeatureModal- :feature="PlanFeature.FEATURE_CUSTOM_ROLES"- :open="showFeatureModal"- @cancel="showFeatureModal = false"- />- </div>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { sortBy } from "lodash-es";-import { PlusIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, onMounted, reactive, ref } from "vue";-import { useRoute } from "vue-router";-import { BBSpin } from "@/bbkit";-import { FeatureBadge, FeatureModal } from "@/components/FeatureGuard";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import { featureToRef, roleNamePrefix, useRoleStore } from "@/store";-import { BASIC_WORKSPACE_PERMISSIONS, PRESET_ROLES } from "@/types";-import type { Role } from "@/types/proto-es/v1/role_service_pb";-import { RoleSchema } from "@/types/proto-es/v1/role_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import { RoleDataTable, RolePanel } from "./Setting/components";-import { provideCustomRoleSettingContext } from "./Setting/context";--type LocalState = {- ready: boolean;- detail: {- role: Role | undefined;- mode: "ADD" | "EDIT";- };- filter: {- keyword: string;- };-};--const route = useRoute();-const roleStore = useRoleStore();-const state = reactive<LocalState>({- ready: false,- detail: {- role: undefined,- mode: "ADD",- },- filter: {- keyword: "",- },-});--const hasCustomRoleFeature = featureToRef(PlanFeature.FEATURE_CUSTOM_ROLES);-const showFeatureModal = ref(false);--const filteredRoleList = computed(() => {- const sortedRoles = sortBy(roleStore.roleList, (role) => {- return PRESET_ROLES.includes(role.name)- ? PRESET_ROLES.indexOf(role.name)- : roleStore.roleList.length;- });- const keyword = state.filter.keyword.trim().toLowerCase();- if (!keyword) return sortedRoles;- return sortedRoles.filter((role) => {- return (- role.name.toLowerCase().includes(keyword) ||- role.description.toLowerCase().includes(keyword)- );- });-});--const addRole = () => {- selectRole(- create(RoleSchema, {- permissions: [...BASIC_WORKSPACE_PERMISSIONS],- }),- "ADD"- );-};--const selectRole = (role: Role | undefined, mode?: "ADD" | "EDIT") => {- state.detail.role = role;- if (mode) {- state.detail.mode = mode;- }-};--onMounted(async () => {- try {- await roleStore.fetchRoleList();- } finally {- state.ready = true;- }-- const name = route.query.role as string;- if (name?.startsWith(roleNamePrefix)) {- const role = roleStore.getRoleByName(name);- if (role) {- selectRole(role, "EDIT");- }- }-});--provideCustomRoleSettingContext({- hasCustomRoleFeature,- showFeatureModal,-});-</script>diff --git a/frontend/src/components/Role/Setting/components/ImportPermissionFromRoleModal.vue b/frontend/src/components/Role/Setting/components/ImportPermissionFromRoleModal.vuedeleted file mode 100644index 711d32c346..0000000000--- a/frontend/src/components/Role/Setting/components/ImportPermissionFromRoleModal.vue+++ /dev/null@@ -1,84 +0,0 @@-<template>- <BBModal :title="$t('role.import-from-role')" @close="$emit('cancel')">- <div class="w-96 mb-2 flex flex-col gap-y-2">- <div>- <p class="textlabel mb-1">{{ $t("role.select-role") }}</p>- <RoleSelect v-model:value="state.selectedRole" :multiple="false" />- </div>- <template v-if="selectedRole">- <p class="textinfolabel">- {{ displayRoleDescription(selectedRole.name) }}- </p>- <div>- <p class="textlabel mb-1">- {{ $t("common.permissions") }} ({{- filterDisplayPermissions.length- }})- </p>- <div class="max-h-[10em] overflow-auto border rounded-sm p-2">- <p- v-for="permission in filterDisplayPermissions"- :key="permission"- class="text-sm leading-5"- >- {{ permission }}- </p>- </div>- </div>- </template>- <div class="mt-4! w-full flex flex-row justify-end items-center gap-2">- <NButton @click.prevent="$emit('cancel')">- {{ $t("common.cancel") }}- </NButton>- <NButton- :disabled="!allowConfirm"- type="primary"- @click.prevent="handleConfirm"- >- {{ $t("common.confirm") }}- </NButton>- </div>- </div>- </BBModal>-</template>--<script lang="ts" setup>-import { NButton } from "naive-ui";-import { computed, reactive } from "vue";-import { BBModal } from "@/bbkit";-import { RoleSelect } from "@/components/v2/Select";-import { useRoleStore } from "@/store";-import { displayRoleDescription } from "@/utils";--interface LocalState {- selectedRole?: string;-}--const emit = defineEmits<{- (event: "cancel"): void;- (event: "import", permissions: string[]): void;-}>();--const roleStore = useRoleStore();-const state = reactive<LocalState>({});--const selectedRole = computed(() => {- return roleStore.roleList.find((role) => role.name === state.selectedRole);-});--const filterDisplayPermissions = computed(() => {- return selectedRole.value?.permissions || [];-});--const allowConfirm = computed(() => {- return !!selectedRole.value;-});--const handleConfirm = () => {- if (!allowConfirm.value) {- return;- }-- emit("import", selectedRole.value?.permissions || []);-};-</script>diff --git a/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleOperationsCell.vue b/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleOperationsCell.vuedeleted file mode 100644index 9cd59f1daf..0000000000--- a/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleOperationsCell.vue+++ /dev/null@@ -1,95 +0,0 @@-<template>- <div v-if="isCustomRole(role.name)" class="w-full flex justify-end gap-x-2">- <MiniActionButton- v-if="allowDelete"- type="error"- @click="handleDeleteRole"- >- <Trash2Icon />- </MiniActionButton>- <MiniActionButton @click="$emit('edit', role)">- <PencilIcon />- </MiniActionButton>- </div>- <ResourceOccupiedModal- ref="resourceOccupiedModalRef"- :target="role.name"- :resources="resourceOccupied"- :show-positive-button="resourceOccupied.length === 0"- @on-submit="onRoleRemove"- @on-close="resetState"- />-</template>--<script lang="tsx" setup>-import { Code } from "@connectrpc/connect";-import { PencilIcon, Trash2Icon } from "lucide-vue-next";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { MiniActionButton } from "@/components/v2";-import ResourceOccupiedModal from "@/components/v2/ResourceOccupiedModal/ResourceOccupiedModal.vue";-import { pushNotification, useRoleStore, useWorkspaceV1Store } from "@/store";-import type { Role } from "@/types/proto-es/v1/role_service_pb";-import { hasWorkspacePermissionV2, isCustomRole } from "@/utils";-import { extractGrpcErrorMessage, getErrorCode } from "@/utils/connect";-import { useCustomRoleSettingContext } from "../../../context";--const props = defineProps<{- role: Role;-}>();--defineEmits<{- (event: "edit", role: Role): void;-}>();--const { hasCustomRoleFeature, showFeatureModal } =- useCustomRoleSettingContext();-const workspaceStore = useWorkspaceV1Store();-const { t } = useI18n();-const resourceOccupiedModalRef =- ref<InstanceType<typeof ResourceOccupiedModal>>();--const allowDelete = computed(() => hasWorkspacePermissionV2("bb.roles.delete"));--const usersWithRole = computed(() => {- return [- ...(workspaceStore.roleMapToUsers.get(props.role.name) ?? new Set([])),- ];-});--const resourceOccupied = ref<string[]>([...usersWithRole.value]);--const resetState = () => {- resourceOccupied.value = [...usersWithRole.value];-};--const handleDeleteRole = () => {- if (!hasCustomRoleFeature.value) {- showFeatureModal.value = true;- return;- }-- resourceOccupiedModalRef.value?.open();-};--const onRoleRemove = async () => {- try {- await useRoleStore().deleteRole(props.role);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.deleted"),- });- } catch (error) {- if (getErrorCode(error) === Code.FailedPrecondition) {- const message = extractGrpcErrorMessage(error);- const resources =- message.split("used by resources: ")[1]?.split(",") ?? [];- if (resources.length > 0) {- resourceOccupied.value = [...resources];- handleDeleteRole();- }- }- }-};-</script>diff --git a/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleTitleCell.vue b/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleTitleCell.vuedeleted file mode 100644index 12d07e8015..0000000000--- a/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleTitleCell.vue+++ /dev/null@@ -1,16 +0,0 @@-<template>- <div>- {{ displayRoleTitle(role.name) }}- <SystemLabel v-if="!isCustomRole(role.name)" class="ml-1" />- </div>-</template>--<script lang="ts" setup>-import SystemLabel from "@/components/SystemLabel.vue";-import type { Role } from "@/types/proto-es/v1/role_service_pb";-import { displayRoleTitle, isCustomRole } from "@/utils";--defineProps<{- role: Role;-}>();-</script>diff --git a/frontend/src/components/Role/Setting/components/RoleDataTable/index.vue b/frontend/src/components/Role/Setting/components/RoleDataTable/index.vuedeleted file mode 100644index 2b382362b4..0000000000--- a/frontend/src/components/Role/Setting/components/RoleDataTable/index.vue+++ /dev/null@@ -1,67 +0,0 @@-<template>- <NDataTable- key="custom-role-table"- :columns="columns"- :data="roleList"- :striped="true"- :row-key="(role: Role) => role.name"- :bordered="true"- />-</template>--<script lang="tsx" setup>-import type { DataTableColumn } from "naive-ui";-import { NDataTable } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import type { Role } from "@/types/proto-es/v1/role_service_pb";-import { displayRoleDescription } from "@/utils";-import RoleOperationsCell from "./cells/RoleOperationsCell.vue";-import RoleTitleCell from "./cells/RoleTitleCell.vue";--defineProps<{- roleList: Role[];-}>();--const emit = defineEmits<{- (event: "select-role", role: Role): void;-}>();--const { t } = useI18n();--const columns = computed(() => {- return [- {- key: "title",- title: t("role.title"),- width: "16rem",- render: (role: Role) => {- return <RoleTitleCell role={role} />;- },- },- {- key: "description",- title: t("common.description"),- ellipsis: {- tooltip: true,- },- render: (role) => {- return displayRoleDescription(role.name);- },- },- {- key: "operations",- title: "",- width: "10rem",- render: (role: Role) => {- return (- <RoleOperationsCell- role={role}- onEdit={() => emit("select-role", role)}- />- );- },- },- ] as DataTableColumn<Role>[];-});-</script>diff --git a/frontend/src/components/Role/Setting/components/RolePanel.vue b/frontend/src/components/Role/Setting/components/RolePanel.vuedeleted file mode 100644index cd56a048dc..0000000000--- a/frontend/src/components/Role/Setting/components/RolePanel.vue+++ /dev/null@@ -1,310 +0,0 @@-<template>- <Drawer- :show="role !== undefined"- width="auto"- @update:show="(show: boolean) => !show && $emit('close')"- >- <DrawerContent- :title="mode === 'ADD' ? $t('role.setting.add') : $t('role.setting.edit')"- :closable="true"- class="w-[44rem] max-w-[100vw] relative"- >- <div class="flex flex-col gap-y-4">- <div class="flex flex-col gap-y-2">- <div class="textlabel">- {{ $t("role.title") }}- <span class="ml-0.5 text-error">*</span>- </div>- <div>- <NInput- v-model:value="state.role.title"- :placeholder="$t('role.setting.title-placeholder')"- :status="state.role.title?.length === 0 ? 'error' : undefined"- :maxlength="200"- :disabled="isBuiltinRole"- />- </div>- <div class="-mt-2">- <ResourceIdField- ref="resourceIdField"- v-model:value="resourceId"- resource-type="role"- :resource-title="state.role.title"- :suffix="true"- :readonly="mode === 'EDIT'"- :validate="validateResourceId"- class="flex flex-col mt-1.5"- editing-class="mt-4"- />- </div>- </div>-- <div class="flex flex-col gap-y-2">- <div class="textlabel">{{ $t("common.description") }}</div>- <div>- <NInput- v-model:value="state.role.description"- type="textarea"- :autosize="{ minRows: 2, maxRows: 4 }"- :placeholder="$t('role.setting.description-placeholder')"- :maxlength="1000"- :disabled="isBuiltinRole"- />- </div>- </div>-- <div class="flex flex-col gap-y-2">- <div class="w-full flex flex-row justify-between items-center">- <div class="textlabel">- {{ $t("common.permissions") }}- <span class="ml-0.5 text-error">*</span>- </div>- <NButton- v-if="!isBuiltinRole"- size="small"- @click="state.showImportPermissionFromRoleModal = true"- >- <PlusIcon class="w-4 h-auto mr-1" />- <span>{{ $t("role.import-from-role") }}</span>- </NButton>- </div>- <RequiredBasicPermissionAlert- v-if="missedBasicPermission.length > 0 && !isBuiltinRole"- :permissions="missedBasicPermission"- :title="$t('common.missing-required-permission')"- >- <template #action>- <div class="mt-2">- <NButton- type="primary"- size="small"- @click="addPermissions"- >- {{ $t("common.add-permissions") }}- </NButton>- </div>- </template>- </RequiredBasicPermissionAlert>- <NTransfer- v-model:value="state.role.permissions"- class="h-[32rem]!"- source-filterable- source-filter-placeholder="Search"- :options="permissionOptions"- :disabled="isBuiltinRole"- />- </div>- </div>-- <div- v-if="state.loading"- class="absolute inset-0 z-10 bg-white/50 flex flex-col items-center justify-center"- >- <BBSpin />- </div>-- <template #footer>- <div v-if="!isBuiltinRole" class="flex items-center justify-end gap-x-2">- <NButton @click="$emit('close')">{{ $t("common.cancel") }}</NButton>- <PermissionGuardWrapper- v-slot="slotProps"- :permissions="[- mode === 'ADD' ? 'bb.roles.create' : 'bb.roles.update'- ]"- >- <NButton- type="primary"- :disabled="!allowSave || slotProps.disabled"- @click="handleSave"- >- <FeatureBadge- :feature="PlanFeature.FEATURE_CUSTOM_ROLES"- class="mr-1 text-white"- />- {{ mode === "ADD" ? $t("common.add") : $t("common.update") }}- </NButton>- </PermissionGuardWrapper>- </div>- </template>- </DrawerContent>- </Drawer>-- <ImportPermissionFromRoleModal- v-if="state.showImportPermissionFromRoleModal"- @cancel="state.showImportPermissionFromRoleModal = false"- @import="handleImportPermissions"- />-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { Code, ConnectError } from "@connectrpc/connect";-import { cloneDeep, uniq } from "lodash-es";-import { PlusIcon } from "lucide-vue-next";-import { NButton, NInput, NTransfer } from "naive-ui";-import { computed, nextTick, reactive, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { BBSpin } from "@/bbkit";-import { FeatureBadge } from "@/components/FeatureGuard";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import { Drawer, DrawerContent, ResourceIdField } from "@/components/v2";-import { pushNotification, useRoleStore } from "@/store";-import { roleNamePrefix } from "@/store/modules/v1/common";-import type { ValidatedMessage } from "@/types";-import { BASIC_WORKSPACE_PERMISSIONS, PERMISSIONS } from "@/types";-import type { Role } from "@/types/proto-es/v1/role_service_pb";-import { RoleSchema } from "@/types/proto-es/v1/role_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import { extractRoleResourceName, isCustomRole } from "@/utils";-import { useCustomRoleSettingContext } from "../context";-import ImportPermissionFromRoleModal from "./ImportPermissionFromRoleModal.vue";-import RequiredBasicPermissionAlert from "./RequiredBasicPermissionAlert.vue";--type LocalState = {- role: Role;- dirty: boolean;- loading: boolean;- showImportPermissionFromRoleModal: boolean;-};--const props = defineProps<{- role: Role | undefined;- mode: "ADD" | "EDIT";-}>();--const emit = defineEmits<{- (event: "close"): void;-}>();--const { t } = useI18n();-const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();-const roleStore = useRoleStore();-const { hasCustomRoleFeature, showFeatureModal } =- useCustomRoleSettingContext();-const state = reactive<LocalState>({- role: create(RoleSchema, {- permissions: [...BASIC_WORKSPACE_PERMISSIONS],- }),- dirty: false,- loading: false,- showImportPermissionFromRoleModal: false,-});--const missedBasicPermission = computed(() => {- return BASIC_WORKSPACE_PERMISSIONS.filter(- (p) => !state.role.permissions.includes(p)- );-});--const addPermissions = () => {- state.role.permissions.push(...missedBasicPermission.value);-};--const resourceId = computed({- get() {- return extractRoleResourceName(state.role.name);- },- set(value) {- state.role.name = `${roleNamePrefix}${value}`;- },-});--const permissionOptions = computed(() => {- return PERMISSIONS.sort().map((p) => ({- label: p,- value: p,- }));-});--const isBuiltinRole = computed(() => !isCustomRole(state.role.name));--const allowSave = computed(() => {- if (!state.dirty) return false;- if (state.role.title?.length === 0) return false;- if (resourceIdField.value) {- if (!resourceIdField.value.resourceId) return false;- if (!resourceIdField.value.isValidated) return false;- }- if (state.role.permissions.length === 0) {- return false;- }- return true;-});--const handleImportPermissions = (permissions: string[]) => {- state.role.permissions = uniq([...state.role.permissions, ...permissions]);- state.showImportPermissionFromRoleModal = false;-};--const handleSave = async () => {- if (!hasCustomRoleFeature.value) {- showFeatureModal.value = true;-- // Getting crazy to adjust the z-indexes of the modal and the panel drawer- // so just close the panel drawer here.- emit("close");- return;- }-- state.loading = true;- try {- state.role = await roleStore.upsertRole(state.role);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: props.mode === "ADD" ? t("common.added") : t("common.updated"),- });- emit("close");- } catch (error) {- if (error instanceof ConnectError && error.code === Code.AlreadyExists) {- resourceIdField.value?.addValidationError(error.message);- } else {- throw error;- }- } finally {- state.loading = false;- }-};--const validateResourceId = async (- name: string-): Promise<ValidatedMessage[]> => {- if (roleStore.roleList.find((r) => r.name === `${roleNamePrefix}${name}`)) {- return [- {- type: "error",- message: t("resource-id.validation.duplicated", {- resource: t("role.self"),- }),- },- ];- }- return [];-};--watch(- () => props.role,- () => {- if (props.role) {- state.role = cloneDeep(props.role);- if (!state.role.title) {- state.role.title = extractRoleResourceName(state.role.name);- }- }- nextTick(() => {- state.dirty = false;- });- },- {- immediate: true,- }-);--watch(- () => [state.role],- () => {- state.dirty = true;- },- { deep: true }-);-</script>diff --git a/frontend/src/components/Role/Setting/components/index.ts b/frontend/src/components/Role/Setting/components/index.tsdeleted file mode 100644index ee41daede7..0000000000--- a/frontend/src/components/Role/Setting/components/index.ts+++ /dev/null@@ -1,4 +0,0 @@-import RoleDataTable from "./RoleDataTable/index.vue";-import RolePanel from "./RolePanel.vue";--export { RoleDataTable, RolePanel };diff --git a/frontend/src/components/Role/Setting/context.ts b/frontend/src/components/Role/Setting/context.tsdeleted file mode 100644index baf23df4b7..0000000000--- a/frontend/src/components/Role/Setting/context.ts+++ /dev/null@@ -1,20 +0,0 @@-import { type InjectionKey, inject, provide, type Ref } from "vue";--export type CustomRoleSettingContext = {- hasCustomRoleFeature: Ref<boolean>;- showFeatureModal: Ref<boolean>;-};--const KEY = Symbol(- "bb.settings.custom-role"-) as InjectionKey<CustomRoleSettingContext>;--export const provideCustomRoleSettingContext = (- context: CustomRoleSettingContext-) => {- provide(KEY, context);-};--export const useCustomRoleSettingContext = () => {- return inject(KEY)!;-};diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex f1d8f56c98..90130910cc 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -186,6 +186,9 @@"revoke": "Revoke","cannot-undo-this-action": "You cannot undo this action","select": "Select",+ "select-all": "Select all",+ "total-n-items": "Total {n} items",+ "n-items-selected": "{n} items selected","optional": "Optional","reason": "Reason","date": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 59e10545b1..6bc4eeae3c 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -186,6 +186,9 @@"revoke": "Revocar","cannot-undo-this-action": "No se puede deshacer esta acción","select": "Seleccionar",+ "select-all": "Seleccionar todo",+ "total-n-items": "Total {n} elementos",+ "n-items-selected": "{n} elementos seleccionados","optional": "Opcional","reason": "Razón","date": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 47ea4177f5..bd75acd558 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -186,6 +186,9 @@"revoke": "キャンセル","cannot-undo-this-action": "この操作は元に戻せません","select": "選ぶ",+ "select-all": "すべて選択",+ "total-n-items": "合計 {n} 件",+ "n-items-selected": "{n} 件選択済み","optional": "オプション","reason": "理由","date": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 15313ae1a5..d9b473961d 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -186,6 +186,9 @@"revoke": "Thu hồi","cannot-undo-this-action": "Bạn không thể hoàn tác hành động này.","select": "Chọn",+ "select-all": "Chọn tất cả",+ "total-n-items": "Tổng {n} mục",+ "n-items-selected": "Đã chọn {n} mục","optional": "Tùy chọn","reason": "Lý do","date": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 947d075ec3..b1365c9646 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -186,6 +186,9 @@"revoke": "撤销","cannot-undo-this-action": "这个操作无法撤销","select": "选择",+ "select-all": "全选",+ "total-n-items": "共 {n} 项",+ "n-items-selected": "已选 {n} 项","optional": "可选","reason": "理由","date": {diff --git a/frontend/src/react/components/ResourceIdField.tsx b/frontend/src/react/components/ResourceIdField.tsxnew file mode 100644index 0000000000..64d72f0af1--- /dev/null+++ b/frontend/src/react/components/ResourceIdField.tsx@@ -0,0 +1,259 @@+import {+ forwardRef,+ useCallback,+ useEffect,+ useImperativeHandle,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import { Input } from "@/react/components/ui/input";+import type { ValidatedMessage } from "@/types";+import { randomString } from "@/utils";++const VALID_CHARS = "abcdefghijklmnopqrstuvwxyz1234567890-";+const RESOURCE_ID_PATTERN = /^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/;++type ResourceType =+ | "environment"+ | "instance"+ | "project"+ | "idp"+ | "role"+ | "database-group"+ | "review-config";++export interface ResourceIdFieldRef {+ resourceId: string;+ isValidated: boolean;+ addValidationError: (message: string) => void;+}++interface ResourceIdFieldProps {+ value: string;+ resourceType: ResourceType;+ resourceName: string;+ resourceTitle?: string;+ suffix?: boolean;+ readonly?: boolean;+ validate?: (resourceId: string) => Promise<ValidatedMessage[]>;+ onChange?: (value: string) => void;+ onValidationChange?: (isValid: boolean) => void;+}++function randomCharacter(ch?: string): string {+ const letters = "abcdefghijklmnopqrstuvwxyz";+ const index = ch+ ? ch.charCodeAt(0) % letters.length+ : Math.floor(Math.random() * letters.length);+ return letters.charAt(index);+}++function escapeTitle(str: string): string {+ return str+ .toLowerCase()+ .split("")+ .map((char) => {+ if (char === " ") return "-";+ if (char.match(/\s/)) return "";+ if (VALID_CHARS.includes(char)) return char;+ return randomCharacter(char);+ })+ .join("");+}++export const ResourceIdField = forwardRef<+ ResourceIdFieldRef,+ ResourceIdFieldProps+>(function ResourceIdField(+ {+ value,+ resourceType: _resourceType, // reserved for future per-type behavior+ resourceName,+ resourceTitle,+ suffix = false,+ readonly = false,+ validate,+ onChange,+ onValidationChange,+ },+ ref+) {+ const { t } = useTranslation();+ const [manualEdit, setManualEdit] = useState(false);+ const [messages, setMessages] = useState<ValidatedMessage[]>([]);+ const randomSuffixRef = useRef(randomString(4).toLowerCase());+ const initializedRef = useRef(false);+ // Use refs for callbacks to avoid re-triggering the auto-generate effect+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;+ const validateRef = useRef(validate);+ validateRef.current = validate;+ const onValidationChangeRef = useRef(onValidationChange);+ onValidationChangeRef.current = onValidationChange;++ const updateMessages = useCallback((msgs: ValidatedMessage[]) => {+ setMessages(msgs);+ onValidationChangeRef.current?.(msgs.length === 0);+ }, []);++ const validateId = useCallback(+ async (id: string): Promise<ValidatedMessage[]> => {+ const result: ValidatedMessage[] = [];++ if (id === "") {+ result.push({+ type: "error",+ message: t("resource-id.validation.empty", {+ resource: resourceName,+ }),+ });+ } else if (id.length > 64) {+ result.push({+ type: "error",+ message: t("resource-id.validation.overflow", {+ resource: resourceName,+ }),+ });+ } else if (!RESOURCE_ID_PATTERN.test(id)) {+ result.push({+ type: "error",+ message: t("resource-id.validation.pattern", {+ resource: resourceName,+ }),+ });+ }++ if (validateRef.current && result.length === 0) {+ const custom = await validateRef.current(id);+ if (Array.isArray(custom)) {+ result.push(...custom);+ }+ }++ return result;+ },+ [resourceName, t]+ );++ // Auto-generate from title+ useEffect(() => {+ if (readonly || manualEdit) return;++ const parts: string[] = [];+ if (resourceTitle) {+ const escaped = escapeTitle(resourceTitle);+ if (suffix) {+ parts.push(escaped, randomSuffixRef.current);+ } else if (escaped) {+ parts.push(escaped);+ } else {+ parts.push(randomString(4).toLowerCase());+ }+ }+ const name = parts.join("-");++ onChangeRef.current?.(name);+ validateId(name).then((msgs) => {+ if (!initializedRef.current && msgs.length > 0) {+ const fallback = name + "-" + randomString(4).toLowerCase();+ onChangeRef.current?.(fallback);+ validateId(fallback).then(updateMessages);+ } else {+ updateMessages(msgs);+ }+ initializedRef.current = true;+ });+ }, [resourceTitle, readonly, manualEdit, suffix, validateId, updateMessages]);++ const handleManualInput = (newValue: string) => {+ onChange?.(newValue);+ setMessages([]);+ validateId(newValue).then(updateMessages);+ };++ useImperativeHandle(+ ref,+ () => ({+ get resourceId() {+ return value;+ },+ get isValidated() {+ return messages.length === 0;+ },+ addValidationError(message: string) {+ const newMessages: ValidatedMessage[] = [+ ...messages,+ { type: "error", message },+ ];+ setMessages(newMessages);+ onValidationChangeRef.current?.(false);+ },+ }),+ [value, messages]+ );++ const visible = readonly ? !!value : true;+ if (!visible) return null;++ return (+ <div>+ {readonly || !manualEdit ? (+ <div className="textinfolabel text-sm flex items-start flex-wrap gap-x-1">+ <div className="flex items-center gap-x-1">+ {t("resource-id.self", { resource: resourceName })}:+ {value ? (+ <span className="text-gray-600 font-medium mr-1">{value}</span>+ ) : (+ <span className="text-control-placeholder italic">-</span>+ )}+ </div>+ {!readonly && (+ <div>+ <span>{t("resource-id.cannot-be-changed-later")}</span>+ <button+ type="button"+ className="text-accent font-medium cursor-pointer hover:opacity-80 ml-1"+ onClick={() => setManualEdit(true)}+ >+ {t("common.edit")}+ </button>+ </div>+ )}+ </div>+ ) : (+ <div className="mt-1">+ <label className="textlabel flex items-center">+ {t("resource-id.self", { resource: resourceName })}+ <span className="ml-0.5 text-error">*</span>+ </label>+ <p className="textinfolabel mb-2 mt-1">+ {t("resource-id.description", { resource: resourceName })}+ </p>+ <Input+ value={value}+ onChange={(e) => handleManualInput(e.target.value)}+ placeholder={t("resource-id.self", { resource: resourceName })}+ className={+ messages.some((m) => m.type === "error") ? "border-error" : ""+ }+ />+ </div>+ )}+ {messages.length > 0 && (+ <ul className="w-full my-2 flex flex-col gap-y-2 list-disc list-outside pl-4">+ {messages.map((msg) => (+ <li+ key={msg.message}+ className={`break-words w-full text-xs ${+ msg.type === "warning" ? "text-yellow-600" : "text-red-600"+ }`}+ >+ {msg.message}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+});diff --git a/frontend/src/react/pages/settings/RolesPage.tsx b/frontend/src/react/pages/settings/RolesPage.tsxnew file mode 100644index 0000000000..6afd01c221--- /dev/null+++ b/frontend/src/react/pages/settings/RolesPage.tsx@@ -0,0 +1,914 @@+import { create } from "@bufbuild/protobuf";+import { Code, ConnectError } from "@connectrpc/connect";+import { cloneDeep, sortBy, uniq } from "lodash-es";+import { Pencil, Plus, Search, Trash2, X } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { FeatureAttention } from "@/react/components/FeatureAttention";+import {+ ResourceIdField,+ type ResourceIdFieldRef,+} from "@/react/components/ResourceIdField";+import {+ Alert,+ AlertDescription,+ AlertTitle,+} from "@/react/components/ui/alert";+import { Badge } from "@/react/components/ui/badge";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { Textarea } from "@/react/components/ui/textarea";+import { useVueState } from "@/react/hooks/useVueState";+import {+ pushNotification,+ useRoleStore,+ useSubscriptionV1Store,+ useWorkspaceV1Store,+} from "@/store";+import { roleNamePrefix } from "@/store/modules/v1/common";+import {+ BASIC_WORKSPACE_PERMISSIONS,+ PERMISSIONS,+ PRESET_ROLES,+} from "@/types";+import type { Role } from "@/types/proto-es/v1/role_service_pb";+import { RoleSchema } from "@/types/proto-es/v1/role_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import {+ displayRoleDescription,+ displayRoleTitle,+ extractRoleResourceName,+ hasWorkspacePermissionV2,+ isCustomRole,+} from "@/utils";+import { extractGrpcErrorMessage, getErrorCode } from "@/utils/connect";++// Escape key stack: only the topmost overlay handles Escape.+const escapeStack: (() => void)[] = [];++function useEscapeKey(onEscape: () => void) {+ useEffect(() => {+ escapeStack.push(onEscape);+ const handler = (e: KeyboardEvent) => {+ if (+ e.key === "Escape" &&+ escapeStack[escapeStack.length - 1] === onEscape+ ) {+ onEscape();+ }+ };+ document.addEventListener("keydown", handler);+ return () => {+ document.removeEventListener("keydown", handler);+ const idx = escapeStack.lastIndexOf(onEscape);+ if (idx >= 0) escapeStack.splice(idx, 1);+ };+ }, [onEscape]);+}++// ============================================================+// PermissionTransfer+// ============================================================++function PermissionTransfer({+ value,+ onChange,+ disabled,+}: {+ value: string[];+ onChange: (permissions: string[]) => void;+ disabled: boolean;+}) {+ const { t } = useTranslation();+ const [sourceFilter, setSourceFilter] = useState("");++ const allPermissions = useMemo(() => [...PERMISSIONS].sort(), []);++ const valueSet = useMemo(() => new Set(value), [value]);++ const sourceItems = useMemo(() => {+ const items = allPermissions.filter((p) => !valueSet.has(p));+ if (!sourceFilter.trim()) return items;+ const kw = sourceFilter.trim().toLowerCase();+ return items.filter((p) => p.toLowerCase().includes(kw));+ }, [allPermissions, valueSet, sourceFilter]);++ const totalSourceCount = allPermissions.length - value.length;++ const selectItem = (p: string) => {+ if (disabled) return;+ onChange(uniq([...value, p]));+ };++ const removeItem = (p: string) => {+ if (disabled) return;+ onChange(value.filter((v) => v !== p));+ };++ const selectAll = () => {+ if (disabled) return;+ onChange(uniq([...value, ...sourceItems]));+ setSourceFilter("");+ };++ const clearAll = () => {+ if (disabled) return;+ onChange([]);+ };++ return (+ <div className="flex h-[28rem] border rounded-md overflow-hidden">+ {/* Source */}+ <div className="flex-1 flex flex-col border-r min-w-0">+ <div className="flex items-center gap-x-2 px-3 py-2 border-b">+ <button+ type="button"+ className="text-sm text-main hover:text-accent disabled:opacity-50"+ disabled={disabled || sourceItems.length === 0}+ onClick={selectAll}+ >+ {t("common.select-all")}+ </button>+ <span className="text-xs text-control-light">+ {t("common.total-n-items", { n: totalSourceCount })}+ </span>+ </div>+ <div className="px-3 py-2 border-b">+ <div className="relative">+ <Input+ placeholder={t("common.search")}+ value={sourceFilter}+ onChange={(e) => setSourceFilter(e.target.value)}+ className="h-8 text-sm pr-8"+ disabled={disabled}+ />+ <Search className="absolute right-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-control-placeholder pointer-events-none" />+ </div>+ </div>+ <div className="flex-1 overflow-auto">+ {sourceItems.map((p) => (+ <div+ key={p}+ className={`group flex items-center justify-between px-3 py-1.5 text-sm hover:bg-gray-50 ${disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`}+ onClick={() => selectItem(p)}+ >+ <span className="truncate">{p}</span>+ {!disabled && (+ <Plus className="h-3.5 w-3.5 shrink-0 text-control-light opacity-0 group-hover:opacity-100 group-hover:text-accent" />+ )}+ </div>+ ))}+ </div>+ </div>++ {/* Target */}+ <div className="flex-1 flex flex-col min-w-0">+ <div className="flex items-center gap-x-2 px-3 py-2 border-b">+ <button+ type="button"+ className="text-sm text-main hover:text-accent disabled:opacity-50"+ disabled={disabled || value.length === 0}+ onClick={clearAll}+ >+ {t("common.clear")}+ </button>+ <span className="text-xs text-control-light">+ {t("common.n-items-selected", { n: value.length })}+ </span>+ </div>+ <div className="flex-1 overflow-auto">+ {[...value].sort().map((p) => (+ <div+ key={p}+ className={`group flex items-center justify-between px-3 py-1.5 text-sm hover:bg-gray-50 ${disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`}+ onClick={() => removeItem(p)}+ >+ <span className="truncate">{p}</span>+ {!disabled && (+ <X className="h-3.5 w-3.5 shrink-0 text-control-light opacity-0 group-hover:opacity-100 group-hover:text-error" />+ )}+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}++// ============================================================+// ImportPermissionModal+// ============================================================++function ImportPermissionModal({+ onCancel,+ onImport,+}: {+ onCancel: () => void;+ onImport: (permissions: string[]) => void;+}) {+ const { t } = useTranslation();+ const roleStore = useRoleStore();+ const roleList = useVueState(() => [...roleStore.roleList]);+ const [selectedRoleName, setSelectedRoleName] = useState<string>("");+ useEscapeKey(onCancel);++ const selectedRole = useMemo(+ () => roleList.find((r) => r.name === selectedRoleName),+ [roleList, selectedRoleName]+ );++ const permissions = selectedRole?.permissions ?? [];++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"+ onClick={(e) => {+ if (e.target === e.currentTarget) onCancel();+ }}+ >+ <div className="bg-white rounded-lg shadow-lg w-[28rem] p-6">+ <div className="flex items-center justify-between mb-4">+ <h3 className="text-lg font-medium">{t("role.import-from-role")}</h3>+ <Button variant="ghost" size="icon" onClick={onCancel}>+ <X className="h-4 w-4" />+ </Button>+ </div>++ <div className="flex flex-col gap-y-3">+ <div>+ <label className="textlabel mb-1 block">+ {t("role.select-role")}+ </label>+ <select+ value={selectedRoleName}+ onChange={(e) => setSelectedRoleName(e.target.value)}+ className="flex h-9 w-full rounded-md border border-control-border bg-transparent px-3 py-1 text-sm"+ >+ <option value="">--</option>+ {roleList.map((role) => (+ <option key={role.name} value={role.name}>+ {displayRoleTitle(role.name)}+ </option>+ ))}+ </select>+ </div>++ {selectedRole && (+ <>+ <p className="textinfolabel">+ {displayRoleDescription(selectedRole.name)}+ </p>+ <div>+ <label className="textlabel mb-1 block">+ {t("common.permissions")} ({permissions.length})+ </label>+ <div className="max-h-40 overflow-auto border rounded-sm p-2">+ {permissions.map((p) => (+ <p key={p} className="text-sm leading-5">+ {p}+ </p>+ ))}+ </div>+ </div>+ </>+ )}++ <div className="flex justify-end gap-x-2 mt-2">+ <Button variant="outline" onClick={onCancel}>+ {t("common.cancel")}+ </Button>+ <Button+ disabled={!selectedRole}+ onClick={() => onImport(permissions)}+ >+ {t("common.confirm")}+ </Button>+ </div>+ </div>+ </div>+ </div>+ );+}++// ============================================================+// DeleteConfirmModal+// ============================================================++function DeleteConfirmModal({+ roleName,+ occupiedResources,+ onConfirm,+ onCancel,+}: {+ roleName: string;+ occupiedResources: string[];+ onConfirm: () => void;+ onCancel: () => void;+}) {+ const { t } = useTranslation();+ const canDelete = occupiedResources.length === 0;+ useEscapeKey(onCancel);++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"+ onClick={(e) => {+ if (e.target === e.currentTarget) onCancel();+ }}+ >+ <div className="bg-white rounded-lg shadow-lg w-[28rem] p-6">+ <h3 className="text-lg font-medium mb-4">+ {t("common.delete")} - {displayRoleTitle(roleName)}+ </h3>++ {occupiedResources.length > 0 ? (+ <div className="mb-4">+ <Alert variant="warning">+ <AlertDescription>+ <p className="mb-2">+ {t("resource.delete-warning-with-resources", {+ name: displayRoleTitle(roleName),+ })}+ </p>+ <ul className="list-disc pl-4 text-sm">+ {occupiedResources.map((r) => (+ <li key={r}>{r}</li>+ ))}+ </ul>+ <p className="mt-2">{t("resource.delete-warning-retry")}</p>+ </AlertDescription>+ </Alert>+ </div>+ ) : (+ <p className="mb-4 text-sm text-control-light">+ {t("resource.delete-warning", {+ name: displayRoleTitle(roleName),+ })}+ </p>+ )}++ <div className="flex justify-end gap-x-2">+ <Button variant="outline" onClick={onCancel}>+ {t("common.cancel")}+ </Button>+ {canDelete && (+ <Button variant="destructive" onClick={onConfirm}>+ {t("common.delete")}+ </Button>+ )}+ </div>+ </div>+ </div>+ );+}++// ============================================================+// RoleDrawer+// ============================================================++function RoleDrawer({+ role,+ mode,+ hasCustomRoleFeature,+ onClose,+ onShowFeatureModal,+}: {+ role: Role | undefined;+ mode: "ADD" | "EDIT";+ hasCustomRoleFeature: boolean;+ onClose: () => void;+ onShowFeatureModal: () => void;+}) {+ const { t } = useTranslation();+ const roleStore = useRoleStore();+ useEscapeKey(onClose);++ const [editRole, setEditRole] = useState<Role>(+ create(RoleSchema, { permissions: [...BASIC_WORKSPACE_PERMISSIONS] })+ );+ const [dirty, setDirty] = useState(false);+ const [loading, setLoading] = useState(false);+ const [showImportModal, setShowImportModal] = useState(false);+ const [resourceId, setResourceId] = useState("");+ const [resourceIdValid, setResourceIdValid] = useState(true);+ const resourceIdFieldRef = useRef<ResourceIdFieldRef>(null);++ const isBuiltin = useMemo(+ () => (editRole.name ? !isCustomRole(editRole.name) : false),+ [editRole.name]+ );++ const missedBasicPermissions = useMemo(+ () =>+ BASIC_WORKSPACE_PERMISSIONS.filter(+ (p) => !editRole.permissions.includes(p)+ ),+ [editRole.permissions]+ );++ const canCreate = hasWorkspacePermissionV2("bb.roles.create");+ const canUpdate = hasWorkspacePermissionV2("bb.roles.update");+ const allowSave = useMemo(() => {+ if (!dirty) return false;+ if (!editRole.title || editRole.title.length === 0) return false;+ if (mode === "ADD") {+ if (!resourceId) return false;+ if (!resourceIdValid) return false;+ }+ if (editRole.permissions.length === 0) return false;+ return true;+ }, [+ dirty,+ editRole.title,+ editRole.permissions,+ mode,+ resourceId,+ resourceIdValid,+ ]);++ const validateResourceId = useCallback(+ async (val: string) => {+ if (+ val &&+ roleStore.roleList.find((r) => r.name === `${roleNamePrefix}${val}`)+ ) {+ return [+ {+ type: "error" as const,+ message: t("resource-id.validation.duplicated", {+ resource: t("role.self"),+ }),+ },+ ];+ }+ return [];+ },+ [roleStore.roleList, t]+ );++ // Sync incoming role prop to local state+ useEffect(() => {+ if (role) {+ const cloned = cloneDeep(role);+ if (!cloned.title) {+ cloned.title = extractRoleResourceName(cloned.name);+ }+ setEditRole(cloned);+ setResourceId(extractRoleResourceName(cloned.name));+ setResourceIdValid(true);+ requestAnimationFrame(() => {+ setDirty(false);+ });+ }+ }, [role]);++ const handleTitleChange = (title: string) => {+ setEditRole((prev) => {+ const next = cloneDeep(prev);+ next.title = title;+ return next;+ });+ setDirty(true);+ };++ const handleResourceIdChange = (val: string) => {+ setResourceId(val);+ setEditRole((prev) => {+ const next = cloneDeep(prev);+ next.name = `${roleNamePrefix}${val}`;+ return next;+ });+ setDirty(true);+ };++ const handleDescriptionChange = (description: string) => {+ setEditRole((prev) => {+ const next = cloneDeep(prev);+ next.description = description;+ return next;+ });+ setDirty(true);+ };++ const handlePermissionsChange = (permissions: string[]) => {+ setEditRole((prev) => {+ const next = cloneDeep(prev);+ next.permissions = permissions;+ return next;+ });+ setDirty(true);+ };++ const addMissingPermissions = () => {+ handlePermissionsChange(+ uniq([...editRole.permissions, ...missedBasicPermissions])+ );+ };++ const handleImportPermissions = (permissions: string[]) => {+ handlePermissionsChange(uniq([...editRole.permissions, ...permissions]));+ setShowImportModal(false);+ };++ const handleSave = async () => {+ if (!hasCustomRoleFeature) {+ onShowFeatureModal();+ onClose();+ return;+ }++ setLoading(true);+ try {+ await roleStore.upsertRole(editRole);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: mode === "ADD" ? t("common.added") : t("common.updated"),+ });+ onClose();+ } catch (error) {+ if (error instanceof ConnectError && error.code === Code.AlreadyExists) {+ resourceIdFieldRef.current?.addValidationError(error.message);+ } else {+ throw error;+ }+ } finally {+ setLoading(false);+ }+ };++ if (!role) return null;++ return (+ <>+ {/* Backdrop */}+ <div className="fixed inset-0 z-40 bg-black/30" onClick={onClose} />++ {/* Drawer */}+ <div className="fixed inset-y-0 right-0 z-50 w-[44rem] max-w-[100vw] bg-white shadow-xl flex flex-col">+ {/* Header */}+ <div className="flex items-center justify-between px-6 py-4 border-b">+ <h2 className="text-lg font-medium">+ {mode === "ADD" ? t("role.setting.add") : t("role.setting.edit")}+ </h2>+ <Button variant="ghost" size="icon" onClick={onClose}>+ <X className="h-5 w-5" />+ </Button>+ </div>++ {/* Content */}+ <div className="flex-1 overflow-auto px-6 py-6">+ <div className="flex flex-col gap-y-5">+ {/* Title */}+ <div className="flex flex-col gap-y-1.5">+ <label className="text-sm font-medium text-main">+ {t("role.title")}+ <span className="ml-0.5 text-error">*</span>+ </label>+ <Input+ value={editRole.title}+ onChange={(e) => handleTitleChange(e.target.value)}+ placeholder={t("role.setting.title-placeholder")}+ maxLength={200}+ disabled={isBuiltin}+ className={+ dirty && editRole.title?.length === 0 ? "border-error" : ""+ }+ />++ {/* Resource ID — inline below title */}+ {mode === "ADD" && (+ <ResourceIdField+ ref={resourceIdFieldRef}+ value={resourceId}+ resourceType="role"+ resourceName={t("role.self")}+ resourceTitle={editRole.title}+ suffix+ validate={validateResourceId}+ onChange={handleResourceIdChange}+ onValidationChange={setResourceIdValid}+ />+ )}+ {mode === "EDIT" && !isBuiltin && (+ <ResourceIdField+ value={extractRoleResourceName(editRole.name)}+ resourceType="role"+ resourceName={t("role.self")}+ readonly+ />+ )}+ </div>++ {/* Description */}+ <div className="flex flex-col gap-y-1.5">+ <label className="text-sm font-medium text-main">+ {t("common.description")}+ </label>+ <Textarea+ value={editRole.description}+ onChange={(e) => handleDescriptionChange(e.target.value)}+ placeholder={t("role.setting.description-placeholder")}+ maxLength={1000}+ disabled={isBuiltin}+ className="min-h-[80px]"+ />+ </div>++ {/* Permissions */}+ <div className="flex flex-col gap-y-2">+ <div className="flex items-center justify-between">+ <label className="text-sm font-medium text-main">+ {t("common.permissions")}+ <span className="ml-0.5 text-error">*</span>+ </label>+ {!isBuiltin && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => setShowImportModal(true)}+ >+ <Plus className="w-4 h-4 mr-1" />+ {t("role.import-from-role")}+ </Button>+ )}+ </div>++ {missedBasicPermissions.length > 0 && !isBuiltin && (+ <Alert variant="error">+ <AlertTitle>+ {t("common.missing-required-permission")}+ </AlertTitle>+ <AlertDescription>+ <p>{t("common.required-workspace-permission")}</p>+ <ul className="list-disc pl-4 mt-1">+ {missedBasicPermissions.map((p) => (+ <li key={p}>{p}</li>+ ))}+ </ul>+ <div className="mt-2">+ <Button size="sm" onClick={addMissingPermissions}>+ {t("common.add-permissions")}+ </Button>+ </div>+ </AlertDescription>+ </Alert>+ )}++ <PermissionTransfer+ value={editRole.permissions}+ onChange={handlePermissionsChange}+ disabled={isBuiltin}+ />+ </div>+ </div>+ </div>++ {/* Footer */}+ {!isBuiltin && (+ <div className="flex items-center justify-end gap-x-2 px-6 py-4 border-t">+ <Button variant="outline" onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button+ disabled={+ !allowSave || (mode === "ADD" ? !canCreate : !canUpdate)+ }+ onClick={handleSave}+ >+ {mode === "ADD" ? t("common.add") : t("common.update")}+ </Button>+ </div>+ )}++ {/* Loading overlay */}+ {loading && (+ <div className="absolute inset-0 z-10 bg-white/50 flex items-center justify-center">+ <div className="animate-spin h-6 w-6 border-2 border-accent border-t-transparent rounded-full" />+ </div>+ )}+ </div>++ {/* Import modal */}+ {showImportModal && (+ <ImportPermissionModal+ onCancel={() => setShowImportModal(false)}+ onImport={handleImportPermissions}+ />+ )}+ </>+ );+}++// ============================================================+// RolesPage (main)+// ============================================================++export function RolesPage() {+ const { t } = useTranslation();+ const roleStore = useRoleStore();+ const workspaceStore = useWorkspaceV1Store();+ const subscriptionStore = useSubscriptionV1Store();++ const [ready, setReady] = useState(false);+ const [detailRole, setDetailRole] = useState<Role | undefined>();+ const [detailMode, setDetailMode] = useState<"ADD" | "EDIT">("ADD");+ const [showFeatureModal, setShowFeatureModal] = useState(false);+ const [deleteTarget, setDeleteTarget] = useState<Role | undefined>();+ const [deleteResources, setDeleteResources] = useState<string[]>([]);++ const hasCustomRoleFeature = useVueState(() =>+ subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_CUSTOM_ROLES)+ );++ const canCreate = hasWorkspacePermissionV2("bb.roles.create");+ const canDelete = hasWorkspacePermissionV2("bb.roles.delete");++ const roleList = useVueState(() => [...roleStore.roleList]);++ const filteredRoleList = useMemo(() => {+ return sortBy(roleList, (role) =>+ PRESET_ROLES.includes(role.name)+ ? PRESET_ROLES.indexOf(role.name)+ : roleList.length+ );+ }, [roleList]);++ // Fetch roles on mount and handle query param+ useEffect(() => {+ roleStore+ .fetchRoleList()+ .then(() => {+ const urlParams = new URLSearchParams(window.location.search);+ const name = urlParams.get("role");+ if (name?.startsWith(roleNamePrefix)) {+ const role = roleStore.getRoleByName(name);+ if (role) {+ setDetailRole(role);+ setDetailMode("EDIT");+ }+ }+ })+ .finally(() => setReady(true));+ }, []);++ const addRole = () => {+ setDetailRole(+ create(RoleSchema, { permissions: [...BASIC_WORKSPACE_PERMISSIONS] })+ );+ setDetailMode("ADD");+ };++ const editRole = (role: Role) => {+ setDetailRole(role);+ setDetailMode("EDIT");+ };++ const handleDeleteRole = (role: Role) => {+ if (!hasCustomRoleFeature) {+ setShowFeatureModal(true);+ return;+ }++ const usersWithRole = [+ ...(workspaceStore.roleMapToUsers.get(role.name) ?? new Set()),+ ];+ setDeleteResources(usersWithRole);+ setDeleteTarget(role);+ };++ const confirmDelete = async () => {+ if (!deleteTarget) return;+ try {+ await roleStore.deleteRole(deleteTarget);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.deleted"),+ });+ setDeleteTarget(undefined);+ } catch (error) {+ if (getErrorCode(error) === Code.FailedPrecondition) {+ const message = extractGrpcErrorMessage(error);+ const resources =+ message.split("used by resources: ")[1]?.split(",") ?? [];+ if (resources.length > 0) {+ setDeleteResources(resources);+ }+ }+ }+ };++ return (+ <div className="w-full px-4 py-4 flex flex-col gap-y-4">+ {showFeatureModal && (+ <FeatureAttention feature={PlanFeature.FEATURE_CUSTOM_ROLES} />+ )}++ <div className="textinfolabel">+ {t("role.setting.description")}{" "}+ <a+ href="https://docs.bytebase.com/administration/roles?source=console"+ target="_blank"+ rel="noopener noreferrer"+ className="text-accent hover:underline"+ >+ {t("common.learn-more")}+ </a>+ </div>++ <div className="w-full flex justify-end">+ <Button disabled={!canCreate} onClick={addRole}>+ <Plus className="h-4 w-4 mr-1" />+ {t("common.add")}+ </Button>+ </div>++ {/* Roles Table */}+ {ready ? (+ <div className="border rounded-md overflow-hidden">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b bg-control-bg">+ <th className="px-4 py-2 text-left font-medium w-64">+ {t("role.title")}+ </th>+ <th className="px-4 py-2 text-left font-medium">+ {t("common.description")}+ </th>+ <th className="px-4 py-2 text-right font-medium w-40" />+ </tr>+ </thead>+ <tbody>+ {filteredRoleList.map((role, i) => (+ <tr+ key={role.name}+ className={`border-b last:border-b-0 ${i % 2 === 1 ? "bg-gray-50" : ""}`}+ >+ <td className="px-4 py-2">+ <span>{displayRoleTitle(role.name)}</span>+ {!isCustomRole(role.name) && (+ <Badge variant="secondary" className="ml-2 text-xs">+ {t("common.system")}+ </Badge>+ )}+ </td>+ <td className="px-4 py-2 text-control-light truncate">+ {displayRoleDescription(role.name)}+ </td>+ <td className="px-4 py-2">+ {isCustomRole(role.name) && (+ <div className="flex justify-end gap-x-2">+ {canDelete && (+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 text-error hover:text-error"+ onClick={() => handleDeleteRole(role)}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ )}+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ onClick={() => editRole(role)}+ >+ <Pencil className="h-4 w-4" />+ </Button>+ </div>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : (+ <div className="flex items-center justify-center h-32">+ <div className="animate-spin h-6 w-6 border-2 border-accent border-t-transparent rounded-full" />+ </div>+ )}++ {/* Role Drawer */}+ <RoleDrawer+ role={detailRole}+ mode={detailMode}+ hasCustomRoleFeature={hasCustomRoleFeature}+ onClose={() => setDetailRole(undefined)}+ onShowFeatureModal={() => setShowFeatureModal(true)}+ />++ {/* Delete confirm */}+ {deleteTarget && (+ <DeleteConfirmModal+ roleName={deleteTarget.name}+ occupiedResources={deleteResources}+ onConfirm={confirmDelete}+ onCancel={() => setDeleteTarget(undefined)}+ />+ )}+ </div>+ );+}diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.tsindex 0af47f8e52..a7d4b6a39b 100644--- a/frontend/src/router/dashboard/workspace.ts+++ b/frontend/src/router/dashboard/workspace.ts@@ -346,8 +346,8 @@ const workspaceRoutes: RouteRecordRaw[] = [title: () => t("settings.sidebar.custom-roles"),requiredPermissionList: () => ["bb.roles.list"],},- component: () => import("@/views/SettingWorkspaceRole.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: () => ({ page: "RolesPage" }),},],},diff --git a/frontend/src/views/SettingWorkspaceRole.vue b/frontend/src/views/SettingWorkspaceRole.vuedeleted file mode 100644index c4c304334e..0000000000--- a/frontend/src/views/SettingWorkspaceRole.vue+++ /dev/null@@ -1,9 +0,0 @@-<template>- <div class="w-full px-4 py-4 flex flex-col gap-y-4 text-sm">- <RoleSetting />- </div>-</template>--<script lang="ts" setup>-import RoleSetting from "@/components/Role/RoleSetting.vue";-</script>