Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(frontend): migrate environments page to React (#19782)

Danny Xub4ffa89e682a
diff --git a/frontend/src/components/EnvironmentForm/Buttons.vue b/frontend/src/components/EnvironmentForm/Buttons.vue
deleted file mode 100644
index 1e8d2f50f5..0000000000
--- a/frontend/src/components/EnvironmentForm/Buttons.vue
+++ /dev/null
@@ -1,107 +0,0 @@
-<template>
- <div
- v-if="create"
- class="flex justify-end items-center gap-x-3"
- v-bind="$attrs"
- >
- <NButton @click.prevent="events.emit('cancel')">
- {{ t("common.cancel") }}
- </NButton>
- <NButton
- type="primary"
- :disabled="!allowCreate"
- @click.prevent="createEnvironment"
- >
- {{ t("common.create") }}
- </NButton>
- </div>
-
- <div
- v-if="!create && allowEdit && valueChanged()"
- class="flex items-center justify-between gap-x-3"
- v-bind="$attrs"
- >
- <NButton @click.prevent="revertEnvironment">
- {{ t("common.cancel") }}
- </NButton>
- <NButton type="primary" @click.prevent="updateEnvironment">
- {{ t("common.confirm-and-update") }}
- </NButton>
- </div>
-</template>
-
-<script setup lang="ts">
-import { cloneDeep, isEqual } from "lodash-es";
-import { NButton } from "naive-ui";
-import { useI18n } from "vue-i18n";
-import { pushNotification } from "@/store";
-import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";
-import { useEnvironmentFormContext } from "./context";
-
-const { t } = useI18n();
-const {
- state,
- environment,
- rolloutPolicy,
- create,
- resourceIdField,
- allowEdit,
- allowCreate,
- valueChanged,
- events,
-} = useEnvironmentFormContext();
-
-const revertEnvironment = () => {
- state.value.environment = cloneDeep(environment.value);
- state.value.rolloutPolicy = cloneDeep(rolloutPolicy.value);
- events.emit("revert-sql-review");
-};
-
-const createEnvironment = () => {
- events.emit("create", {
- environment: {
- id: resourceIdField.value?.resourceId,
- title: state.value.environment.title,
- color: state.value.environment.color,
- tags: state.value.environment.tags,
- order: state.value.environment.order,
- },
- rolloutPolicy: state.value.rolloutPolicy,
- });
-};
-
-const updateEnvironment = () => {
- if (!isEqual(rolloutPolicy.value, state.value.rolloutPolicy)) {
- events.emit("update-policy", {
- environment: state.value.environment,
- policyType: PolicyType.ROLLOUT_POLICY,
- policy: state.value.rolloutPolicy,
- });
- }
-
- events.emit("update-sql-review");
-
- const env = cloneDeep(environment.value);
- if (
- state.value.environment.title !== env.title ||
- !isEqual(state.value.environment.tags, env.tags) ||
- state.value.environment.color !== env.color
- ) {
- const environmentPatch = {
- ...env,
- title: state.value.environment.title,
- tags: state.value.environment.tags,
- color: state.value.environment.color,
- };
- events.emit("update", environmentPatch);
- }
-
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("environment.successfully-updated-environment", {
- name: state.value.environment.title,
- }),
- });
-};
-</script>
diff --git a/frontend/src/components/EnvironmentForm/EnvironmentForm.vue b/frontend/src/components/EnvironmentForm/EnvironmentForm.vue
deleted file mode 100644
index 9e6041482a..0000000000
--- a/frontend/src/components/EnvironmentForm/EnvironmentForm.vue
+++ /dev/null
@@ -1,100 +0,0 @@
-<template>
- <slot />
-
- <FeatureModal
- :open="missingFeature != undefined"
- :feature="missingFeature"
- @cancel="missingFeature = undefined"
- />
-</template>
-
-<script lang="ts" setup>
-import { computed, toRef } from "vue";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import { hasFeature } from "@/store";
-import type { Policy } from "@/types/proto-es/v1/org_policy_service_pb";
-import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import type { Environment } from "@/types/v1/environment";
-import { FeatureModal } from "../FeatureGuard";
-import { provideEnvironmentFormContext } from "./context";
-
-const props = withDefaults(
- defineProps<{
- create?: boolean;
- environment: Environment;
- rolloutPolicy: Policy;
- }>(),
- {
- create: false,
- }
-);
-
-const emit = defineEmits<{
- (
- event: "create",
- params: {
- environment: Partial<Environment>;
- rolloutPolicy: Policy;
- }
- ): void;
- (event: "update", environment: Environment): void;
- (
- event: "update-policy",
- params: {
- environment: Environment;
- policyType: PolicyType;
- policy: Policy;
- }
- ): void;
- (event: "delete", environment: Environment): void;
- (event: "cancel"): void;
-}>();
-
-const context = provideEnvironmentFormContext({
- create: toRef(props, "create"),
- environment: toRef(props, "environment"),
- rolloutPolicy: toRef(props, "rolloutPolicy"),
-});
-const { valueChanged, events, missingFeature } = context;
-
-const isEditing = computed(() => {
- return !props.create && valueChanged();
-});
-
-useEmitteryEventListener(events, "create", (params) => {
- const { environment } = params;
- if (environment.tags?.protected === "protected") {
- if (!hasFeature(PlanFeature.FEATURE_ENVIRONMENT_TIERS)) {
- missingFeature.value = PlanFeature.FEATURE_ENVIRONMENT_TIERS;
- return;
- }
- }
-
- emit("create", params);
-});
-useEmitteryEventListener(events, "update", (environment) => {
- if (
- environment.tags.protected === "protected" &&
- !hasFeature(PlanFeature.FEATURE_ENVIRONMENT_TIERS)
- ) {
- missingFeature.value = PlanFeature.FEATURE_ENVIRONMENT_TIERS;
- return;
- }
-
- emit("update", environment);
-});
-useEmitteryEventListener(events, "update-policy", (params) => {
- emit("update-policy", params);
-});
-useEmitteryEventListener(events, "delete", (environment) => {
- emit("delete", environment);
-});
-useEmitteryEventListener(events, "cancel", () => {
- emit("cancel");
-});
-
-defineExpose({
- isEditing,
-});
-</script>
diff --git a/frontend/src/components/EnvironmentForm/Form.vue b/frontend/src/components/EnvironmentForm/Form.vue
deleted file mode 100644
index 15c2245008..0000000000
--- a/frontend/src/components/EnvironmentForm/Form.vue
+++ /dev/null
@@ -1,343 +0,0 @@
-<template>
- <div>
- <div class="flex flex-col gap-y-6">
- <div v-if="features.includes('BASE')" class="flex flex-col gap-y-2">
- <div for="name" class="flex item-center gap-x-2">
- <NColorPicker
- :modes="['hex']"
- :show-alpha="false"
- :disabled="!allowEdit"
- :value="state.environment.color || '#4f46e5'"
- @complete="onColorComplete"
- @update:value="onColorUpdate"
- >
- <template #trigger="{ value, onClick, ref: triggerRef }">
- <div
- :ref="triggerRef"
- class="w-5 h-5 rounded-sm cursor-pointer"
- :style="{ backgroundColor: value || '#4f46e5' }"
- @click="onClick"
- />
- </template>
- </NColorPicker>
- <span for="name" class="font-medium">
- {{ t("common.environment-name") }}
- <RequiredStar />
- </span>
- </div>
- <PermissionGuardWrapper
- v-slot="slotProps"
- :permissions="[
- 'bb.settings.setEnvironment'
- ]"
- >
- <NInput
- v-model:value="state.environment.title"
- :disabled="slotProps.disabled"
- required
- />
- </PermissionGuardWrapper>
-
- <ResourceIdField
- ref="resourceIdField"
- resource-type="environment"
- :readonly="!create"
- :value="state.environment.id"
- :resource-title="state.environment.title"
- :fetch-resource="
- (id) => getEnvironmentById(id)
- "
- />
- </div>
-
- <div v-if="features.includes('TIER')" class="flex flex-col gap-y-2">
- <div class="gap-y-1">
- <label class="font-medium flex items-center">
- {{ t("policy.environment-tier.name") }}
- <FeatureBadge :feature="PlanFeature.FEATURE_ENVIRONMENT_TIERS" />
- </label>
- <p class="text-sm text-gray-600">
- <i18n-t tag="span" keypath="policy.environment-tier.description">
- <template #newline><br /></template>
- </i18n-t>
- <LearnMoreLink
- class="ml-1"
- url="https://docs.bytebase.com/change-database/environment-policy/overview/?source=console#environment-tier"
- />
- </p>
- </div>
-
- <PermissionGuardWrapper
- v-slot="slotProps"
- :permissions="[
- 'bb.settings.setEnvironment'
- ]"
- >
- <NCheckbox
- :checked="state.environment.tags.protected === 'protected'"
- :disabled="slotProps.disabled"
- @update:checked="
- (on: boolean) => {
- state.environment.tags.protected = on
- ? 'protected'
- : 'unprotected';
- }
- "
- >
- {{ t("policy.environment-tier.mark-env-as-production") }}
- </NCheckbox>
- </PermissionGuardWrapper>
- </div>
-
- <div
- v-if="features.includes('ROLLOUT_POLICY') && hasGetPolicyPermission"
- class="flex flex-col gap-y-2"
- >
- <div class="gap-y-1">
- <div class="flex items-baseline gap-x-2">
- <label class="font-medium">
- {{ t("policy.rollout.name") }}
- </label>
- <span
- v-show="!create && valueChanged('rolloutPolicy')"
- class="textlabeltip"
- >
- {{ t("policy.rollout.tip") }}
- </span>
- </div>
- <div class="textinfolabel">
- {{ t("policy.rollout.info", { permission: "bb.taskRuns.create" }) }}
- <LearnMoreLink
- class="ml-1"
- url="https://docs.bytebase.com/change-database/environment-policy/rollout-policy/?source=console"
- />
- </div>
- </div>
- <RolloutPolicyConfig
- v-model:policy="state.rolloutPolicy"
- />
- </div>
-
- <SQLReviewForResource
- v-if="features.includes('SQL_REVIEW') && !create"
- ref="sqlReviewForResourceRef"
- :resource="`${environmentNamePrefix}${environment.id}`"
- />
- </div>
-
- <div
- v-if="!create"
- class="mt-6 border-t border-block-border flex justify-between items-center pt-4 pb-2"
- >
- <BBButtonConfirm
- v-if="allowArchive"
- :type="'DELETE'"
- :button-text="t('environment.delete')"
- :ok-text="t('common.delete')"
- :confirm-title="
- t('environment.delete') + ` '${state.environment.title}'?`
- "
- :positive-button-props="{
- disabled: existRelatedResource ? !confirmDelete : false,
- }"
- :require-confirm="true"
- @confirm="deleteEnvironment"
- >
- <div class="mt-3">
- <NCheckbox
- v-if="existRelatedResource"
- v-model:checked="confirmDelete"
- class="mr-2"
- />
- <span>
- {{
- existRelatedResource
- ? t("environment.delete-description")
- : t("common.cannot-undo-this-action")
- }}
- </span>
- </div>
- </BBButtonConfirm>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { computedAsync } from "@vueuse/core";
-import { NCheckbox, NColorPicker, NInput } from "naive-ui";
-import { computed, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { BBButtonConfirm } from "@/bbkit";
-import LearnMoreLink from "@/components/LearnMoreLink.vue";
-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
-import RequiredStar from "@/components/RequiredStar.vue";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import {
- hasFeature,
- pushNotification,
- useActuatorV1Store,
- useDatabaseV1Store,
- useEnvironmentV1Store,
- useInstanceV1Store,
-} from "@/store";
-import { environmentNamePrefix } from "@/store/modules/v1/common";
-import { isValidEnvironmentName } from "@/types";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import { hasWorkspacePermissionV2 } from "@/utils";
-import { FeatureBadge } from "../FeatureGuard";
-import SQLReviewForResource from "../SQLReview/components/SQLReviewForResource.vue";
-import { ResourceIdField } from "../v2";
-import { useEnvironmentFormContext } from "./context";
-import RolloutPolicyConfig from "./RolloutPolicyConfig.vue";
-
-withDefaults(
- defineProps<{
- features?: Array<
- "BASE" | "TIER" | "ROLLOUT_POLICY" | "SQL_REVIEW" | "ACCESS_CONTROL"
- >;
- }>(),
- {
- features: () => [
- "BASE",
- "TIER",
- "ROLLOUT_POLICY",
- "SQL_REVIEW",
- "ACCESS_CONTROL",
- ],
- }
-);
-
-const confirmDelete = ref<boolean>(false);
-const { t } = useI18n();
-const {
- create,
- environment,
- state,
- allowEdit,
- valueChanged,
- missingFeature,
- events,
- resourceIdField,
-} = useEnvironmentFormContext();
-const environmentStore = useEnvironmentV1Store();
-const instanceStore = useInstanceV1Store();
-const databaseStore = useDatabaseV1Store();
-const actuatorStore = useActuatorV1Store();
-
-const hasGetPolicyPermission = computed(() => {
- return hasWorkspacePermissionV2("bb.policies.get");
-});
-
-const sqlReviewForResourceRef =
- ref<InstanceType<typeof SQLReviewForResource>>();
-
-const getEnvironmentById = (id: string) => {
- const environment = environmentStore.getEnvironmentByName(
- `${environmentNamePrefix}${id}`,
- false /* not fallback */
- );
- if (!isValidEnvironmentName(environment.name)) {
- return Promise.resolve(undefined);
- }
- return Promise.resolve(environment);
-};
-
-watch(
- () => sqlReviewForResourceRef.value?.isDirty ?? false,
- (isDirty) => {
- if (isDirty) {
- state.value.policyChanged = true;
- } else {
- state.value.policyChanged = false;
- }
- }
-);
-
-const hasEnvironmentPolicyFeature = computed(() =>
- hasFeature(PlanFeature.FEATURE_ENVIRONMENT_TIERS)
-);
-
-const allowArchive = computed(() => {
- return allowEdit.value && environmentStore.environmentList.length > 1;
-});
-
-const fetchInstances = async () => {
- try {
- const resp = await instanceStore.fetchInstanceList({
- pageSize: 1,
- filter: {
- environment: environment.value.name,
- },
- silent: true,
- });
- return resp.instances;
- } catch {
- return [];
- }
-};
-
-const fetchDatabases = async () => {
- try {
- const resp = await databaseStore.fetchDatabases({
- pageSize: 1,
- parent: actuatorStore.workspaceResourceName,
- filter: {
- environment: environment.value.name,
- },
- silent: true,
- });
- return resp.databases;
- } catch {
- return [];
- }
-};
-
-const existRelatedResource = computedAsync(async () => {
- if (create.value) {
- return false;
- }
- if (!allowArchive.value) {
- return false;
- }
-
- const [listInstance, listDatabase] = await Promise.all([
- fetchInstances(),
- fetchDatabases(),
- ]);
- return listInstance.length !== 0 || listDatabase.length !== 0;
-}, false);
-
-const onColorComplete = (color: string) => {
- if (color.toUpperCase() === "#FFFFFF") {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: t("common.warning"),
- description: "Invalid color",
- });
- state.value.environment.color = "#4f46e5";
- }
-};
-
-const onColorUpdate = (color: string) => {
- if (!hasEnvironmentPolicyFeature.value) {
- missingFeature.value = PlanFeature.FEATURE_ENVIRONMENT_TIERS;
- return;
- }
- state.value.environment.color = color;
-};
-
-const deleteEnvironment = () => {
- events.emit("delete", state.value.environment);
-};
-
-useEmitteryEventListener(events, "update-sql-review", async () => {
- if (sqlReviewForResourceRef.value?.isDirty) {
- await sqlReviewForResourceRef.value.update();
- }
-});
-
-useEmitteryEventListener(events, "revert-sql-review", () => {
- sqlReviewForResourceRef.value?.revert();
-});
-</script>
diff --git a/frontend/src/components/EnvironmentForm/RolloutPolicyConfig.vue b/frontend/src/components/EnvironmentForm/RolloutPolicyConfig.vue
deleted file mode 100644
index 14ddd96b37..0000000000
--- a/frontend/src/components/EnvironmentForm/RolloutPolicyConfig.vue
+++ /dev/null
@@ -1,121 +0,0 @@
-<template>
- <div class="flex flex-col items-start gap-y-2">
- <div class="flex flex-col gap-y-2">
- <PermissionGuardWrapper
- v-slot="slotProps"
- :permissions="[
- 'bb.policies.update'
- ]"
- >
- <div class="flex flex-col gap-y-2">
- <RoleSelect
- v-model:value="rolloutPolicy.roles"
- :disabled="slotProps.disabled"
- multiple
- @update:value="updateRoles(rolloutPolicy.roles)"
- />
- </div>
- </PermissionGuardWrapper>
- <div class="w-full inline-flex items-start gap-x-2">
- <PermissionGuardWrapper
- v-slot="slotProps"
- :permissions="[
- 'bb.policies.update'
- ]"
- >
- <Switch
- :value="isAutomaticRolloutChecked"
- :text="true"
- :disabled="slotProps.disabled"
- @update:value="toggleAutomaticRollout($event)"
- />
- </PermissionGuardWrapper>
- <div class="flex flex-col">
- <span class="textlabel">
- {{ t("policy.rollout.auto") }}
- </span>
- <div class="textinfolabel">
- {{ t("policy.rollout.auto-info") }}
- </div>
- </div>
- </div>
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { create } from "@bufbuild/protobuf";
-import { cloneDeep } from "lodash-es";
-import { computed, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
-import type {
- Policy,
- RolloutPolicy,
-} from "@/types/proto-es/v1/org_policy_service_pb";
-import { RolloutPolicySchema } from "@/types/proto-es/v1/org_policy_service_pb";
-import { RoleSelect, Switch } from "../v2";
-
-const { t } = useI18n();
-
-const props = defineProps<{
- policy: Policy;
-}>();
-
-const emit = defineEmits<{
- (event: "update:policy", policy: Policy): void;
-}>();
-
-const rolloutPolicy = ref<RolloutPolicy>(
- cloneDeep(
- props.policy.policy?.case === "rolloutPolicy"
- ? props.policy.policy.value
- : create(RolloutPolicySchema)
- )
-);
-
-const isAutomaticRolloutChecked = computed(() => {
- return rolloutPolicy.value.automatic;
-});
-
-const update = (rp: RolloutPolicy) => {
- emit("update:policy", {
- ...props.policy,
- policy: {
- case: "rolloutPolicy",
- value: rp,
- },
- });
-};
-
-const toggleAutomaticRollout = (selected: boolean) => {
- update(
- create(RolloutPolicySchema, {
- ...rolloutPolicy.value,
- automatic: selected,
- })
- );
-};
-
-const updateRoles = (roles: string[]) => {
- update(
- create(RolloutPolicySchema, {
- ...rolloutPolicy.value,
- roles: roles,
- })
- );
-};
-
-watch(
- () =>
- props.policy.policy?.case === "rolloutPolicy"
- ? props.policy.policy.value
- : undefined,
- (p) => {
- if (p) {
- rolloutPolicy.value = cloneDeep(p);
- }
- },
- { immediate: true, deep: true }
-);
-</script>
diff --git a/frontend/src/components/EnvironmentForm/context.ts b/frontend/src/components/EnvironmentForm/context.ts
deleted file mode 100644
index cf7c487442..0000000000
--- a/frontend/src/components/EnvironmentForm/context.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import Emittery from "emittery";
-import { cloneDeep, isEmpty, isEqual } from "lodash-es";
-import { useDialog } from "naive-ui";
-import type { InjectionKey, Ref } from "vue";
-import { computed, inject, provide, ref, watch } from "vue";
-import type { ResourceIdField } from "@/components/v2";
-import {
- type Policy,
- PolicyType,
-} from "@/types/proto-es/v1/org_policy_service_pb";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import type { Environment } from "@/types/v1/environment";
-import { hasWorkspacePermissionV2 } from "@/utils";
-
-export type LocalState = {
- environment: Environment;
- rolloutPolicy: Policy;
- policyChanged: boolean;
-};
-
-const KEY = Symbol(
- "bb.workspace.Environment-form"
-) as InjectionKey<EnvironmentFormContext>;
-
-export const provideEnvironmentFormContext = (baseContext: {
- create: Ref<boolean>;
- environment: Ref<Environment>;
- rolloutPolicy: Ref<Policy>;
-}) => {
- const $d = useDialog();
- const events = new Emittery<{
- create: {
- environment: Partial<Environment>;
- rolloutPolicy: Policy;
- };
- update: Environment;
- "update-policy": {
- environment: Environment;
- policyType: PolicyType;
- policy: Policy;
- };
- "update-sql-review": undefined;
- "revert-sql-review": undefined;
- delete: Environment;
- cancel: undefined;
- }>();
- const { create, environment, rolloutPolicy } = baseContext;
- const state = ref<LocalState>({
- environment: cloneDeep(environment.value),
- rolloutPolicy: cloneDeep(rolloutPolicy.value),
- policyChanged: false,
- });
- const missingFeature = ref<PlanFeature | undefined>(undefined);
- const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();
-
- const valueChanged = (
- field?: "environment" | "approvalPolicy" | "rolloutPolicy"
- ): boolean => {
- switch (field) {
- case "environment":
- return !isEqual(environment.value, state.value.environment);
- case "rolloutPolicy":
- return !isEqual(rolloutPolicy.value, state.value.rolloutPolicy);
-
- default:
- return (
- !isEqual(environment.value, state.value.environment) ||
- !isEqual(rolloutPolicy.value, state.value.rolloutPolicy) ||
- state.value.policyChanged
- );
- }
- };
-
- const allowCreate = computed(() => {
- return (
- !isEmpty(state.value.environment.title) &&
- resourceIdField.value?.resourceId &&
- resourceIdField.value?.isValidated
- );
- });
-
- const allowEdit = computed(() => {
- return (
- create.value || hasWorkspacePermissionV2("bb.settings.setEnvironment")
- );
- });
-
- watch(environment, (cur) => {
- state.value.environment = cloneDeep(cur);
- });
- watch(rolloutPolicy, (cur) => {
- state.value.rolloutPolicy = cloneDeep(cur);
- });
-
- const context = {
- ...baseContext,
- $d,
- events,
- state,
- missingFeature,
- resourceIdField,
- allowCreate,
- allowEdit,
- valueChanged,
- };
- provide(KEY, context);
-
- return context;
-};
-
-export const useEnvironmentFormContext = () => {
- return inject(KEY)!;
-};
-
-export type EnvironmentFormContext = ReturnType<
- typeof provideEnvironmentFormContext
->;
diff --git a/frontend/src/components/EnvironmentForm/index.ts b/frontend/src/components/EnvironmentForm/index.ts
deleted file mode 100644
index b2a5ded6ed..0000000000
--- a/frontend/src/components/EnvironmentForm/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import Buttons from "./Buttons.vue";
-import EnvironmentForm from "./EnvironmentForm.vue";
-import Form from "./Form.vue";
-
-export * from "./context";
-export { EnvironmentForm, Form, Buttons };
-export default EnvironmentForm;
diff --git a/frontend/src/react/pages/settings/EnvironmentsPage.tsx b/frontend/src/react/pages/settings/EnvironmentsPage.tsx
new file mode 100644
index 0000000000..26dea26aea
--- /dev/null
+++ b/frontend/src/react/pages/settings/EnvironmentsPage.tsx
@@ -0,0 +1,1494 @@
+import { create } from "@bufbuild/protobuf";
+import { cloneDeep, isEqual } from "lodash-es";
+import { GripVertical, ListOrdered, Plus, ShieldAlert, X } from "lucide-react";
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { useTranslation } from "react-i18next";
+import { FeatureAttention } from "@/react/components/FeatureAttention";
+import { ResourceIdField } from "@/react/components/ResourceIdField";
+import { Button } from "@/react/components/ui/button";
+import { Input } from "@/react/components/ui/input";
+import { useVueState } from "@/react/hooks/useVueState";
+import { router } from "@/router";
+import { WORKSPACE_ROUTE_SQL_REVIEW_DETAIL } from "@/router/dashboard/workspaceRoutes";
+import {
+ pushNotification,
+ useActuatorV1Store,
+ useDatabaseV1Store,
+ useEnvironmentV1Store,
+ useInstanceV1Store,
+ useRoleStore,
+ useSQLReviewStore,
+ useSubscriptionV1Store,
+ useUIStateStore,
+} from "@/store";
+import { environmentNamePrefix } from "@/store/modules/v1/common";
+import {
+ getEmptyRolloutPolicy,
+ usePolicyV1Store,
+} from "@/store/modules/v1/policy";
+import {
+ formatEnvironmentName,
+ isValidEnvironmentName,
+ PRESET_PROJECT_ROLES,
+ PRESET_ROLES,
+ PRESET_WORKSPACE_ROLES,
+} from "@/types";
+import type {
+ Policy,
+ RolloutPolicy,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import {
+ PolicyResourceType,
+ PolicySchema,
+ PolicyType,
+ RolloutPolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import type { Environment } from "@/types/v1/environment";
+import {
+ displayRoleTitle,
+ hasWorkspacePermissionV2,
+ hexToRgb,
+ sqlReviewPolicySlug,
+} from "@/utils";
+
+// ============================================================
+// Escape key stack
+// ============================================================
+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]);
+}
+
+// ============================================================
+// EnvironmentName - displays env name with color badge
+// ============================================================
+function EnvironmentName({
+ environment,
+ link = false,
+}: {
+ environment: Environment;
+ link?: boolean;
+}) {
+ const subscriptionStore = useSubscriptionV1Store();
+ const hasEnvTierFeature = useVueState(() =>
+ subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_ENVIRONMENT_TIERS)
+ );
+ const color = environment.color || "#4f46e5";
+ const rgbValues = hexToRgb(color);
+ const rgbStr = rgbValues.join(", ");
+ const showProductionIcon =
+ hasEnvTierFeature && environment.tags?.protected === "protected";
+
+ const content = (
+ <span
+ className="inline-flex items-center gap-x-1 px-1.5 rounded select-none truncate"
+ style={{
+ backgroundColor: `rgba(${rgbStr}, 0.1)`,
+ color: `rgb(${rgbStr})`,
+ }}
+ >
+ <span className="truncate">{environment.title}</span>
+ {showProductionIcon && (
+ <ShieldAlert className="w-3.5 h-3.5 shrink-0 text-control" />
+ )}
+ </span>
+ );
+
+ if (link) {
+ return (
+ <a
+ href={`/${formatEnvironmentName(environment.id)}`}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ router.push({ path: `/${formatEnvironmentName(environment.id)}` });
+ }}
+ className="hover:underline"
+ >
+ {content}
+ </a>
+ );
+ }
+
+ return content;
+}
+
+// ============================================================
+// Toggle switch
+// ============================================================
+function ToggleSwitch({
+ checked,
+ disabled,
+ onChange,
+}: {
+ checked: boolean;
+ disabled?: boolean;
+ onChange: (value: boolean) => void;
+}) {
+ return (
+ <button
+ type="button"
+ role="switch"
+ aria-checked={checked}
+ disabled={disabled}
+ className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 ${
+ checked ? "bg-accent" : "bg-gray-200"
+ }`}
+ onClick={() => onChange(!checked)}
+ >
+ <span
+ className={`pointer-events-none inline-block h-4 w-4 rounded-full bg-white shadow-sm transition-transform ${
+ checked ? "translate-x-4" : "translate-x-0"
+ }`}
+ />
+ </button>
+ );
+}
+
+// ============================================================
+// RolloutPolicyConfig
+// ============================================================
+function RolloutPolicyConfig({
+ policy,
+ onChange,
+}: {
+ policy: Policy;
+ onChange: (policy: Policy) => void;
+}) {
+ const { t } = useTranslation();
+ const roleStore = useRoleStore();
+ const subscriptionStore = useSubscriptionV1Store();
+ const roleList = useVueState(() => [...roleStore.roleList]);
+ const hasCustomRoleFeature = useVueState(() =>
+ subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_CUSTOM_ROLES)
+ );
+ const canUpdatePolicy = hasWorkspacePermissionV2("bb.policies.update");
+
+ const rolloutPolicy: RolloutPolicy =
+ policy.policy?.case === "rolloutPolicy"
+ ? policy.policy.value
+ : create(RolloutPolicySchema);
+
+ const update = (rp: RolloutPolicy) => {
+ onChange({
+ ...policy,
+ policy: {
+ case: "rolloutPolicy",
+ value: rp,
+ },
+ });
+ };
+
+ const toggleAutomatic = (checked: boolean) => {
+ update(
+ create(RolloutPolicySchema, {
+ ...rolloutPolicy,
+ automatic: checked,
+ })
+ );
+ };
+
+ const removeRole = (role: string) => {
+ update(
+ create(RolloutPolicySchema, {
+ ...rolloutPolicy,
+ roles: rolloutPolicy.roles.filter((r) => r !== role),
+ })
+ );
+ };
+
+ const addRole = (role: string) => {
+ if (rolloutPolicy.roles.includes(role)) return;
+ update(
+ create(RolloutPolicySchema, {
+ ...rolloutPolicy,
+ roles: [...rolloutPolicy.roles, role],
+ })
+ );
+ };
+
+ // Available roles grouped
+ const availableRoles = useMemo(() => {
+ const selected = new Set(rolloutPolicy.roles);
+ const groups: {
+ label: string;
+ roles: { name: string; title: string }[];
+ }[] = [];
+
+ const wsRoles = PRESET_WORKSPACE_ROLES.map((name) =>
+ roleStore.getRoleByName(name)
+ )
+ .filter((r) => r && !selected.has(r.name))
+ .map((r) => ({ name: r!.name, title: displayRoleTitle(r!.name) }));
+ if (wsRoles.length > 0) {
+ groups.push({ label: t("role.workspace-roles.self"), roles: wsRoles });
+ }
+
+ const projRoles = PRESET_PROJECT_ROLES.map((name) =>
+ roleStore.getRoleByName(name)
+ )
+ .filter((r) => r && !selected.has(r.name))
+ .map((r) => ({ name: r!.name, title: displayRoleTitle(r!.name) }));
+ if (projRoles.length > 0) {
+ groups.push({ label: t("role.project-roles.self"), roles: projRoles });
+ }
+
+ if (hasCustomRoleFeature) {
+ const customRoles = roleList
+ .filter((r) => !PRESET_ROLES.includes(r.name) && !selected.has(r.name))
+ .map((r) => ({ name: r.name, title: displayRoleTitle(r.name) }));
+ if (customRoles.length > 0) {
+ groups.push({
+ label: t("role.custom-roles.self"),
+ roles: customRoles,
+ });
+ }
+ }
+
+ return groups;
+ }, [roleList, rolloutPolicy.roles, roleStore, t]);
+
+ const [showRoleDropdown, setShowRoleDropdown] = useState(false);
+ const dropdownRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!showRoleDropdown) return;
+ const handler = (e: MouseEvent) => {
+ if (
+ dropdownRef.current &&
+ !dropdownRef.current.contains(e.target as Node)
+ ) {
+ setShowRoleDropdown(false);
+ }
+ };
+ document.addEventListener("mousedown", handler);
+ return () => document.removeEventListener("mousedown", handler);
+ }, [showRoleDropdown]);
+
+ return (
+ <div className="flex flex-col items-start gap-y-2">
+ <div className="flex flex-col gap-y-2">
+ {/* Role select */}
+ <div className="flex flex-wrap items-center gap-2">
+ {rolloutPolicy.roles.map((role) => (
+ <span
+ key={role}
+ className="inline-flex items-center gap-x-1 rounded-md bg-gray-100 px-2 py-1 text-sm"
+ >
+ {displayRoleTitle(role)}
+ {canUpdatePolicy && (
+ <button
+ type="button"
+ className="text-gray-400 hover:text-gray-600"
+ onClick={() => removeRole(role)}
+ >
+ <X className="w-3.5 h-3.5" />
+ </button>
+ )}
+ </span>
+ ))}
+ {canUpdatePolicy && (
+ <div className="relative" ref={dropdownRef}>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setShowRoleDropdown(!showRoleDropdown)}
+ >
+ <Plus className="w-3.5 h-3.5 mr-1" />
+ {t("common.add")}
+ </Button>
+ {showRoleDropdown && (
+ <div className="absolute z-50 mt-1 w-64 max-h-60 overflow-auto rounded-md border border-control-border bg-white py-1 shadow-md">
+ {availableRoles.map((group) => (
+ <div key={group.label}>
+ <div className="px-2 py-1 text-xs font-semibold text-gray-500 uppercase">
+ {group.label}
+ </div>
+ {group.roles.map((role) => (
+ <button
+ key={role.name}
+ type="button"
+ className="w-full text-left px-3 py-1.5 text-sm hover:bg-control-bg cursor-pointer"
+ onClick={() => {
+ addRole(role.name);
+ setShowRoleDropdown(false);
+ }}
+ >
+ {role.title}
+ </button>
+ ))}
+ </div>
+ ))}
+ {availableRoles.length === 0 && (
+ <div className="px-3 py-2 text-sm text-gray-400">
+ {t("common.no-data")}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Auto rollout toggle */}
+ <div className="w-full inline-flex items-start gap-x-2">
+ <ToggleSwitch
+ checked={rolloutPolicy.automatic}
+ disabled={!canUpdatePolicy}
+ onChange={toggleAutomatic}
+ />
+ <div className="flex flex-col">
+ <span className="textlabel">{t("policy.rollout.auto")}</span>
+ <div className="textinfolabel">{t("policy.rollout.auto-info")}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// ============================================================
+// SQLReviewSection
+// ============================================================
+interface SQLReviewSectionRef {
+ save: () => Promise<void>;
+ revert: () => void;
+}
+
+function SQLReviewSectionInner(
+ {
+ environmentId,
+ onDirtyChange,
+ }: { environmentId: string; onDirtyChange: (dirty: boolean) => void },
+ ref: React.ForwardedRef<SQLReviewSectionRef>
+) {
+ const { t } = useTranslation();
+ const reviewStore = useSQLReviewStore();
+ const resourcePath = `${environmentNamePrefix}${environmentId}`;
+
+ const canGetReviewConfig = hasWorkspacePermissionV2("bb.reviewConfigs.get");
+ const canGetPolicy = hasWorkspacePermissionV2("bb.policies.get");
+ const canUpdateReviewConfig = hasWorkspacePermissionV2(
+ "bb.reviewConfigs.update"
+ );
+ const canUpdatePolicy = hasWorkspacePermissionV2("bb.policies.update");
+
+ const reviewPolicyList = useVueState(() => [...reviewStore.reviewPolicyList]);
+
+ const currentPolicy = useMemo(() => {
+ return reviewPolicyList.find((p) => p.resources.includes(resourcePath));
+ }, [reviewPolicyList, resourcePath]);
+
+ const [pendingPolicy, setPendingPolicy] = useState(currentPolicy);
+ const [enforce, setEnforce] = useState(currentPolicy?.enforce ?? false);
+ const [showSelectPanel, setShowSelectPanel] = useState(false);
+ const selectPanelRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!showSelectPanel) return;
+ const handler = (e: MouseEvent) => {
+ if (
+ selectPanelRef.current &&
+ !selectPanelRef.current.contains(e.target as Node)
+ ) {
+ setShowSelectPanel(false);
+ }
+ };
+ document.addEventListener("mousedown", handler);
+ return () => document.removeEventListener("mousedown", handler);
+ }, [showSelectPanel]);
+
+ useEffect(() => {
+ setPendingPolicy(currentPolicy);
+ setEnforce(currentPolicy?.enforce ?? false);
+ }, [currentPolicy]);
+
+ // Fetch the full review policy list and the current resource's policy on mount
+ useEffect(() => {
+ reviewStore.fetchReviewPolicyList();
+ reviewStore.getOrFetchReviewPolicyByResource(resourcePath, true);
+ }, [resourcePath, reviewStore]);
+
+ const isDirty =
+ enforce !== (currentPolicy?.enforce ?? false) ||
+ !isEqual(pendingPolicy, currentPolicy);
+
+ useEffect(() => {
+ onDirtyChange(isDirty);
+ }, [isDirty, onDirtyChange]);
+
+ const saveSQLReview = useCallback(async () => {
+ if (!isEqual(currentPolicy, pendingPolicy)) {
+ if (currentPolicy) {
+ await reviewStore.upsertReviewConfigTag({
+ oldResources: [...currentPolicy.resources],
+ newResources: currentPolicy.resources.filter(
+ (r) => r !== resourcePath
+ ),
+ review: currentPolicy.id,
+ });
+ }
+ if (pendingPolicy) {
+ await reviewStore.upsertReviewConfigTag({
+ oldResources: [...pendingPolicy.resources],
+ newResources: [...pendingPolicy.resources, resourcePath],
+ review: pendingPolicy.id,
+ });
+ }
+ }
+ if (pendingPolicy && pendingPolicy.enforce !== enforce) {
+ await reviewStore.upsertReviewPolicy({
+ id: pendingPolicy.id,
+ enforce,
+ });
+ }
+ }, [currentPolicy, pendingPolicy, enforce, resourcePath, reviewStore]);
+
+ const revertSQLReview = useCallback(() => {
+ setPendingPolicy(currentPolicy);
+ setEnforce(currentPolicy?.enforce ?? false);
+ }, [currentPolicy]);
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ save: saveSQLReview,
+ revert: revertSQLReview,
+ }),
+ [saveSQLReview, revertSQLReview]
+ );
+
+ if (!canGetReviewConfig || !canGetPolicy) return null;
+
+ return (
+ <div className="flex flex-col gap-y-2">
+ <div className="flex items-center gap-x-2">
+ <label className="font-medium">{t("sql-review.title")}</label>
+ </div>
+ <div>
+ {pendingPolicy ? (
+ <div className="inline-flex items-center gap-x-2">
+ <ToggleSwitch
+ checked={enforce}
+ disabled={!canUpdateReviewConfig}
+ onChange={setEnforce}
+ />
+ <div className="flex items-center gap-x-1">
+ <span
+ className="textlabel normal-link text-accent! cursor-pointer"
+ onClick={() => {
+ router.push({
+ name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
+ params: {
+ sqlReviewPolicySlug: sqlReviewPolicySlug(pendingPolicy),
+ },
+ });
+ }}
+ >
+ {pendingPolicy.name}
+ </span>
+ {canUpdatePolicy && (
+ <button
+ type="button"
+ className="p-0.5 text-gray-400 hover:text-gray-600"
+ onClick={() => {
+ setPendingPolicy(undefined);
+ setEnforce(false);
+ }}
+ >
+ <X className="w-4 h-4" />
+ </button>
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="relative" ref={selectPanelRef}>
+ <Button
+ variant="outline"
+ disabled={!canUpdatePolicy}
+ onClick={() => setShowSelectPanel(!showSelectPanel)}
+ >
+ {t("sql-review.configure-policy")}
+ </Button>
+ {showSelectPanel && (
+ <div className="absolute z-50 mt-1 w-80 max-h-60 overflow-auto rounded-md border border-control-border bg-white py-1 shadow-md">
+ {reviewPolicyList.length === 0 ? (
+ <div className="px-3 py-2 text-sm text-gray-400">
+ {t("common.no-data")}
+ </div>
+ ) : (
+ reviewPolicyList.map((review) => (
+ <button
+ key={review.id}
+ type="button"
+ className="w-full text-left px-3 py-2 text-sm hover:bg-control-bg cursor-pointer"
+ onClick={() => {
+ setPendingPolicy(review);
+ setEnforce(true);
+ setShowSelectPanel(false);
+ }}
+ >
+ <div className="font-medium">{review.name}</div>
+ </button>
+ ))
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+const SQLReviewSection = forwardRef(SQLReviewSectionInner);
+
+// ============================================================
+// EnvironmentDetail - detail panel for a single environment
+// ============================================================
+function EnvironmentDetail({
+ environment,
+ onDelete,
+ onDirtyChange: onDetailDirtyChange,
+}: {
+ environment: Environment;
+ onDelete: (env: Environment) => void;
+ onDirtyChange: (dirty: boolean) => void;
+}) {
+ const { t } = useTranslation();
+ const environmentStore = useEnvironmentV1Store();
+ const policyStore = usePolicyV1Store();
+ const subscriptionStore = useSubscriptionV1Store();
+
+ const canEdit = hasWorkspacePermissionV2("bb.settings.setEnvironment");
+ const canGetPolicy = hasWorkspacePermissionV2("bb.policies.get");
+
+ const sqlReviewRef = useRef<SQLReviewSectionRef>(null);
+
+ // Local editing state
+ const [editTitle, setEditTitle] = useState(environment.title);
+ const [editColor, setEditColor] = useState(environment.color || "#4f46e5");
+ const [editProtected, setEditProtected] = useState(
+ environment.tags?.protected === "protected"
+ );
+ const [rolloutPolicy, setRolloutPolicy] = useState<Policy | null>(null);
+ const [originalRolloutPolicy, setOriginalRolloutPolicy] =
+ useState<Policy | null>(null);
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
+ const [existRelatedResource, setExistRelatedResource] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const [sqlReviewDirty, setSqlReviewDirty] = useState(false);
+
+ const hasEnvironmentTiers = useVueState(() =>
+ subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_ENVIRONMENT_TIERS)
+ );
+
+ const environmentList = useVueState(() => [
+ ...environmentStore.environmentList,
+ ]);
+
+ // Reset state when environment changes
+ useEffect(() => {
+ setEditTitle(environment.title);
+ setEditColor(environment.color || "#4f46e5");
+ setEditProtected(environment.tags?.protected === "protected");
+ setShowDeleteConfirm(false);
+ }, [environment.id, environment.title, environment.color, environment.tags]);
+
+ // Fetch rollout policy
+ useEffect(() => {
+ const fetchPolicy = async () => {
+ const envName = formatEnvironmentName(environment.id);
+ const policy = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: envName,
+ policyType: PolicyType.ROLLOUT_POLICY,
+ });
+ const result =
+ policy ??
+ create(PolicySchema, {
+ policy: {
+ case: "rolloutPolicy",
+ value: create(RolloutPolicySchema, {}),
+ },
+ });
+ setRolloutPolicy(result);
+ setOriginalRolloutPolicy(cloneDeep(result));
+ };
+ fetchPolicy();
+ }, [environment.id, policyStore]);
+
+ // Check for related resources (instances/databases)
+ const instanceStore = useInstanceV1Store();
+ const databaseStore = useDatabaseV1Store();
+ const actuatorStore = useActuatorV1Store();
+
+ useEffect(() => {
+ const checkRelatedResources = async () => {
+ if (!canEdit || environmentList.length <= 1) {
+ setExistRelatedResource(false);
+ return;
+ }
+ try {
+ const [instResp, dbResp] = await Promise.all([
+ instanceStore.fetchInstanceList({
+ pageSize: 1,
+ filter: { environment: environment.name },
+ silent: true,
+ }),
+ databaseStore.fetchDatabases({
+ pageSize: 1,
+ parent: actuatorStore.workspaceResourceName,
+ filter: { environment: environment.name },
+ silent: true,
+ }),
+ ]);
+ setExistRelatedResource(
+ instResp.instances.length > 0 || dbResp.databases.length > 0
+ );
+ } catch {
+ setExistRelatedResource(false);
+ }
+ };
+ checkRelatedResources();
+ }, [
+ environment.id,
+ environment.name,
+ canEdit,
+ environmentList.length,
+ instanceStore,
+ databaseStore,
+ actuatorStore,
+ ]);
+
+ const envChanged = useMemo(() => {
+ return (
+ editTitle !== environment.title ||
+ editColor !== (environment.color || "#4f46e5") ||
+ editProtected !== (environment.tags?.protected === "protected")
+ );
+ }, [editTitle, editColor, editProtected, environment]);
+
+ const policyChanged = useMemo(() => {
+ if (!rolloutPolicy || !originalRolloutPolicy) return false;
+ return !isEqual(rolloutPolicy, originalRolloutPolicy);
+ }, [rolloutPolicy, originalRolloutPolicy]);
+
+ const hasChanges = envChanged || policyChanged || sqlReviewDirty;
+
+ useEffect(() => {
+ onDetailDirtyChange(hasChanges);
+ }, [hasChanges, onDetailDirtyChange]);
+
+ const revert = () => {
+ setEditTitle(environment.title);
+ setEditColor(environment.color || "#4f46e5");
+ setEditProtected(environment.tags?.protected === "protected");
+ if (originalRolloutPolicy) {
+ setRolloutPolicy(cloneDeep(originalRolloutPolicy));
+ }
+ sqlReviewRef.current?.revert();
+ };
+
+ const save = async () => {
+ // Check feature gate for production tier
+ if (editProtected && !hasEnvironmentTiers) {
+ return;
+ }
+
+ // Update environment if changed
+ if (envChanged) {
+ const newTags = { ...environment.tags };
+ newTags.protected = editProtected ? "protected" : "unprotected";
+ const updated = await environmentStore.updateEnvironment({
+ ...environment,
+ title: editTitle,
+ color: editColor,
+ tags: newTags,
+ });
+ // Sync local state to the saved values so hasChanges becomes false
+ setEditTitle(updated.title);
+ setEditColor(updated.color || "#4f46e5");
+ setEditProtected(updated.tags?.protected === "protected");
+ }
+
+ // Update rollout policy if changed
+ if (policyChanged && rolloutPolicy) {
+ await policyStore.upsertPolicy({
+ parentPath: formatEnvironmentName(environment.id),
+ policy: rolloutPolicy,
+ });
+ setOriginalRolloutPolicy(cloneDeep(rolloutPolicy));
+ }
+
+ // Save SQL review changes
+ if (sqlReviewDirty) {
+ await sqlReviewRef.current?.save();
+ setSqlReviewDirty(false);
+ }
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("environment.successfully-updated-environment", {
+ name: editTitle,
+ }),
+ });
+ };
+
+ const onColorChange = (color: string) => {
+ if (!hasEnvironmentTiers) {
+ return;
+ }
+ if (color.toUpperCase() === "#FFFFFF") {
+ pushNotification({
+ module: "bytebase",
+ style: "WARN",
+ title: t("common.warning"),
+ description: "Invalid color",
+ });
+ setEditColor("#4f46e5");
+ return;
+ }
+ setEditColor(color);
+ };
+
+ const allowDelete = canEdit && environmentList.length > 1;
+
+ return (
+ <div className="flex flex-col h-full w-full">
+ <div className="flex-1 px-4">
+ <div className="flex flex-col gap-y-6">
+ {/* Name section */}
+ <div className="flex flex-col gap-y-2">
+ <div className="flex items-center gap-x-2">
+ <input
+ type="color"
+ value={editColor}
+ disabled={!canEdit}
+ onChange={(e) => onColorChange(e.target.value)}
+ className="w-5 h-5 rounded-sm cursor-pointer border-0 p-0"
+ />
+ <span className="font-medium">
+ {t("common.environment-name")}
+ <span className="ml-0.5 text-error">*</span>
+ </span>
+ </div>
+ <Input
+ value={editTitle}
+ disabled={!canEdit}
+ onChange={(e) => setEditTitle(e.target.value)}
+ />
+ <ResourceIdField
+ value={environment.id}
+ resourceType="environment"
+ resourceName={t("common.environment")}
+ readonly
+ />
+ </div>
+
+ {/* Tier section */}
+ <div className="flex flex-col gap-y-2">
+ <div className="gap-y-1">
+ <label className="font-medium flex items-center">
+ {t("policy.environment-tier.name")}
+ </label>
+ <p className="text-sm text-gray-600">
+ {t("policy.environment-tier.description", { newline: "\n" })}
+ <a
+ href="https://docs.bytebase.com/change-database/environment-policy/overview/?source=console#environment-tier"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="ml-1 text-accent hover:underline"
+ >
+ {t("common.learn-more")}
+ </a>
+ </p>
+ </div>
+ <label className="inline-flex items-center gap-x-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={editProtected}
+ disabled={!canEdit}
+ onChange={(e) => setEditProtected(e.target.checked)}
+ className="rounded border-gray-300"
+ />
+ <span className="text-sm">
+ {t("policy.environment-tier.mark-env-as-production")}
+ </span>
+ </label>
+ {editProtected && !hasEnvironmentTiers && (
+ <FeatureAttention
+ feature={PlanFeature.FEATURE_ENVIRONMENT_TIERS}
+ />
+ )}
+ </div>
+
+ {/* Rollout policy section */}
+ {canGetPolicy && rolloutPolicy && (
+ <div className="flex flex-col gap-y-2">
+ <div className="gap-y-1">
+ <div className="flex items-baseline gap-x-2">
+ <label className="font-medium">
+ {t("policy.rollout.name")}
+ </label>
+ {policyChanged && (
+ <span className="textlabeltip">
+ {t("policy.rollout.tip")}
+ </span>
+ )}
+ </div>
+ <div className="textinfolabel">
+ {t("policy.rollout.info", {
+ permission: "bb.taskRuns.create",
+ })}
+ <a
+ href="https://docs.bytebase.com/change-database/environment-policy/rollout-policy/?source=console"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="ml-1 text-accent hover:underline"
+ >
+ {t("common.learn-more")}
+ </a>
+ </div>
+ </div>
+ <RolloutPolicyConfig
+ policy={rolloutPolicy}
+ onChange={setRolloutPolicy}
+ />
+ </div>
+ )}
+
+ {/* SQL Review section */}
+ <SQLReviewSection
+ ref={sqlReviewRef}
+ environmentId={environment.id}
+ onDirtyChange={setSqlReviewDirty}
+ />
+
+ {/* Delete section */}
+ {allowDelete && (
+ <div className="mt-6 border-t border-block-border flex justify-between items-center pt-4 pb-2">
+ <Button
+ variant="destructive"
+ onClick={() => setShowDeleteConfirm(true)}
+ >
+ {t("environment.delete")}
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Sticky bottom buttons */}
+ {canEdit && hasChanges && (
+ <div className="sticky bottom-0 bg-white py-2 px-2 border-t border-block-border flex items-center justify-between gap-x-2">
+ <Button variant="outline" onClick={revert}>
+ {t("common.cancel")}
+ </Button>
+ <Button onClick={save}>{t("common.confirm-and-update")}</Button>
+ </div>
+ )}
+
+ {/* Delete confirmation dialog */}
+ {showDeleteConfirm && (
+ <>
+ <div
+ className="fixed inset-0 z-40 bg-black/30"
+ onClick={() => setShowDeleteConfirm(false)}
+ />
+ <div className="fixed inset-0 z-50 flex items-center justify-center">
+ <div className="bg-white rounded-lg shadow-xl p-6 max-w-md w-full mx-4">
+ <h3 className="text-lg font-medium mb-2">
+ {t("environment.delete")} '{editTitle}'?
+ </h3>
+ <div className="mt-3">
+ {existRelatedResource && (
+ <label className="flex items-start gap-x-2 mb-2">
+ <input
+ type="checkbox"
+ checked={confirmDelete}
+ onChange={(e) => setConfirmDelete(e.target.checked)}
+ className="mt-0.5 rounded border-gray-300"
+ />
+ <span className="text-sm text-gray-600">
+ {t("environment.delete-description")}
+ </span>
+ </label>
+ )}
+ {!existRelatedResource && (
+ <span className="text-sm text-gray-600">
+ {t("common.cannot-undo-this-action")}
+ </span>
+ )}
+ </div>
+ <div className="flex justify-end gap-x-2 mt-4">
+ <Button
+ variant="outline"
+ onClick={() => {
+ setShowDeleteConfirm(false);
+ setConfirmDelete(false);
+ }}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={existRelatedResource && !confirmDelete}
+ onClick={() => {
+ setShowDeleteConfirm(false);
+ setConfirmDelete(false);
+ onDelete(environment);
+ }}
+ >
+ {t("common.delete")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+// ============================================================
+// CreateDrawer
+// ============================================================
+function CreateDrawer({
+ onClose,
+ onCreate,
+}: {
+ onClose: () => void;
+ onCreate: (params: {
+ environment: Partial<Environment>;
+ rolloutPolicy: Policy;
+ }) => void;
+}) {
+ const { t } = useTranslation();
+ useEscapeKey(onClose);
+ const subscriptionStore = useSubscriptionV1Store();
+ const environmentStore = useEnvironmentV1Store();
+
+ const hasEnvironmentTiers = useVueState(() =>
+ subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_ENVIRONMENT_TIERS)
+ );
+
+ const [title, setTitle] = useState("");
+ const [color, setColor] = useState("#4f46e5");
+ const [isProtected, setIsProtected] = useState(false);
+ const [rolloutPolicy, setRolloutPolicy] = useState<Policy>(
+ getEmptyRolloutPolicy("", PolicyResourceType.ENVIRONMENT)
+ );
+ const [resourceId, setResourceId] = useState("");
+ const [resourceIdValid, setResourceIdValid] = useState(false);
+
+ const canCreate = useMemo(() => {
+ return title.trim().length > 0 && resourceId.length > 0 && resourceIdValid;
+ }, [title, resourceId, resourceIdValid]);
+
+ const handleCreate = () => {
+ if (!canCreate) return;
+ if (isProtected && !hasEnvironmentTiers) return;
+
+ const tags: Record<string, string> = {};
+ tags.protected = isProtected ? "protected" : "unprotected";
+
+ onCreate({
+ environment: {
+ id: resourceId,
+ title: title.trim(),
+ color,
+ tags,
+ order: 0,
+ },
+ rolloutPolicy,
+ });
+ };
+
+ const validateResourceId = useCallback(
+ async (id: string) => {
+ const env = environmentStore.getEnvironmentByName(
+ `${environmentNamePrefix}${id}`,
+ false
+ );
+ if (isValidEnvironmentName(env.name)) {
+ return [
+ {
+ type: "error" as const,
+ message: t("resource-id.validation.duplicated", {
+ resource: t("common.environment"),
+ }),
+ },
+ ];
+ }
+ return [];
+ },
+ [environmentStore, t]
+ );
+
+ const onColorChange = (newColor: string) => {
+ if (newColor.toUpperCase() === "#FFFFFF") {
+ pushNotification({
+ module: "bytebase",
+ style: "WARN",
+ title: t("common.warning"),
+ description: "Invalid color",
+ });
+ setColor("#4f46e5");
+ return;
+ }
+ setColor(newColor);
+ };
+
+ return (
+ <>
+ <div className="fixed inset-0 z-40 bg-black/30" onClick={onClose} />
+ <div className="fixed inset-y-0 right-0 z-50 w-xl max-w-[100vw] bg-white shadow-xl flex flex-col">
+ <div className="flex items-center justify-between px-6 py-4 border-b">
+ <h2 className="text-lg font-medium">{t("environment.create")}</h2>
+ <Button variant="ghost" size="icon" onClick={onClose}>
+ <X className="h-5 w-5" />
+ </Button>
+ </div>
+
+ <div className="flex-1 overflow-auto px-6 py-6">
+ <div className="flex flex-col gap-y-6">
+ {/* Name */}
+ <div className="flex flex-col gap-y-2">
+ <div className="flex items-center gap-x-2">
+ <input
+ type="color"
+ value={color}
+ onChange={(e) => onColorChange(e.target.value)}
+ className="w-5 h-5 rounded-sm cursor-pointer border-0 p-0"
+ />
+ <span className="font-medium">
+ {t("common.environment-name")}
+ <span className="ml-0.5 text-error">*</span>
+ </span>
+ </div>
+ <Input
+ value={title}
+ onChange={(e) => setTitle(e.target.value)}
+ autoFocus
+ />
+ <ResourceIdField
+ value={resourceId}
+ resourceType="environment"
+ resourceName={t("common.environment")}
+ resourceTitle={title}
+ validate={validateResourceId}
+ onChange={setResourceId}
+ onValidationChange={setResourceIdValid}
+ />
+ </div>
+
+ {/* Tier */}
+ <div className="flex flex-col gap-y-2">
+ <label className="font-medium">
+ {t("policy.environment-tier.name")}
+ </label>
+ <p className="text-sm text-gray-600">
+ {t("policy.environment-tier.description", { newline: "\n" })}
+ </p>
+ <label className="inline-flex items-center gap-x-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={isProtected}
+ onChange={(e) => setIsProtected(e.target.checked)}
+ className="rounded border-gray-300"
+ />
+ <span className="text-sm">
+ {t("policy.environment-tier.mark-env-as-production")}
+ </span>
+ </label>
+ {isProtected && !hasEnvironmentTiers && (
+ <FeatureAttention
+ feature={PlanFeature.FEATURE_ENVIRONMENT_TIERS}
+ />
+ )}
+ </div>
+
+ {/* Rollout Policy */}
+ <div className="flex flex-col gap-y-2">
+ <div className="gap-y-1">
+ <label className="font-medium">
+ {t("policy.rollout.name")}
+ </label>
+ <div className="textinfolabel">
+ {t("policy.rollout.info", {
+ permission: "bb.taskRuns.create",
+ })}
+ </div>
+ </div>
+ <RolloutPolicyConfig
+ policy={rolloutPolicy}
+ onChange={setRolloutPolicy}
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex justify-end items-center gap-x-2 px-6 py-4 border-t">
+ <Button variant="outline" onClick={onClose}>
+ {t("common.cancel")}
+ </Button>
+ <Button disabled={!canCreate} onClick={handleCreate}>
+ {t("common.create")}
+ </Button>
+ </div>
+ </div>
+ </>
+ );
+}
+
+// ============================================================
+// ReorderDrawer
+// ============================================================
+function ReorderDrawer({
+ environments,
+ onClose,
+ onConfirm,
+}: {
+ environments: Environment[];
+ onClose: () => void;
+ onConfirm: (reordered: Environment[]) => void;
+}) {
+ const { t } = useTranslation();
+ useEscapeKey(onClose);
+ const [list, setList] = useState(() => [...environments]);
+ const [dragIndex, setDragIndex] = useState<number | null>(null);
+
+ const orderChanged = useMemo(() => {
+ for (let i = 0; i < list.length; i++) {
+ if (list[i].id !== environments[i].id) return true;
+ }
+ return false;
+ }, [list, environments]);
+
+ const onDragStart = (index: number) => {
+ setDragIndex(index);
+ };
+
+ const onDragOver = (e: React.DragEvent, index: number) => {
+ e.preventDefault();
+ if (dragIndex === null || dragIndex === index) return;
+ const newList = [...list];
+ const [item] = newList.splice(dragIndex, 1);
+ newList.splice(index, 0, item);
+ setList(newList);
+ setDragIndex(index);
+ };
+
+ return (
+ <>
+ <div className="fixed inset-0 z-40 bg-black/30" onClick={onClose} />
+ <div className="fixed inset-y-0 right-0 z-50 w-120 max-w-[90vw] bg-white shadow-xl flex flex-col">
+ <div className="flex items-center justify-between px-6 py-4 border-b">
+ <h2 className="text-lg font-medium">{t("environment.reorder")}</h2>
+ <Button variant="ghost" size="icon" onClick={onClose}>
+ <X className="h-5 w-5" />
+ </Button>
+ </div>
+
+ <div className="flex-1 overflow-auto px-6 py-4">
+ {list.map((env, index) => (
+ <div
+ key={env.id}
+ draggable
+ onDragStart={() => onDragStart(index)}
+ onDragOver={(e) => onDragOver(e, index)}
+ onDragEnd={() => setDragIndex(null)}
+ className={`flex items-center justify-between p-2 hover:bg-gray-100 rounded-xs cursor-grab ${
+ dragIndex === index ? "opacity-50" : ""
+ }`}
+ >
+ <div className="flex items-center gap-x-2">
+ <span className="textinfo">{index + 1}.</span>
+ <EnvironmentName environment={env} />
+ </div>
+ <GripVertical className="w-5 h-5 text-gray-500" />
+ </div>
+ ))}
+ </div>
+
+ <div className="flex justify-end items-center gap-x-2 px-6 py-4 border-t">
+ <Button variant="outline" onClick={onClose}>
+ {t("common.cancel")}
+ </Button>
+ <Button disabled={!orderChanged} onClick={() => onConfirm(list)}>
+ {t("common.confirm")}
+ </Button>
+ </div>
+ </div>
+ </>
+ );
+}
+
+// ============================================================
+// Main Page
+// ============================================================
+export function EnvironmentsPage() {
+ const { t } = useTranslation();
+ const environmentStore = useEnvironmentV1Store();
+ const policyStore = usePolicyV1Store();
+ const uiStateStore = useUIStateStore();
+
+ const environmentList = useVueState(() => [
+ ...environmentStore.environmentList,
+ ]);
+
+ const [selectedId, setSelectedId] = useState("");
+ const [showCreate, setShowCreate] = useState(false);
+ const [showReorder, setShowReorder] = useState(false);
+ const [detailDirty, setDetailDirty] = useState(false);
+ const detailDirtyRef = useRef(false);
+ // Keep ref in sync so event handlers always see the latest value
+ detailDirtyRef.current = detailDirty;
+
+ const canEdit = hasWorkspacePermissionV2("bb.settings.setEnvironment");
+
+ // Initialize selected tab and intro state
+ useEffect(() => {
+ if (!uiStateStore.getIntroStateByKey("environment.visit")) {
+ uiStateStore.saveIntroStateByKey({
+ key: "environment.visit",
+ newState: true,
+ });
+ }
+ }, [uiStateStore]);
+
+ // Select from hash or default to first
+ useEffect(() => {
+ const hash = window.location.hash.slice(1);
+ if (environmentList.length > 0) {
+ const found = environmentList.find((e) => e.id === hash);
+ if (found) {
+ setSelectedId(found.id);
+ } else {
+ setSelectedId((prev) =>
+ prev && environmentList.find((e) => e.id === prev)
+ ? prev
+ : environmentList[0].id
+ );
+ }
+ }
+ }, [environmentList]);
+
+ // Listen for hash changes
+ useEffect(() => {
+ const onHashChange = () => {
+ const hash = window.location.hash.slice(1);
+ if (hash && environmentList.find((e) => e.id === hash)) {
+ if (detailDirtyRef.current) {
+ if (!window.confirm(t("common.leave-without-saving"))) {
+ return;
+ }
+ }
+ setSelectedId(hash);
+ setDetailDirty(false);
+ }
+ };
+ window.addEventListener("hashchange", onHashChange);
+ return () => window.removeEventListener("hashchange", onHashChange);
+ }, [environmentList, t]);
+
+ // Guard browser refresh/close
+ useEffect(() => {
+ const handler = (e: BeforeUnloadEvent) => {
+ if (detailDirtyRef.current) {
+ e.preventDefault();
+ }
+ };
+ window.addEventListener("beforeunload", handler);
+ return () => window.removeEventListener("beforeunload", handler);
+ }, []);
+
+ // Guard Vue router navigation (sidebar links, etc.)
+ useEffect(() => {
+ const removeGuard = router.beforeEach((_to, _from, next) => {
+ if (detailDirtyRef.current) {
+ if (!window.confirm(t("common.leave-without-saving"))) {
+ next(false);
+ return;
+ }
+ }
+ next();
+ });
+ return removeGuard;
+ }, [t]);
+
+ const selectTab = (id: string) => {
+ if (id === selectedId) return;
+ if (detailDirty) {
+ if (!window.confirm(t("common.leave-without-saving"))) {
+ return;
+ }
+ }
+ setDetailDirty(false);
+ setSelectedId(id);
+ const currentRoute = router.currentRoute.value;
+ router.replace({
+ name: currentRoute.name ?? undefined,
+ hash: `#${id}`,
+ });
+ };
+
+ const selectedEnvironment = useMemo(() => {
+ return environmentList.find((e) => e.id === selectedId);
+ }, [environmentList, selectedId]);
+
+ const handleCreate = async (params: {
+ environment: Partial<Environment>;
+ rolloutPolicy: Policy;
+ }) => {
+ const { environment, rolloutPolicy } = params;
+ const DEFAULT_POLICY = getEmptyRolloutPolicy(
+ "",
+ PolicyResourceType.ENVIRONMENT
+ );
+ const createdEnvironment = await environmentStore.createEnvironment({
+ id: environment.id,
+ title: environment.title,
+ order: environmentList.length,
+ color: environment.color,
+ tags: environment.tags,
+ });
+
+ const isCustomized = !isEqual(rolloutPolicy, DEFAULT_POLICY);
+ if (isCustomized) {
+ await policyStore.upsertPolicy({
+ parentPath: `${environmentNamePrefix}${createdEnvironment.id}`,
+ policy: rolloutPolicy,
+ });
+ }
+
+ setShowCreate(false);
+ selectTab(createdEnvironment.id);
+ };
+
+ const handleDelete = async (environment: Environment) => {
+ await environmentStore.deleteEnvironment(
+ formatEnvironmentName(environment.id)
+ );
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.deleted"),
+ });
+ // Select first remaining environment
+ const remaining = environmentStore.environmentList;
+ if (remaining.length > 0) {
+ selectTab(remaining[0].id);
+ }
+ };
+
+ const handleReorder = async (reordered: Environment[]) => {
+ await environmentStore.reorderEnvironmentList(reordered);
+ setShowReorder(false);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ };
+
+ return (
+ <div className="py-4 w-full h-full flex flex-col gap-4">
+ {/* Tabs header */}
+ <div className="flex items-center border-b border-control-border">
+ <div className="flex-1 flex overflow-x-auto">
+ {environmentList.map((env, index) => (
+ <button
+ key={env.id}
+ type="button"
+ className={`relative flex items-center gap-x-2 px-4 pb-2 pt-1 text-sm font-medium whitespace-nowrap cursor-pointer transition-colors ${
+ selectedId === env.id
+ ? "text-accent after:absolute after:inset-x-0 after:bottom-[-1px] after:h-0.5 after:bg-accent"
+ : "text-control-light hover:text-control"
+ }`}
+ onClick={() => selectTab(env.id)}
+ >
+ <span className="text-opacity-60">{index + 1}.</span>
+ <EnvironmentName environment={env} />
+ </button>
+ ))}
+ </div>
+
+ {/* Toolbar */}
+ {canEdit && (
+ <div className="flex items-center justify-end gap-x-2 px-2 pb-1 shrink-0">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={environmentList.length <= 1}
+ onClick={() => setShowReorder(true)}
+ >
+ <ListOrdered className="h-4 w-4 mr-1" />
+ {t("common.reorder")}
+ </Button>
+ <Button size="sm" onClick={() => setShowCreate(true)}>
+ <Plus className="h-4 w-4 mr-1" />
+ {t("environment.create")}
+ </Button>
+ </div>
+ )}
+ </div>
+
+ {/* Tab content */}
+ <div className="flex-1 overflow-auto">
+ {selectedEnvironment && (
+ <EnvironmentDetail
+ key={selectedEnvironment.id}
+ environment={selectedEnvironment}
+ onDelete={handleDelete}
+ onDirtyChange={setDetailDirty}
+ />
+ )}
+ </div>
+
+ {/* Create drawer */}
+ {showCreate && (
+ <CreateDrawer
+ onClose={() => setShowCreate(false)}
+ onCreate={handleCreate}
+ />
+ )}
+
+ {/* Reorder drawer */}
+ {showReorder && (
+ <ReorderDrawer
+ environments={environmentList}
+ onClose={() => setShowReorder(false)}
+ onConfirm={handleReorder}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/router/dashboard/environmentV1.ts b/frontend/src/router/dashboard/environmentV1.ts
index e0842a6672..e28c54ad67 100644
--- a/frontend/src/router/dashboard/environmentV1.ts
+++ b/frontend/src/router/dashboard/environmentV1.ts
@@ -8,15 +8,14 @@ const environmentV1Routes: RouteRecordRaw[] = [
{
path: "environments/:environmentName",
name: ENVIRONMENT_V1_ROUTE_DETAIL,
- components: {
- content: () => import("@/views/EnvironmentDetail.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
- },
- props: { content: true },
meta: {
title: () => t("common.environment"),
requiredPermissionList: () => ["bb.settings.getEnvironment"],
},
+ redirect: (to) => ({
+ name: ENVIRONMENT_V1_ROUTE_DASHBOARD,
+ hash: `#${to.params.environmentName}`,
+ }),
},
];
diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.ts
index a1f1d58fc5..83fba21e00 100644
--- a/frontend/src/router/dashboard/workspace.ts
+++ b/frontend/src/router/dashboard/workspace.ts
@@ -98,10 +98,13 @@ const workspaceRoutes: RouteRecordRaw[] = [
requiredPermissionList: () => ["bb.settings.getEnvironment"],
},
components: {
- content: () => import("@/views/EnvironmentDashboard.vue"),
+ content: () => import("@/react/ReactPageMount.vue"),
leftSidebar: () => import("@/views/DashboardSidebar.vue"),
},
- props: { content: true, leftSidebar: true },
+ props: {
+ content: () => ({ page: "EnvironmentsPage" }),
+ leftSidebar: true,
+ },
},
{
path: "users/:principalEmail",
diff --git a/frontend/src/views/EnvironmentDashboard.vue b/frontend/src/views/EnvironmentDashboard.vue
deleted file mode 100644
index ec27d9944c..0000000000
--- a/frontend/src/views/EnvironmentDashboard.vue
+++ /dev/null
@@ -1,341 +0,0 @@
-<template>
- <div class="py-4 w-full h-full flex flex-col gap-4">
- <NTabs
- type="line"
- :bar-width="200"
- :value="state.selectedId"
- :size="tabSize"
- justify-content="start"
- class="h-full"
- :tab-style="isMdOrAbove?'margin: 0 1rem; padding-left: 2rem; padding: 0 2.5rem 0.5rem 2.5rem;':''"
- @update:value="onTabChange"
- >
- <NTabPane
- v-for="(item, index) in tabItemList"
- :key="item.id"
- :name="item.id"
- :tab="() => renderTab(item.data!, index)"
- class="h-full"
- >
- <EnvironmentDetail
- ref="environmentDetailRefs"
- :environment-name="item.id"
- :buttons-class="buttonsClass"
- @delete="doDelete"
- />
- </NTabPane>
- <template v-if="!isMdOrAbove" #prefix>
- <span/>
- </template>
- <template #suffix>
- <PermissionGuardWrapper
- v-slot="slotProps"
- :permissions="['bb.settings.setEnvironment']"
- >
- <div class="flex items-center justify-end gap-x-2 px-2 pb-1">
- <NButton
- :disabled="slotProps.disabled || environmentList.length <= 1"
- @click="startReorder"
- >
- <template #icon>
- <ListOrderedIcon class="h-4 w-4" />
- </template>
- <span v-if="showToolbarLabel">{{ t("common.reorder") }}</span>
- </NButton>
- <NButton
- type="primary"
- :disabled="slotProps.disabled"
- @click="createEnvironment"
- >
- <template #icon>
- <PlusIcon class="h-4 w-4" />
- </template>
- <span v-if="showToolbarLabel">{{ t("environment.create") }}</span>
- </NButton>
- </div>
- </PermissionGuardWrapper>
- </template>
- </NTabs>
- </div>
-
- <Drawer :show="state.showCreateModal" @close="state.showCreateModal = false">
- <EnvironmentForm
- :create="true"
- :environment="getEnvironmentCreate()"
- :rollout-policy="DEFAULT_NEW_ROLLOUT_POLICY"
- @create="doCreate"
- @cancel="state.showCreateModal = false"
- >
- <DrawerContent
- :title="t('environment.create')"
- class="w-xl max-w-[100vw]"
- >
- <EnvironmentFormBody />
- <template #footer>
- <EnvironmentFormButtons />
- </template>
- </DrawerContent>
- </EnvironmentForm>
- </Drawer>
-
- <Drawer v-model:show="state.reorder" :close-on-esc="true">
- <DrawerContent :title="t('environment.reorder')" class="w-120 max-w-[90vw]">
- <div>
- <VueDraggable
- v-model="state.reorderedEnvironmentList"
- :animation="300"
- >
- <div
- v-for="(element, index) in state.reorderedEnvironmentList"
- :key="(element as Environment).id"
- class="flex items-center justify-between p-2 hover:bg-gray-100 rounded-xs cursor-grab"
- >
- <div class="flex items-center gap-x-2">
- <span class="textinfo"> {{ index + 1 }}.</span>
- <EnvironmentV1Name :environment="(element as Environment)" :link="false" />
- </div>
- <GripVerticalIcon class="w-5 h-5 text-gray-500" />
- </div>
- </VueDraggable>
- </div>
- <template #footer>
- <div class="flex items-center justify-end gap-x-2">
- <NButton @click="discardReorder">{{ t("common.cancel") }}</NButton>
- <NButton type="primary" :disabled="!orderChanged" @click="doReorder">
- {{ t("common.confirm") }}
- </NButton>
- </div>
- </template>
- </DrawerContent>
- </Drawer>
-</template>
-
-<script lang="ts" setup>
-import { create } from "@bufbuild/protobuf";
-import { isEqual } from "lodash-es";
-import { GripVerticalIcon, ListOrderedIcon, PlusIcon } from "lucide-vue-next";
-import { NButton, NTabPane, NTabs } from "naive-ui";
-import { computed, h, onMounted, reactive, ref, watch } from "vue";
-import { VueDraggable } from "vue-draggable-plus";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import {
- EnvironmentForm,
- Form as EnvironmentFormBody,
- Buttons as EnvironmentFormButtons,
-} from "@/components/EnvironmentForm";
-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
-import { Drawer, DrawerContent, EnvironmentV1Name } from "@/components/v2";
-import { useRouteChangeGuard } from "@/composables/useRouteChangeGuard";
-import { useWideScreen } from "@/composables/useWideScreen";
-import {
- environmentNamePrefix,
- pushNotification,
- useEnvironmentV1Store,
- useUIStateStore,
-} from "@/store";
-import {
- getEmptyRolloutPolicy,
- usePolicyV1Store,
-} from "@/store/modules/v1/policy";
-import { formatEnvironmentName } from "@/types";
-import type { Policy } from "@/types/proto-es/v1/org_policy_service_pb";
-import { PolicyResourceType } from "@/types/proto-es/v1/org_policy_service_pb";
-import { EnvironmentSetting_EnvironmentSchema } from "@/types/proto-es/v1/setting_service_pb";
-import type { Environment } from "@/types/v1/environment";
-import { TailwindBreakpoints, type VueClass } from "@/utils";
-import EnvironmentDetail from "@/views/EnvironmentDetail.vue";
-
-const DEFAULT_NEW_ROLLOUT_POLICY: Policy = getEmptyRolloutPolicy(
- "",
- PolicyResourceType.ENVIRONMENT
-);
-
-defineProps<{
- buttonsClass?: VueClass;
-}>();
-
-interface LocalState {
- selectedId: string;
- reorderedEnvironmentList: Environment[];
- showCreateModal: boolean;
- reorder: boolean;
-}
-
-const { t } = useI18n();
-const environmentV1Store = useEnvironmentV1Store();
-const uiStateStore = useUIStateStore();
-const policyV1Store = usePolicyV1Store();
-const router = useRouter();
-const environmentDetailRefs = ref<InstanceType<typeof EnvironmentDetail>[]>([]);
-const showToolbarLabel = useWideScreen(TailwindBreakpoints.sm);
-const isMdOrAbove = useWideScreen();
-const tabSize = computed(() => (isMdOrAbove.value ? "large" : "small"));
-
-const environmentList = computed(() => environmentV1Store.environmentList);
-
-const state = reactive<LocalState>({
- selectedId: "",
- reorderedEnvironmentList: [],
- showCreateModal: false,
- reorder: false,
-});
-
-const selectEnvironment = (index: number) => {
- const id = environmentList.value[index].id;
- onTabChange(id);
-};
-
-useRouteChangeGuard(
- computed(() => environmentDetailRefs.value[0]?.isEditing ?? false)
-);
-
-const onTabChange = (id: string) => {
- // The NTabPane only render the selected environment,
- // so we only need to check the 1st environmentDetailRefs
- if (environmentDetailRefs.value[0]?.isEditing) {
- if (!window.confirm(t("common.leave-without-saving"))) {
- return;
- }
- }
- state.selectedId = id;
- router.replace({
- name: router.currentRoute.value.name,
- hash: "#" + id,
- });
-};
-
-const selectEnvironmentOnHash = (target: string) => {
- if (environmentList.value.length <= 0) {
- return;
- }
- const index = Math.max(
- 0,
- environmentList.value.findIndex((env) => env.id === target)
- );
- selectEnvironment(index);
-};
-
-onMounted(() => {
- if (!uiStateStore.getIntroStateByKey("environment.visit")) {
- uiStateStore.saveIntroStateByKey({
- key: "environment.visit",
- newState: true,
- });
- }
-});
-
-watch(
- () => router.currentRoute.value.hash,
- (hash) => {
- selectEnvironmentOnHash(hash.slice(1));
- },
- { immediate: true }
-);
-
-const tabItemList = computed(() => {
- return environmentList.value.map((item, index: number) => {
- const title = `${index + 1}. ${item.title}`;
- const id = item.id;
- return { title, id, data: item };
- });
-});
-
-const getEnvironmentCreate = () => {
- return {
- ...create(EnvironmentSetting_EnvironmentSchema, {}),
- order: 0,
- };
-};
-
-const createEnvironment = () => {
- stopReorder();
- state.showCreateModal = true;
-};
-
-const doCreate = async (params: {
- environment: Partial<Environment>;
- rolloutPolicy: Policy;
-}) => {
- const { environment, rolloutPolicy } = params;
- const createdEnvironment = await environmentV1Store.createEnvironment({
- id: environment.id,
- title: environment.title,
- order: environmentList.value.length,
- color: environment.color,
- tags: environment.tags,
- });
-
- // Only persist rollout policy if user customized it from the defaults
- // Otherwise, let the backend return defaults dynamically via GetPolicy API
- const isCustomized = !isEqual(rolloutPolicy, DEFAULT_NEW_ROLLOUT_POLICY);
- if (isCustomized) {
- await policyV1Store.upsertPolicy({
- parentPath: `${environmentNamePrefix}${createdEnvironment.id}`,
- policy: rolloutPolicy,
- });
- }
-
- state.showCreateModal = false;
- selectEnvironment(createdEnvironment.order);
-};
-
-const startReorder = () => {
- state.reorderedEnvironmentList = [...environmentList.value];
- state.reorder = true;
-};
-
-const stopReorder = () => {
- state.reorder = false;
-};
-
-const orderChanged = computed(() => {
- for (let i = 0; i < state.reorderedEnvironmentList.length; i++) {
- if (state.reorderedEnvironmentList[i].id !== environmentList.value[i].id) {
- return true;
- }
- }
- return false;
-});
-
-const discardReorder = () => {
- stopReorder();
-};
-
-const doReorder = () => {
- environmentV1Store
- .reorderEnvironmentList(state.reorderedEnvironmentList)
- .then(() => {
- stopReorder();
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
- });
-};
-
-const doDelete = async (environment: Environment) => {
- await environmentV1Store.deleteEnvironment(
- formatEnvironmentName(environment.id)
- );
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.deleted"),
- });
- if (environmentList.value.length > 0) {
- selectEnvironment(0);
- }
-};
-
-const renderTab = (env: Environment, index: number) => {
- return h("div", { class: "flex items-center gap-x-2 py-1" }, [
- h("span", { class: "text-opacity-60" }, `${index + 1}.`),
- h(EnvironmentV1Name, {
- environment: env,
- link: false,
- }),
- ]);
-};
-</script>
diff --git a/frontend/src/views/EnvironmentDetail.vue b/frontend/src/views/EnvironmentDetail.vue
deleted file mode 100644
index c7c57cfddd..0000000000
--- a/frontend/src/views/EnvironmentDetail.vue
+++ /dev/null
@@ -1,137 +0,0 @@
-<template>
- <EnvironmentForm
- v-if="state.rolloutPolicy"
- ref="environmentFormRef"
- :environment="state.environment"
- :rollout-policy="state.rolloutPolicy"
- @update="doUpdate"
- @delete="doDelete"
- @update-policy="updatePolicy"
- >
- <div class="flex flex-col h-full w-full">
- <EnvironmentFormBody :features="features" class="w-full flex-1 px-4" />
- <EnvironmentFormButtons
- class="sticky bottom-0 bg-white py-2 px-2 border-t border-block-border"
- :class="buttonsClass"
- />
- </div>
- </EnvironmentForm>
-</template>
-
-<script lang="ts" setup>
-import { create } from "@bufbuild/protobuf";
-import { cloneDeep, isEqual } from "lodash-es";
-import { computed, reactive, ref, watchEffect } from "vue";
-import {
- EnvironmentForm,
- Form as EnvironmentFormBody,
- Buttons as EnvironmentFormButtons,
-} from "@/components/EnvironmentForm";
-import { useEnvironmentV1Store } from "@/store";
-import { environmentNamePrefix } from "@/store/modules/v1/common";
-import { usePolicyV1Store } from "@/store/modules/v1/policy";
-import { formatEnvironmentName } from "@/types";
-import type { Policy } from "@/types/proto-es/v1/org_policy_service_pb";
-import {
- PolicySchema,
- PolicyType,
- RolloutPolicySchema,
-} from "@/types/proto-es/v1/org_policy_service_pb";
-import type { Environment } from "@/types/v1/environment";
-import { type VueClass } from "@/utils";
-
-interface LocalState {
- environment: Environment;
- rolloutPolicy?: Policy;
-}
-
-const props = defineProps<{
- features?: InstanceType<typeof EnvironmentFormBody>["features"];
- environmentName: string;
- buttonsClass?: VueClass;
-}>();
-
-const emit = defineEmits<{
- (event: "delete", environment: Environment): void;
-}>();
-
-const environmentV1Store = useEnvironmentV1Store();
-const policyV1Store = usePolicyV1Store();
-const environmentFormRef = ref<InstanceType<typeof EnvironmentForm>>();
-
-const state = reactive<LocalState>({
- environment: environmentV1Store.getEnvironmentByName(
- `${environmentNamePrefix}${props.environmentName}`
- ),
-});
-
-const stateEnvironmentName = computed(() => {
- return formatEnvironmentName(state.environment.id);
-});
-
-// Fetch rollout policy directly using getOrFetchPolicyByParentAndType
-// The backend now returns default policy if none exists, so no manual fallback needed
-const preparePolicy = async () => {
- const policy = await policyV1Store.getOrFetchPolicyByParentAndType({
- parentPath: stateEnvironmentName.value,
- policyType: PolicyType.ROLLOUT_POLICY,
- });
- state.rolloutPolicy =
- policy ??
- create(PolicySchema, {
- policy: {
- case: "rolloutPolicy",
- value: create(RolloutPolicySchema, {}),
- },
- });
-};
-
-watchEffect(preparePolicy);
-
-const assignEnvironment = (environment: Environment) => {
- state.environment = environment;
-};
-
-const doUpdate = (environmentPatch: Environment) => {
- const pendingUpdate = cloneDeep(state.environment);
- if (environmentPatch.title !== pendingUpdate.title) {
- pendingUpdate.title = environmentPatch.title;
- }
- if (!isEqual(environmentPatch.tags, pendingUpdate.tags)) {
- pendingUpdate.tags = environmentPatch.tags;
- }
- if (environmentPatch.color !== pendingUpdate.color) {
- pendingUpdate.color = environmentPatch.color;
- }
-
- environmentV1Store.updateEnvironment(pendingUpdate).then((environment) => {
- assignEnvironment(environment);
- });
-};
-
-const doDelete = (environment: Environment) => {
- emit("delete", environment);
-};
-
-const updatePolicy = async (params: {
- environment: Environment;
- policyType: PolicyType;
- policy: Policy;
-}) => {
- const { environment, policyType, policy } = params;
-
- const updatedPolicy = await policyV1Store.upsertPolicy({
- parentPath: formatEnvironmentName(environment.id),
- policy,
- });
- switch (policyType) {
- case PolicyType.ROLLOUT_POLICY:
- state.rolloutPolicy = updatedPolicy;
- break;
- }
-};
-
-defineExpose({
- isEditing: computed(() => environmentFormRef.value?.isEditing ?? false),
-});
-</script>