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 semantic types settings page to React (#19769)
Danny Xu2d5d7422291a
diff --git a/frontend/src/components/ColumnDataTable/SemanticTypeCell.vue b/frontend/src/components/ColumnDataTable/SemanticTypeCell.vueindex c4bbd3f6cd..c87281bf8c 100644--- a/frontend/src/components/ColumnDataTable/SemanticTypeCell.vue+++ b/frontend/src/components/ColumnDataTable/SemanticTypeCell.vue@@ -40,17 +40,21 @@</template><script lang="ts" setup>+import { create } from "@bufbuild/protobuf";import { PencilIcon, XIcon } from "lucide-vue-next";import { NPopconfirm } from "naive-ui";-import { computed, reactive } from "vue";-import { useSemanticType } from "@/components/SensitiveData/useSemanticType";+import { computed, reactive, watchEffect } from "vue";import { MiniActionButton } from "@/components/v2";-import { useSubscriptionV1Store } from "@/store";+import { useSettingV1Store, useSubscriptionV1Store } from "@/store";import type { Database } from "@/types/proto-es/v1/database_service_pb";+import {+ SemanticTypeSetting_SemanticTypeSchema,+ Setting_SettingName,+} from "@/types/proto-es/v1/setting_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import { getInstanceResource } from "@/utils";+import { getInstanceResource, hasWorkspacePermissionV2 } from "@/utils";import FeatureModal from "../FeatureGuard/FeatureModal.vue";-import SemanticTypesDrawer from "../SensitiveData/components/SemanticTypesDrawer.vue";+import SemanticTypesDrawer from "./SemanticTypesDrawer.vue";type LocalState = {showFeatureModal: boolean;@@ -72,9 +76,36 @@ const state = reactive<LocalState>({showSemanticTypesDrawer: false,});const subscriptionV1Store = useSubscriptionV1Store();-const { semanticType, semanticTypeList } = useSemanticType(- computed(() => props.semanticTypeId)-);+const settingV1Store = useSettingV1Store();++watchEffect(async () => {+ await settingV1Store.getOrFetchSettingByName(+ Setting_SettingName.SEMANTIC_TYPES,+ true+ );+});++const semanticTypeList = computed(() => {+ const setting = settingV1Store.getSettingByName(+ Setting_SettingName.SEMANTIC_TYPES+ );+ if (setting?.value?.value?.case === "semanticType") {+ return setting.value.value.value.types ?? [];+ }+ return [];+});++const semanticType = computed(() => {+ const id = props.semanticTypeId;+ if (!id) return;+ if (!hasWorkspacePermissionV2("bb.settings.get")) {+ return create(SemanticTypeSetting_SemanticTypeSchema, {+ id,+ title: id,+ });+ }+ return semanticTypeList.value.find((data) => data.id === id);+});const hasSensitiveDataFeature = computed(() => {return subscriptionV1Store.hasFeature(PlanFeature.FEATURE_DATA_MASKING);diff --git a/frontend/src/components/SensitiveData/components/SemanticTypesDrawer.vue b/frontend/src/components/ColumnDataTable/SemanticTypesDrawer.vuesimilarity index 98%rename from frontend/src/components/SensitiveData/components/SemanticTypesDrawer.vuerename to frontend/src/components/ColumnDataTable/SemanticTypesDrawer.vueindex b9d8ae7411..5df0d7dd42 100644--- a/frontend/src/components/SensitiveData/components/SemanticTypesDrawer.vue+++ b/frontend/src/components/ColumnDataTable/SemanticTypesDrawer.vue@@ -3,7 +3,6 @@<DrawerContent :title="$t('settings.sensitive-data.semantic-types.self')"><div class="flex flex-col gap-y-8 w-200 h-full"><SemanticTypesTable- :readonly="true":row-clickable="true":size="'small'":semantic-item-list="semanticItemList"diff --git a/frontend/src/components/ColumnDataTable/SemanticTypesTable.vue b/frontend/src/components/ColumnDataTable/SemanticTypesTable.vuenew file mode 100644index 0000000000..66a69416a8--- /dev/null+++ b/frontend/src/components/ColumnDataTable/SemanticTypesTable.vue@@ -0,0 +1,174 @@+<template>+ <NDataTable+ :size="size"+ :data="semanticItemList"+ :columns="columnList"+ :striped="true"+ :bordered="true"+ :row-props="rowProps"+ :row-key="(item: SemanticItem) => item.item.id"+ />+</template>++<script lang="tsx" setup>+import { InfoIcon } from "lucide-vue-next";+import type { DataTableColumn } from "naive-ui";+import { NDataTable, NTooltip } from "naive-ui";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import type {+ Algorithm,+ SemanticTypeSetting_SemanticType,+} from "@/types/proto-es/v1/setting_service_pb";++export interface SemanticItem {+ mode: "NORMAL";+ dirty: boolean;+ item: SemanticTypeSetting_SemanticType;+}++const props = withDefaults(+ defineProps<{+ size?: "small" | "medium" | "large";+ semanticItemList: SemanticItem[];+ rowClickable: boolean;+ }>(),+ { size: "medium" }+);++const emit = defineEmits<{+ (event: "select", id: string): void;+}>();++const { t } = useI18n();++type MaskingType = "full-mask" | "range-mask" | "md5-mask" | "inner-outer-mask";++const getMaskingType = (+ algorithm: Algorithm | undefined+): MaskingType | undefined => {+ if (!algorithm?.mask) return undefined;+ switch (algorithm.mask.case) {+ case "fullMask":+ return "full-mask";+ case "rangeMask":+ return "range-mask";+ case "innerOuterMask":+ return "inner-outer-mask";+ case "md5Mask":+ return "md5-mask";+ default:+ return undefined;+ }+};++const isBuiltinSemanticType = (item: SemanticTypeSetting_SemanticType) => {+ return item.id.startsWith("bb.");+};++const columnList = computed(() => {+ const columns: DataTableColumn<SemanticItem>[] = [+ {+ key: "icon",+ title: t("settings.sensitive-data.semantic-types.table.icon"),+ width: 80,+ align: "center",+ render: (item) => {+ if (item.item.icon) {+ return (+ <div class="flex items-center justify-center">+ <img src={item.item.icon} class="w-6 h-6 object-contain" alt="" />+ </div>+ );+ }+ return (+ <div class="flex items-center justify-center">+ <span class="text-gray-400">-</span>+ </div>+ );+ },+ },+ {+ key: "id",+ title: "ID",+ width: 150,+ resizable: true,+ ellipsis: { tooltip: true },+ render: (item) => item.item.id,+ },+ {+ key: "title",+ title: t("settings.sensitive-data.semantic-types.table.semantic-type"),+ width: "minmax(min-content, auto)",+ resizable: true,+ ellipsis: { tooltip: true },+ render: (item) => item.item.title,+ },+ {+ key: "description",+ title: t("settings.sensitive-data.semantic-types.table.description"),+ width: 200,+ resizable: true,+ ellipsis: { tooltip: true },+ render: (item) => item.item.description,+ },+ {+ key: "algorithm",+ title: t(+ "settings.sensitive-data.semantic-types.table.masking-algorithm"+ ),+ width: "minmax(min-content, auto)",+ resizable: true,+ render: (item) => {+ return (+ <div class="flex items-center gap-x-1">+ {isBuiltinSemanticType(item.item) ? (+ <h3>+ {t(+ `dynamic.settings.sensitive-data.semantic-types.template.${item.item.id.split(".").join("-")}.title`+ )}+ </h3>+ ) : (+ <h3>+ {getMaskingType(item.item.algorithm)+ ? t(+ `settings.sensitive-data.algorithms.${getMaskingType(item.item.algorithm)?.toLowerCase()}.self`+ )+ : "N/A"}+ </h3>+ )}+ {isBuiltinSemanticType(item.item) && (+ <NTooltip>+ {{+ trigger: () => <InfoIcon class="w-4" />,+ default: () => (+ <div class="whitespace-pre-line">+ {t(+ `dynamic.settings.sensitive-data.semantic-types.template.${item.item.id.split(".").join("-")}.algorithm.description`+ )}+ </div>+ ),+ }}+ </NTooltip>+ )}+ </div>+ );+ },+ },+ ];++ return columns;+});++const rowProps = (item: SemanticItem) => {+ return {+ style: props.rowClickable ? "cursor: pointer;" : "",+ onClick: () => {+ if (!props.rowClickable) {+ return;+ }+ emit("select", item.item.id);+ },+ };+};+</script>diff --git a/frontend/src/components/SensitiveData/SemanticTypesView.vue b/frontend/src/components/SensitiveData/SemanticTypesView.vuedeleted file mode 100644index 45f10a74cb..0000000000--- a/frontend/src/components/SensitiveData/SemanticTypesView.vue+++ /dev/null@@ -1,242 +0,0 @@-<template>- <div class="w-full flex flex-col gap-y-4">- <div class="flex justify-end">- <PermissionGuardWrapper- v-slot="slotProps"- :permissions="['bb.policies.update']"- >- <div class="flex items-center gap-x-2">- <NButton- :disabled="slotProps.disabled || !hasSensitiveDataFeature"- @click="state.showTemplateDrawer = true"- >- {{ $t("settings.sensitive-data.semantic-types.use-predefined-type") }}- </NButton>- <NButton- type="primary"- :disabled="slotProps.disabled || !hasSensitiveDataFeature"- @click="onAdd"- >- <template #icon>- <PlusIcon class="h-4 w-4" />- </template>- {{ $t("common.add") }}- </NButton>- </div>- </PermissionGuardWrapper>- </div>- <div class="textinfolabel">- {{ $t("settings.sensitive-data.semantic-types.label") }}- </div>- <SemanticTypesTable- :readonly="!hasPermission || !hasSensitiveDataFeature"- :row-clickable="false"- :semantic-item-list="state.semanticItemList"- @cancel="onCancel"- @remove="onRemove"- @confirm="onConfirm"- />- </div>- <SemanticTemplateDrawer- :show="state.showTemplateDrawer"- @apply="onTemplateApply"- @dismiss="state.showTemplateDrawer = false"- />-</template>-<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { PlusIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { v4 as uuidv4 } from "uuid";-import { computed, onMounted, reactive } from "vue";-import { useI18n } from "vue-i18n";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import { featureToRef, pushNotification, useSettingV1Store } from "@/store";-import type { SemanticTypeSetting_SemanticType } from "@/types/proto-es/v1/setting_service_pb";-import {- SemanticTypeSetting_SemanticTypeSchema,- Setting_SettingName,- SettingValueSchema as SettingSettingValueSchema,-} from "@/types/proto-es/v1/setting_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import { hasWorkspacePermissionV2 } from "@/utils";-import SemanticTemplateDrawer from "./components/SemanticTemplateDrawer.vue";-import type { SemanticItem } from "./components/SemanticTypesTable.vue";-import SemanticTypesTable from "./components/SemanticTypesTable.vue";--interface LocalState {- semanticItemList: SemanticItem[];- processing: boolean;- showTemplateDrawer: boolean;-}--const { t } = useI18n();-const state = reactive<LocalState>({- semanticItemList: [],- processing: false,- showTemplateDrawer: false,-});--const settingStore = useSettingV1Store();-const hasPermission = computed(() => {- return hasWorkspacePermissionV2("bb.policies.update");-});-const hasSensitiveDataFeature = featureToRef(PlanFeature.FEATURE_DATA_MASKING);--const semanticTypeSettingValue = computed(() => {- const semanticTypeSetting = settingStore.getSettingByName(- Setting_SettingName.SEMANTIC_TYPES- );- return semanticTypeSetting?.value?.value?.case === "semanticType"- ? (semanticTypeSetting.value.value.value.types ?? [])- : [];-});--onMounted(async () => {- await settingStore.getOrFetchSettingByName(- Setting_SettingName.SEMANTIC_TYPES- );- state.semanticItemList = semanticTypeSettingValue.value.map(- (semanticType) => {- return {- dirty: false,- item: semanticType,- mode: "NORMAL",- };- }- );-});--const onAdd = () => {- state.semanticItemList.push({- mode: "CREATE",- dirty: false,- item: create(SemanticTypeSetting_SemanticTypeSchema, {- id: uuidv4(),- }),- });-};--const onRemove = async (index: number) => {- const item = state.semanticItemList[index];- if (!item) {- return;- }- state.semanticItemList.splice(index, 1);- if (item.mode === "CREATE") {- return;- }-- await settingStore.upsertSetting({- name: Setting_SettingName.SEMANTIC_TYPES,- value: create(SettingSettingValueSchema, {- value: {- case: "semanticType",- value: {- types: state.semanticItemList- .filter((data) => data.mode === "NORMAL")- .map((data) => data.item),- },- },- }),- });-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.deleted"),- });-};--const onConfirm = async (index: number) => {- const item = state.semanticItemList[index];- state.semanticItemList[index] = {- ...item,- dirty: false,- mode: "NORMAL",- };-- await onUpsert(- state.semanticItemList- .filter((data) => data.mode === "NORMAL")- .map((data) => data.item),- t(`common.${item.mode === "CREATE" ? "created" : "updated"}`)- );-};--const onUpsert = async (- semanticItemList: SemanticTypeSetting_SemanticType[],- notification: string-) => {- await settingStore.upsertSetting({- name: Setting_SettingName.SEMANTIC_TYPES,- value: create(SettingSettingValueSchema, {- value: {- case: "semanticType",- value: {- types: semanticItemList,- },- },- }),- });-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: notification,- });-};--const onCancel = (index: number) => {- const item = state.semanticItemList[index];-- if (item.mode === "CREATE") {- state.semanticItemList.splice(index, 1);- } else {- const semanticTypeSetting = settingStore.getSettingByName(- Setting_SettingName.SEMANTIC_TYPES- );- const types =- semanticTypeSetting?.value?.value?.case === "semanticType"- ? (semanticTypeSetting.value.value.value.types ?? [])- : [];- const origin = types.find((s) => s.id === item.item.id);- if (!origin) {- return;- }- state.semanticItemList[index] = {- item: origin,- mode: "NORMAL",- dirty: false,- };- }-};--const onTemplateApply = async (template: SemanticTypeSetting_SemanticType) => {- if (state.semanticItemList.find((item) => item.item.id === template.id)) {- pushNotification({- module: "bytebase",- style: "INFO",- title: t(- "settings.sensitive-data.semantic-types.template.duplicate-warning",- {- title: template.title,- }- ),- });- return;- }- const semanticItem: SemanticItem = {- dirty: false,- mode: "NORMAL",- item: create(SemanticTypeSetting_SemanticTypeSchema, {- ...template,- }),- };- state.semanticItemList.push(semanticItem);- await onUpsert(- [...semanticTypeSettingValue.value, semanticItem.item],- t("common.created")- );-};-</script>diff --git a/frontend/src/components/SensitiveData/components/IconSelector.vue b/frontend/src/components/SensitiveData/components/IconSelector.vuedeleted file mode 100644index e742176eed..0000000000--- a/frontend/src/components/SensitiveData/components/IconSelector.vue+++ /dev/null@@ -1,120 +0,0 @@-<template>- <div class="w-full">- <div v-if="!isEditing" class="flex items-center justify-center gap-1">- <template v-if="value">- <!-- Display uploaded image -->- <img :src="value" class="w-6 h-6 object-contain" alt="" />- <MiniActionButton v-if="!readonly" @click="startEditing">- <PencilIcon class="w-4 h-4" />- </MiniActionButton>- </template>- <MiniActionButton v-else-if="!readonly" @click="startEditing">- <PencilIcon class="w-4 h-4" />- </MiniActionButton>- <span v-else class="text-gray-400">-</span>- </div>-- <!-- Edit mode -->- <NPopover- v-else- :show="true"- trigger="manual"- placement="bottom"- @clickoutside="cancelEdit"- >- <template #trigger>- <div class="w-full" />- </template>- <div class="p-2 flex flex-col gap-y-4">- <div class="w-48 h-48 flex justify-center items-center border border-gray-300 border-dashed rounded-md relative">- <div- class="w-1/3 h-1/3 bg-no-repeat bg-contain bg-center rounded-md pointer-events-none"- :style="`background-image: url(${tempValue});`"- ></div>-- <SingleFileSelector- class="flex flex-col gap-y-1 text-center justify-center items-center absolute top-0 bottom-0 left-0 right-0"- :class="[tempValue ? 'opacity-0 hover:opacity-90' : '']"- :max-file-size-in-mi-b="2"- :support-file-extensions="supportImageExtensions"- :show-no-data-placeholder="!tempValue"- @on-select="onFileSelect"- />- </div>- <div class="flex justify-end gap-2">- <NButton size="tiny" @click="clearIcon">- {{ $t("common.clear") }}- </NButton>- <NButton size="tiny" @click="cancelEdit">- {{ $t("common.cancel") }}- </NButton>- <NButton size="tiny" type="primary" @click="confirmEdit">- {{ $t("common.confirm") }}- </NButton>- </div>- </div>- </NPopover>- </div>-</template>--<script setup lang="ts">-import { PencilIcon } from "lucide-vue-next";-import { NButton, NPopover } from "naive-ui";-import { ref, watch } from "vue";-import SingleFileSelector from "@/components/SingleFileSelector.vue";-import { MiniActionButton } from "@/components/v2";--const props = defineProps<{- value?: string;- readonly?: boolean;-}>();--const emit = defineEmits<{- (event: "update:value", value: string): void;-}>();--const isEditing = ref(false);-const tempValue = ref("");--watch(- () => isEditing.value,- (editing) => {- if (editing) {- tempValue.value = props.value ?? "";- }- }-);--const supportImageExtensions = [".jpg", ".jpeg", ".png", ".webp", ".svg"];--const startEditing = () => {- if (props.readonly) return;- isEditing.value = true;-};--const confirmEdit = () => {- emit("update:value", tempValue.value);- isEditing.value = false;-};--const cancelEdit = () => {- isEditing.value = false;-};--const clearIcon = () => {- tempValue.value = "";-};--const onFileSelect = async (file: File) => {- const fileInBase64 = await convertFileToBase64(file);- tempValue.value = fileInBase64;-};--const convertFileToBase64 = (file: File) =>- new Promise<string>((resolve, reject) => {- const reader = new FileReader();- reader.readAsDataURL(file);- reader.onload = () => resolve(reader.result as string);- reader.onerror = (error) => reject(error);- });-</script>diff --git a/frontend/src/components/SensitiveData/components/MaskingAlgorithmsCreateDrawer.vue b/frontend/src/components/SensitiveData/components/MaskingAlgorithmsCreateDrawer.vuedeleted file mode 100644index 7e31532137..0000000000--- a/frontend/src/components/SensitiveData/components/MaskingAlgorithmsCreateDrawer.vue+++ /dev/null@@ -1,619 +0,0 @@-<template>- <Drawer :show="show" @close="$emit('dismiss')">- <DrawerContent- :title="- algorithm- ? $t('settings.sensitive-data.algorithms.edit')- : $t('settings.sensitive-data.algorithms.add')- "- >- <div class="w-[40rem] max-w-[calc(100vw-5rem)]">- <div class="flex flex-col gap-y-6 pb-6">- <div class="w-full mb-6 flex flex-col gap-y-1">- <label for="masking-type" class="textlabel">- {{ $t("settings.sensitive-data.algorithms.table.masking-type") }}- <RequiredStar />- </label>- <RadioGrid- :value="state.maskingType"- :options="maskingTypeList"- :disabled="readonly"- class="grid-cols-3 gap-2"- @update:value="onMaskingTypeChange($event as MaskingType)"- >- <template #item="{ option }">- {{ option.label }}- </template>- </RadioGrid>- </div>- </div>- <div class="flex flex-col gap-y-6 border-t border-block-border pt-6">- <template v-if="state.maskingType === 'full-mask'">- <div class="sm:col-span-2 sm:col-start-1">- <label for="substitution" class="textlabel">- {{- $t(- "settings.sensitive-data.algorithms.full-mask.substitution"- )- }}- <RequiredStar />- </label>- <p class="textinfolabel">- {{- $t(- "settings.sensitive-data.algorithms.full-mask.substitution-label"- )- }}- </p>- <NInput- v-model:value="state.fullMask.substitution"- :placeholder="- t('settings.sensitive-data.algorithms.full-mask.substitution')- "- class="mt-2"- :disabled="state.processing || readonly"- />- </div>- </template>- <template v-if="state.maskingType === 'range-mask'">- <p class="textinfolabel">- {{ $t("settings.sensitive-data.algorithms.range-mask.label") }}- </p>- <div- v-for="(slice, i) in state.rangeMask.slices"- :key="i"- class="flex gap-x-2 items-center"- >- <div class="flex-none flex flex-col gap-y-1">- <label for="slice-start" class="textlabel flex">- {{- $t(- "settings.sensitive-data.algorithms.range-mask.slice-start"- )- }}- <RequiredStar />- </label>- <NInputNumber- :value="slice.start"- :placeholder="- t(- 'settings.sensitive-data.algorithms.range-mask.slice-start'- )- "- :disabled="state.processing || readonly"- style="width: 5rem"- @update:value="onSliceStartChange(i, $event)"- />- </div>- <div class="flex-none flex flex-col gap-y-1">- <label for="slice-end" class="textlabel">- {{- $t(- "settings.sensitive-data.algorithms.range-mask.slice-end"- )- }}- <RequiredStar />- </label>- <NInputNumber- :value="slice.end"- :placeholder="- t('settings.sensitive-data.algorithms.range-mask.slice-end')- "- :disabled="state.processing || readonly"- style="width: 5rem"- @update:value="onSliceEndChange(i, $event)"- />- </div>- <div class="flex-1 flex flex-col gap-y-1">- <label for="substitution" class="textlabel">- {{- $t(- "settings.sensitive-data.algorithms.range-mask.substitution"- )- }}- <RequiredStar />- </label>- <NInput- v-model:value="slice.substitution"- :placeholder="- t(- 'settings.sensitive-data.algorithms.range-mask.substitution'- )- "- :disabled="state.processing || readonly"- />- </div>- <div class="h-[34px] flex flex-row items-center self-end">- <MiniActionButton- :disabled="state.processing || readonly"- @click.stop="removeSlice(i)"- >- <TrashIcon class="w-4 h-4" />- </MiniActionButton>- </div>- </div>- <div v-if="rangeMaskErrorMessage" class="text-red-600">- {{ rangeMaskErrorMessage }}- </div>- <NButton- class="ml-auto"- :disabled="state.processing || readonly"- @click.prevent="addSlice"- >- {{ $t("common.add") }}- </NButton>- </template>- <template v-if="state.maskingType === 'md5-mask'">- <div class="sm:col-span-2 sm:col-start-1">- <label for="salt" class="textlabel">- {{ $t("settings.sensitive-data.algorithms.md5-mask.salt") }}- <RequiredStar />- </label>- <p class="textinfolabel">- {{- $t("settings.sensitive-data.algorithms.md5-mask.salt-label")- }}- </p>- <NInput- v-model:value="state.md5Mask.salt"- :placeholder="- t('settings.sensitive-data.algorithms.md5-mask.salt')- "- class="mt-2"- :disabled="state.processing || readonly"- />- </div>- </template>- <template v-if="state.maskingType === 'inner-outer-mask'">- <label class="textlabel">- {{- $t("settings.sensitive-data.algorithms.inner-outer-mask.type")- }}- <RequiredStar />- <p class="textinfolabel">- {{- state.innerOuterMask.type ==- Algorithm_InnerOuterMask_MaskType.INNER- ? $t(- "settings.sensitive-data.algorithms.inner-outer-mask.inner-label"- )- : $t(- "settings.sensitive-data.algorithms.inner-outer-mask.outer-label"- )- }}- </p>- </label>- <NRadioGroup- v-model:value="state.innerOuterMask.type"- :disabled="state.processing || readonly"- >- <NRadio :value="Algorithm_InnerOuterMask_MaskType.INNER">- {{- $t(- "settings.sensitive-data.algorithms.inner-outer-mask.inner-mask"- )- }}- </NRadio>- <NRadio :value="Algorithm_InnerOuterMask_MaskType.OUTER">- {{- $t(- "settings.sensitive-data.algorithms.inner-outer-mask.outer-mask"- )- }}- </NRadio>- </NRadioGroup>- <div class="flex gap-x-2 items-center">- <div class="flex-none flex flex-col gap-y-1">- <label for="slice-start" class="textlabel flex">- {{- $t(- "settings.sensitive-data.algorithms.inner-outer-mask.prefix-length"- )- }}- <RequiredStar />- </label>- <NInputNumber- :value="state.innerOuterMask.prefixLen"- :placeholder="- t(- 'settings.sensitive-data.algorithms.inner-outer-mask.prefix-length'- )- "- :disabled="state.processing || readonly"- style="width: 5.5rem"- @update:value="onPrefixChange($event as number)"- />- </div>- <div class="flex-none flex flex-col gap-y-1">- <label for="slice-end" class="textlabel">- {{- $t(- "settings.sensitive-data.algorithms.inner-outer-mask.suffix-length"- )- }}- <RequiredStar />- </label>- <NInputNumber- :value="state.innerOuterMask.suffixLen"- :placeholder="- t(- 'settings.sensitive-data.algorithms.inner-outer-mask.suffix-length'- )- "- :disabled="state.processing || readonly"- style="width: 5.5rem"- @update:value="onSuffixChange($event as number)"- />- </div>- <div class="flex-1 flex flex-col gap-y-1">- <label for="substitution" class="textlabel">- {{- $t(- "settings.sensitive-data.algorithms.range-mask.substitution"- )- }}- <RequiredStar />- </label>- <NInput- v-model:value="state.innerOuterMask.substitution"- :placeholder="- t(- 'settings.sensitive-data.algorithms.range-mask.substitution'- )- "- :disabled="state.processing || readonly"- />- </div>- </div>- </template>- </div>- </div>- <template #footer>- <div class="w-full flex justify-between items-center">- <div class="w-full flex justify-end items-center gap-x-2">- <NButton @click.prevent="$emit('dismiss')">- {{ $t("common.cancel") }}- </NButton>- <NTooltip :disabled="!errorMessage">- <template #trigger>- <NButton- v-if="!readonly"- :disabled="isSubmitDisabled"- type="primary"- @click.prevent="() => $emit('apply', maskingAlgorithm)"- >- {{ $t("common.confirm") }}- </NButton>- </template>- {{ errorMessage }}- </NTooltip>- </div>- </div>- </template>- </DrawerContent>- </Drawer>-</template>-<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { cloneDeep } from "lodash-es";-import { TrashIcon } from "lucide-vue-next";-import {- NButton,- NInput,- NInputNumber,- NRadio,- NRadioGroup,- NTooltip,-} from "naive-ui";-import { computed, reactive, watch } from "vue";-import { useI18n } from "vue-i18n";-import RequiredStar from "@/components/RequiredStar.vue";-import type { RadioGridOption } from "@/components/v2";-import {- Drawer,- DrawerContent,- MiniActionButton,- RadioGrid,-} from "@/components/v2";-import type {- Algorithm,- Algorithm_InnerOuterMask,- Algorithm_FullMask as FullMask,- Algorithm_MD5Mask as MD5Mask,- Algorithm_RangeMask as RangeMask,-} from "@/types/proto-es/v1/setting_service_pb";-import {- Algorithm_InnerOuterMask_MaskType,- Algorithm_InnerOuterMaskSchema,- Algorithm_RangeMask_SliceSchema,- AlgorithmSchema,- Algorithm_FullMaskSchema as FullMaskSchema,- Algorithm_MD5MaskSchema as MD5MaskSchema,- Algorithm_RangeMaskSchema as RangeMaskSchema,-} from "@/types/proto-es/v1/setting_service_pb";-import type { MaskingType } from "./utils";-import { getMaskingType } from "./utils";--interface MaskingTypeOption extends RadioGridOption<MaskingType> {- value: MaskingType;- label: string;-}--interface LocalState {- processing: boolean;- maskingType: MaskingType;- fullMask: FullMask;- rangeMask: RangeMask;- md5Mask: MD5Mask;- innerOuterMask: Algorithm_InnerOuterMask;-}--const props = defineProps<{- show: boolean;- readonly: boolean;- algorithm?: Algorithm;-}>();--defineEmits<{- (event: "dismiss"): void;- (event: "apply", algorithm: Algorithm): void;-}>();--const defaultRangeMask = computed(() =>- create(RangeMaskSchema, {- slices: [- create(Algorithm_RangeMask_SliceSchema, {- start: 0,- end: 1,- substitution: "*",- }),- ],- })-);--const defaultInnerOuterMask = computed(() =>- create(Algorithm_InnerOuterMaskSchema, {- prefixLen: 0,- suffixLen: 0,- type: Algorithm_InnerOuterMask_MaskType.INNER,- substitution: "*",- })-);--const state = reactive<LocalState>({- processing: false,- maskingType: "full-mask",- fullMask: create(FullMaskSchema, {}),- rangeMask: cloneDeep(defaultRangeMask.value),- md5Mask: create(MD5MaskSchema, {}),- innerOuterMask: cloneDeep(defaultInnerOuterMask.value),-});--const { t } = useI18n();--const maskingTypeList = computed((): MaskingTypeOption[] => [- {- value: "full-mask",- label: t("settings.sensitive-data.algorithms.full-mask.self"),- },- {- value: "range-mask",- label: t("settings.sensitive-data.algorithms.range-mask.self"),- },- {- value: "md5-mask",- label: t("settings.sensitive-data.algorithms.md5-mask.self"),- },- {- value: "inner-outer-mask",- label: t("settings.sensitive-data.algorithms.inner-outer-mask.self"),- },-]);--watch(- () => props.algorithm,- (algorithm) => {- state.maskingType = getMaskingType(algorithm) ?? "full-mask";- state.fullMask =- algorithm?.mask?.case === "fullMask"- ? algorithm.mask.value- : create(FullMaskSchema, {});- state.rangeMask =- algorithm?.mask?.case === "rangeMask"- ? algorithm.mask.value- : cloneDeep(defaultRangeMask.value);- state.md5Mask =- algorithm?.mask?.case === "md5Mask"- ? algorithm.mask.value- : create(MD5MaskSchema, {});- state.innerOuterMask =- algorithm?.mask?.case === "innerOuterMask"- ? algorithm.mask.value- : cloneDeep(defaultInnerOuterMask.value);- }-);--const maskingAlgorithm = computed((): Algorithm => {- switch (state.maskingType) {- case "full-mask":- return create(AlgorithmSchema, {- mask: {- case: "fullMask",- value: state.fullMask,- },- });- case "range-mask":- return create(AlgorithmSchema, {- mask: {- case: "rangeMask",- value: state.rangeMask,- },- });- case "md5-mask":- return create(AlgorithmSchema, {- mask: {- case: "md5Mask",- value: state.md5Mask,- },- });- case "inner-outer-mask":- return create(AlgorithmSchema, {- mask: {- case: "innerOuterMask",- value: state.innerOuterMask,- },- });- default:- return create(AlgorithmSchema, {- mask: {- case: "fullMask",- value: create(FullMaskSchema, {}),- },- });- }-});--const rangeMaskErrorMessage = computed(() => {- if (state.rangeMask.slices.length === 0) {- return t("settings.sensitive-data.algorithms.error.slice-required");- }- for (let i = 0; i < state.rangeMask.slices.length; i++) {- const slice = state.rangeMask.slices[i];- if (Number.isNaN(slice.start) || Number.isNaN(slice.end)) {- return t("settings.sensitive-data.algorithms.error.slice-invalid-number");- }-- for (let j = 0; j < i; j++) {- const pre = state.rangeMask.slices[j];- if (slice.start >= pre.end || pre.start >= slice.end) {- continue;- }- return t("settings.sensitive-data.algorithms.error.slice-overlap");- }-- if (!slice.substitution) {- return t(- "settings.sensitive-data.algorithms.error.substitution-required"- );- }- if (slice.substitution.length > 16) {- return t("settings.sensitive-data.algorithms.error.substitution-length");- }- }- return "";-});--const errorMessage = computed(() => {- switch (state.maskingType) {- case "full-mask":- if (!state.fullMask.substitution) {- return t(- "settings.sensitive-data.algorithms.error.substitution-required"- );- }- if (state.fullMask.substitution.length > 16) {- return t(- "settings.sensitive-data.algorithms.error.substitution-length"- );- }- return "";- case "md5-mask":- if (!state.md5Mask.salt) {- return t("settings.sensitive-data.algorithms.error.salt-required");- }- return "";- case "range-mask":- return rangeMaskErrorMessage.value;- case "inner-outer-mask":- if (!state.innerOuterMask.substitution) {- return t(- "settings.sensitive-data.algorithms.error.substitution-required"- );- }- if (state.innerOuterMask.substitution.length > 16) {- return t(- "settings.sensitive-data.algorithms.error.substitution-length"- );- }- return "";- }- return "";-});--const isSubmitDisabled = computed(() => {- if (props.readonly || state.processing) {- return true;- }-- return !!errorMessage.value;-});--const onMaskingTypeChange = (maskingType: MaskingType) => {- if (state.processing || props.readonly) {- return;- }- switch (maskingType) {- case "full-mask":- state.fullMask = create(FullMaskSchema, {});- break;- case "range-mask":- state.rangeMask = cloneDeep(defaultRangeMask.value);- break;- case "md5-mask":- state.md5Mask = create(MD5MaskSchema, {});- break;- case "inner-outer-mask":- state.innerOuterMask = cloneDeep(defaultInnerOuterMask.value);- break;- }- state.maskingType = maskingType;-};--const addSlice = () => {- const last = state.rangeMask.slices[state.rangeMask.slices.length - 1];- state.rangeMask.slices.push(- create(Algorithm_RangeMask_SliceSchema, {- start: (last?.start ?? -1) + 1,- end: (last?.end ?? 0) + 1,- substitution: "*",- })- );-};--const removeSlice = (i: number) => {- state.rangeMask.slices.splice(i, 1);-};--const onSliceStartChange = (index: number, val: number | null) => {- if (val === null || Number.isNaN(val)) {- return;- }- const slice = state.rangeMask.slices[index];- slice.start = val;- if (slice.end <= slice.start) {- slice.end = slice.start + 1;- }-};--const onSliceEndChange = (index: number, val: number | null) => {- if (val === null || Number.isNaN(val)) {- return;- }- const slice = state.rangeMask.slices[index];- slice.end = val;-};--const onPrefixChange = (val: number) => {- if (val === null || Number.isNaN(val) || val < 0) {- return;- }- state.innerOuterMask.prefixLen = val;-};--const onSuffixChange = (val: number) => {- if (val === null || Number.isNaN(val) || val < 0) {- return;- }- state.innerOuterMask.suffixLen = val;-};-</script>diff --git a/frontend/src/components/SensitiveData/components/SemanticTemplateDrawer.vue b/frontend/src/components/SensitiveData/components/SemanticTemplateDrawer.vuedeleted file mode 100644index 0324c7ec10..0000000000--- a/frontend/src/components/SensitiveData/components/SemanticTemplateDrawer.vue+++ /dev/null@@ -1,66 +0,0 @@-<template>- <Drawer :show="show" @close="$emit('dismiss')">- <DrawerContent- :title="$t('settings.sensitive-data.semantic-types.add-from-template')"- class="max-w-[100vw]"- >- <div class="w-2xl flex flex-col gap-y-4">- <p class="textinfolabel">- {{- $t("settings.sensitive-data.semantic-types.template.description")- }}- </p>- <SemanticTypesTable- :readonly="true"- :row-clickable="true"- :semantic-item-list="semanticTemplateList"- @select="onApply($event)"- />- </div>- <template #footer>- <div class="w-full flex justify-between items-center">- <div class="w-full flex justify-end items-center gap-x-2">- <NButton @click.prevent="$emit('dismiss')">- {{ $t("common.cancel") }}- </NButton>- </div>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script setup lang="ts">-import { NButton } from "naive-ui";-import { computed } from "vue";-import { Drawer, DrawerContent } from "@/components/v2";-import { getSemanticTemplateList } from "@/types";-import type { SemanticTypeSetting_SemanticType } from "@/types/proto-es/v1/setting_service_pb";-import type { SemanticItem } from "./SemanticTypesTable.vue";-import SemanticTypesTable from "./SemanticTypesTable.vue";--defineProps<{- show: boolean;-}>();--const emit = defineEmits<{- (event: "dismiss"): void;- (event: "apply", item: SemanticTypeSetting_SemanticType): void;-}>();--const semanticTemplateList = computed((): SemanticItem[] =>- getSemanticTemplateList().map((item) => ({- dirty: false,- item,- mode: "NORMAL",- }))-);--const onApply = (id: string) => {- const data = semanticTemplateList.value.find((data) => data.item.id === id);- if (data) {- emit("apply", data.item);- }- emit("dismiss");-};-</script>diff --git a/frontend/src/components/SensitiveData/components/SemanticTypesTable.vue b/frontend/src/components/SensitiveData/components/SemanticTypesTable.vuedeleted file mode 100644index e0419c52d1..0000000000--- a/frontend/src/components/SensitiveData/components/SemanticTypesTable.vue+++ /dev/null@@ -1,374 +0,0 @@-<template>- <NDataTable- :size="size"- :data="semanticItemList"- :columns="columnList"- :striped="true"- :bordered="true"- :row-props="rowProps"- :row-key="(item: SemanticItem) => item.item.id"- />-- <MaskingAlgorithmsCreateDrawer- :show="state.pendingEditSemanticIndex !== undefined"- :algorithm="- state.pendingEditSemanticIndex !== undefined- ? getMaskingType(- semanticItemList[state.pendingEditSemanticIndex].item.algorithm- )- ? semanticItemList[state.pendingEditSemanticIndex].item.algorithm- : undefined- : undefined- "- :readonly="readonly"- @apply="onAlgorithmUpsert"- @dismiss="onDrawerDismiss"- />-</template>--<script lang="tsx" setup>-import {- CheckIcon,- InfoIcon,- PencilIcon,- TrashIcon,- Undo2Icon,-} from "lucide-vue-next";-import type { DataTableColumn } from "naive-ui";-import { NDataTable, NInput, NPopconfirm, NTooltip } from "naive-ui";-import { computed, reactive } from "vue";-import { useI18n } from "vue-i18n";-import { MiniActionButton } from "@/components/v2";-import {- type Algorithm,- type SemanticTypeSetting_SemanticType,-} from "@/types/proto-es/v1/setting_service_pb";-import IconSelector from "./IconSelector.vue";-import MaskingAlgorithmsCreateDrawer from "./MaskingAlgorithmsCreateDrawer.vue";-import { getMaskingType } from "./utils";--type SemanticItemMode = "NORMAL" | "CREATE" | "EDIT";--export interface SemanticItem {- mode: SemanticItemMode;- dirty: boolean;- item: SemanticTypeSetting_SemanticType;-}--interface LocalState {- pendingEditSemanticIndex?: number;- processing: boolean;-}--const props = withDefaults(- defineProps<{- size?: "small" | "medium" | "large";- readonly: boolean;- semanticItemList: SemanticItem[];- rowClickable: boolean;- }>(),- { size: "medium" }-);--const emit = defineEmits<{- (event: "select", id: string): void;- (event: "remove", index: number): void;- (event: "cancel", index: number): void;- (event: "confirm", index: number): void;-}>();--const state = reactive<LocalState>({- processing: false,-});--const { t } = useI18n();--const onDrawerDismiss = () => {- state.pendingEditSemanticIndex = undefined;-};--const isBuiltinSemanticType = (item: SemanticTypeSetting_SemanticType) => {- return item.id.startsWith("bb.");-};--const isReadonly = (item: SemanticTypeSetting_SemanticType) => {- return props.readonly || isBuiltinSemanticType(item);-};--const onAlgorithmUpsert = async (maskingAlgorithm: Algorithm) => {- if (state.pendingEditSemanticIndex === undefined) {- return;- }- onInput(- state.pendingEditSemanticIndex,- (data) => (data.item.algorithm = maskingAlgorithm)- );- if (- !isConfirmDisabled(props.semanticItemList[state.pendingEditSemanticIndex])- ) {- emit("confirm", state.pendingEditSemanticIndex);- }- onDrawerDismiss();-};--const columnList = computed(() => {- const columns: DataTableColumn<SemanticItem>[] = [- {- key: "icon",- title: t("settings.sensitive-data.semantic-types.table.icon"),- width: 80,- align: "center",- render: (item, row) => {- if (item.mode === "NORMAL") {- if (item.item.icon) {- return (- <div class="flex items-center justify-center">- <img- src={item.item.icon}- class="w-6 h-6 object-contain"- alt=""- />- </div>- );- }- return (- <div class="flex items-center justify-center">- <span class="text-gray-400">-</span>- </div>- );- }- // For edit mode, show IconSelector- return (- <IconSelector- value={item.item.icon || ""}- onUpdate:value={(val: string) =>- onInput(row, (data) => (data.item.icon = val))- }- />- );- },- },- {- key: "id",- title: "ID",- width: 150,- resizable: true,- ellipsis: {- tooltip: true,- },- render: (item) => item.item.id,- },- {- key: "title",- title: t("settings.sensitive-data.semantic-types.table.semantic-type"),- width: "minmax(min-content, auto)",- resizable: true,- ellipsis: {- tooltip: true,- },- render: (item, row) => {- if (item.mode === "NORMAL") {- return item.item.title;- }- return (- <NInput- value={item.item.title}- size="small"- type="text"- placeholder={t(- "settings.sensitive-data.semantic-types.table.semantic-type"- )}- onInput={(val: string) =>- onInput(row, (data) => (data.item.title = val))- }- />- );- },- },- {- key: "description",- title: t("settings.sensitive-data.semantic-types.table.description"),- width: 200,- resizable: true,- ellipsis: {- tooltip: true,- },- render: (item, row) => {- if (item.mode === "NORMAL") {- return item.item.description;- }- return (- <NInput- value={item.item.description}- size="small"- type="text"- placeholder={t(- "settings.sensitive-data.semantic-types.table.description"- )}- onInput={(val: string) =>- onInput(row, (data) => (data.item.description = val))- }- />- );- },- },- ];-- columns.push({- key: "algorithm",- title: t("settings.sensitive-data.semantic-types.table.masking-algorithm"),- width: "minmax(min-content, auto)",- resizable: true,- render: (item, row) => {- return (- <div class="flex items-center gap-x-1">- {isBuiltinSemanticType(item.item) ? (- <h3>- {t(- `dynamic.settings.sensitive-data.semantic-types.template.${item.item.id.split(".").join("-")}.title`- )}- </h3>- ) : (- <h3>- {getMaskingType(item.item.algorithm)- ? t(- `settings.sensitive-data.algorithms.${getMaskingType(item.item.algorithm)?.toLowerCase()}.self`- )- : "N/A"}- </h3>- )}- {isBuiltinSemanticType(item.item) && (- <NTooltip>- {{- trigger: () => <InfoIcon class="w-4" />,- default: () => (- <div class="whitespace-pre-line">- {t(- `dynamic.settings.sensitive-data.semantic-types.template.${item.item.id.split(".").join("-")}.algorithm.description`- )}- </div>- ),- }}- </NTooltip>- )}- {!isReadonly(item.item) && (- <MiniActionButton- onClick={() => {- state.pendingEditSemanticIndex = row;- }}- >- <PencilIcon class="w-4 h-4" />- </MiniActionButton>- )}- </div>- );- },- });-- if (!props.readonly) {- // operation.- columns.push({- align: "right",- key: "operation",- title: t("common.edit"),- width: 100,- render: (item, row) => {- if (isBuiltinSemanticType(item.item)) {- return (- <NPopconfirm onPositiveClick={() => emit("remove", row)}>- {{- trigger: () => {- return (- <MiniActionButton type="error">- <TrashIcon class="w-4 h-4" />- </MiniActionButton>- );- },- default: () => (- <div class="whitespace-nowrap">- {t("settings.sensitive-data.semantic-types.table.delete")}- </div>- ),- }}- </NPopconfirm>- );- }-- return (- <div class="flex shrink gap-x-2 items-center justify-end">- {item.mode !== "NORMAL" && (- <MiniActionButton onClick={() => emit("cancel", row)}>- <Undo2Icon class="w-4 h-4" />- </MiniActionButton>- )}- {item.mode === "EDIT" && (- <NPopconfirm onPositiveClick={() => emit("remove", row)}>- {{- trigger: () => {- return (- <MiniActionButton type="error">- <TrashIcon class="w-4 h-4" />- </MiniActionButton>- );- },- default: () => (- <div class="whitespace-nowrap">- {t("settings.sensitive-data.semantic-types.table.delete")}- </div>- ),- }}- </NPopconfirm>- )}- {item.mode !== "NORMAL" && (- <MiniActionButton- type={"primary"}- disabled={isConfirmDisabled(item)}- onClick={() => emit("confirm", row)}- >- <CheckIcon class="w-4 h-4" />- </MiniActionButton>- )}- {item.mode === "NORMAL" && (- <MiniActionButton onClick={() => (item.mode = "EDIT")}>- <PencilIcon class="w-4 h-4" />- </MiniActionButton>- )}- </div>- );- },- });- }- return columns;-});--const rowProps = (item: SemanticItem) => {- return {- style: props.rowClickable ? "cursor: pointer;" : "",- onClick: () => {- if (!props.rowClickable) {- return;- }- emit("select", item.item.id);- },- };-};--const onInput = (index: number, callback: (item: SemanticItem) => void) => {- const item = props.semanticItemList[index];- if (!item) {- return;- }- callback(item);- item.dirty = true;-};--const isConfirmDisabled = (data: SemanticItem): boolean => {- if (!data.item.title) {- return true;- }- if (data.mode === "EDIT" && !data.dirty) {- return true;- }- return false;-};-</script>diff --git a/frontend/src/components/SensitiveData/index.ts b/frontend/src/components/SensitiveData/index.tsindex 06648a0087..dff5368db7 100644--- a/frontend/src/components/SensitiveData/index.ts+++ b/frontend/src/components/SensitiveData/index.ts@@ -1,5 +1,4 @@import ClassificationView from "./ClassificationView.vue";import GlobalMaskingRulesView from "./GlobalMaskingRulesView.vue";-import SemanticTypesView from "./SemanticTypesView.vue";-export { GlobalMaskingRulesView, SemanticTypesView, ClassificationView };+export { GlobalMaskingRulesView, ClassificationView };diff --git a/frontend/src/components/SensitiveData/useSemanticType.ts b/frontend/src/components/SensitiveData/useSemanticType.tsdeleted file mode 100644index 604a1264be..0000000000--- a/frontend/src/components/SensitiveData/useSemanticType.ts+++ /dev/null@@ -1,48 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { computed, type MaybeRef, unref, watchEffect } from "vue";-import { useSettingV1Store } from "@/store";-import {- SemanticTypeSetting_SemanticTypeSchema,- Setting_SettingName,-} from "@/types/proto-es/v1/setting_service_pb";-import { hasWorkspacePermissionV2 } from "@/utils";--export const useSemanticType = (semanticTypeId: MaybeRef<string>) => {- const settingV1Store = useSettingV1Store();-- watchEffect(async () => {- await settingV1Store.getOrFetchSettingByName(- Setting_SettingName.SEMANTIC_TYPES,- /* silent */ true- );- });-- const semanticTypeList = computed(() => {- const setting = settingV1Store.getSettingByName(- Setting_SettingName.SEMANTIC_TYPES- );- if (setting?.value?.value?.case === "semanticType") {- return setting.value.value.value.types ?? [];- }- return [];- });-- const semanticType = computed(() => {- const id = unref(semanticTypeId);- if (!id) {- return;- }- if (!hasWorkspacePermissionV2("bb.settings.get")) {- return create(SemanticTypeSetting_SemanticTypeSchema, {- id,- title: id,- });- }- return semanticTypeList.value.find((data) => data.id === id);- });-- return {- semanticTypeList,- semanticType,- };-};diff --git a/frontend/src/react/i18n.ts b/frontend/src/react/i18n.tsindex 90ba6a3be9..21b037f89f 100644--- a/frontend/src/react/i18n.ts+++ b/frontend/src/react/i18n.ts@@ -32,12 +32,13 @@ function buildResources() {const resources: Record<string, { translation: Record<string, unknown> }> ={};for (const [locale, data] of Object.entries(- rawLocales as Record<string, { main: string; sub: string }>+ rawLocales as Record<string, { main: string; sub: string; dynamic: string }>)) {const main = JSON.parse(data.main);const sub = JSON.parse(data.sub);+ const dynamic = JSON.parse(data.dynamic);resources[locale] = {- translation: merge({}, main, { subscription: sub }),+ translation: merge({}, main, { subscription: sub }, { dynamic }),};}return resources;diff --git a/frontend/src/react/pages/settings/SemanticTypesPage.tsx b/frontend/src/react/pages/settings/SemanticTypesPage.tsxnew file mode 100644index 0000000000..56479eb88d--- /dev/null+++ b/frontend/src/react/pages/settings/SemanticTypesPage.tsx@@ -0,0 +1,1531 @@+import { create } from "@bufbuild/protobuf";+import { Check, Info, Pencil, Plus, Trash2, Undo2, X } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { v4 as uuidv4 } from "uuid";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { useVueState } from "@/react/hooks/useVueState";+import {+ pushNotification,+ useActuatorV1Store,+ useSettingV1Store,+ useSubscriptionV1Store,+} from "@/store";+import { getSemanticTemplateList, instanceLimitFeature } from "@/types";+import type {+ Algorithm,+ SemanticTypeSetting_SemanticType,+} from "@/types/proto-es/v1/setting_service_pb";+import {+ Algorithm_InnerOuterMask_MaskType,+ Algorithm_InnerOuterMaskSchema,+ Algorithm_RangeMask_SliceSchema,+ AlgorithmSchema,+ Algorithm_FullMaskSchema as FullMaskSchema,+ Algorithm_MD5MaskSchema as MD5MaskSchema,+ Algorithm_RangeMaskSchema as RangeMaskSchema,+ SemanticTypeSetting_SemanticTypeSchema,+ Setting_SettingName,+ SettingValueSchema as SettingSettingValueSchema,+} from "@/types/proto-es/v1/setting_service_pb";+import {+ PlanFeature,+ PlanType,+} from "@/types/proto-es/v1/subscription_service_pb";+import { hasWorkspacePermissionV2 } from "@/utils";++type SemanticItemMode = "NORMAL" | "CREATE" | "EDIT";++interface SemanticItem {+ mode: SemanticItemMode;+ dirty: boolean;+ item: SemanticTypeSetting_SemanticType;+}++type MaskingType = "full-mask" | "range-mask" | "md5-mask" | "inner-outer-mask";++function getMaskingType(+ algorithm: Algorithm | undefined+): MaskingType | undefined {+ if (!algorithm?.mask) return undefined;+ switch (algorithm.mask.case) {+ case "fullMask":+ return "full-mask";+ case "rangeMask":+ return "range-mask";+ case "innerOuterMask":+ return "inner-outer-mask";+ case "md5Mask":+ return "md5-mask";+ default:+ return undefined;+ }+}++function isBuiltinSemanticType(item: SemanticTypeSetting_SemanticType) {+ return item.id.startsWith("bb.");+}++function useEscapeKey(onEscape: () => void) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.key === "Escape") onEscape();+ };+ document.addEventListener("keydown", handler);+ return () => document.removeEventListener("keydown", handler);+ }, [onEscape]);+}++function useClickOutside(+ ref: React.RefObject<HTMLElement | null>,+ onClickOutside: () => void+) {+ useEffect(() => {+ // Delay by one frame so the click that opened the popover doesn't+ // immediately trigger the outside-click handler.+ const id = requestAnimationFrame(() => {+ document.addEventListener("mousedown", handler);+ });+ function handler(e: MouseEvent) {+ if (ref.current && !ref.current.contains(e.target as Node)) {+ onClickOutside();+ }+ }+ return () => {+ cancelAnimationFrame(id);+ document.removeEventListener("mousedown", handler);+ };+ }, [ref, onClickOutside]);+}++export function SemanticTypesPage() {+ const { t } = useTranslation();+ const settingStore = useSettingV1Store();++ const subscriptionStore = useSubscriptionV1Store();+ const actuatorStore = useActuatorV1Store();++ const hasPermission = hasWorkspacePermissionV2("bb.policies.update");+ const hasSensitiveDataFeature = useVueState(() =>+ subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING)+ );+ const existInstanceWithoutLicense = useVueState(+ () =>+ actuatorStore.totalInstanceCount > actuatorStore.activatedInstanceCount &&+ instanceLimitFeature.has(PlanFeature.FEATURE_DATA_MASKING)+ );+ const isReadonly = !hasPermission || !hasSensitiveDataFeature;++ const [items, setItems] = useState<SemanticItem[]>([]);+ const [loaded, setLoaded] = useState(false);+ const [showTemplateDrawer, setShowTemplateDrawer] = useState(false);+ const [algorithmDrawer, setAlgorithmDrawer] = useState<{+ index: number;+ algorithm?: Algorithm;+ } | null>(null);++ // Deferred side-effect queue: state updaters push actions here,+ // and a useEffect flushes them after React commits.+ const pendingActionRef = useRef<(() => void)[]>([]);+ useEffect(() => {+ const actions = pendingActionRef.current.splice(0);+ for (const action of actions) action();+ });++ const semanticTypeSettingValue = useVueState(() => {+ const setting = settingStore.getSettingByName(+ Setting_SettingName.SEMANTIC_TYPES+ );+ return setting?.value?.value?.case === "semanticType"+ ? (setting.value.value.value.types ?? [])+ : [];+ });++ useEffect(() => {+ settingStore+ .getOrFetchSettingByName(Setting_SettingName.SEMANTIC_TYPES)+ .then(() => setLoaded(true));+ }, []);++ useEffect(() => {+ if (!loaded) return;+ setItems(+ semanticTypeSettingValue.map((st) => ({+ dirty: false,+ item: st,+ mode: "NORMAL" as const,+ }))+ );+ }, [loaded]);++ const upsertSetting = useCallback(+ async (types: SemanticTypeSetting_SemanticType[], notification: string) => {+ await settingStore.upsertSetting({+ name: Setting_SettingName.SEMANTIC_TYPES,+ value: create(SettingSettingValueSchema, {+ value: {+ case: "semanticType",+ value: { types },+ },+ }),+ });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: notification,+ });+ },+ []+ );++ const onAdd = useCallback(() => {+ setItems((prev) => [+ ...prev,+ {+ mode: "CREATE",+ dirty: false,+ item: create(SemanticTypeSetting_SemanticTypeSchema, {+ id: uuidv4(),+ }),+ },+ ]);+ }, []);++ const onStartEdit = useCallback((index: number) => {+ setItems((prev) => {+ const next = [...prev];+ next[index] = { ...next[index], mode: "EDIT" };+ return next;+ });+ }, []);++ const onRemove = useCallback(+ (index: number) => {+ setItems((prev) => {+ const next = [...prev];+ const removed = next.splice(index, 1)[0];+ if (removed.mode !== "CREATE") {+ const types = next+ .filter((d) => d.mode === "NORMAL")+ .map((d) => d.item);+ pendingActionRef.current.push(() =>+ upsertSetting(types, t("common.deleted"))+ );+ }+ return next;+ });+ },+ [upsertSetting, t]+ );++ const onConfirm = useCallback(+ (index: number) => {+ setItems((prev) => {+ const next = [...prev];+ const item = next[index];+ const wasCreate = item.mode === "CREATE";+ next[index] = { ...item, dirty: false, mode: "NORMAL" };+ const types = next+ .filter((d) => d.mode === "NORMAL")+ .map((d) => d.item);+ const msg = t(wasCreate ? "common.created" : "common.updated");+ pendingActionRef.current.push(() => upsertSetting(types, msg));+ return next;+ });+ },+ [upsertSetting, t]+ );++ const onCancel = useCallback(+ (index: number) => {+ setItems((prev) => {+ const next = [...prev];+ const item = next[index];+ if (item.mode === "CREATE") {+ next.splice(index, 1);+ } else {+ const origin = semanticTypeSettingValue.find(+ (s) => s.id === item.item.id+ );+ if (origin) {+ next[index] = { item: origin, mode: "NORMAL", dirty: false };+ }+ }+ return next;+ });+ },+ [semanticTypeSettingValue]+ );++ const onInput = useCallback(+ (+ index: number,+ updater: (+ item: SemanticTypeSetting_SemanticType+ ) => SemanticTypeSetting_SemanticType+ ) => {+ setItems((prev) => {+ const next = [...prev];+ const current = next[index];+ if (!current) return prev;+ next[index] = {+ ...current,+ dirty: true,+ item: updater(current.item),+ };+ return next;+ });+ },+ []+ );++ const algorithmDrawerRef = useRef(algorithmDrawer);+ algorithmDrawerRef.current = algorithmDrawer;++ const onAlgorithmApply = useCallback(+ (algorithm: Algorithm) => {+ const drawer = algorithmDrawerRef.current;+ if (drawer === null) return;+ const { index } = drawer;+ setItems((prev) => {+ const next = [...prev];+ const current = next[index];+ if (!current) return prev;+ const updated: SemanticItem = {+ ...current,+ dirty: true,+ item: { ...current.item, algorithm },+ };+ if (updated.item.title) {+ updated.dirty = false;+ updated.mode = "NORMAL";+ next[index] = updated;+ const types = next+ .filter((d) => d.mode === "NORMAL")+ .map((d) => d.item);+ const msg = t(+ current.mode === "CREATE" ? "common.created" : "common.updated"+ );+ pendingActionRef.current.push(() => upsertSetting(types, msg));+ } else {+ next[index] = updated;+ }+ return next;+ });+ setAlgorithmDrawer(null);+ },+ [upsertSetting, t]+ );++ const onOpenAlgorithmDrawer = useCallback(+ (index: number, algorithm?: Algorithm) => {+ setAlgorithmDrawer({ index, algorithm });+ },+ []+ );++ const onTemplateApply = useCallback(+ (template: SemanticTypeSetting_SemanticType) => {+ setItems((prev) => {+ if (prev.find((item) => item.item.id === template.id)) {+ pendingActionRef.current.push(() =>+ pushNotification({+ module: "bytebase",+ style: "INFO",+ title: t(+ "settings.sensitive-data.semantic-types.template.duplicate-warning",+ { title: template.title }+ ),+ })+ );+ return prev;+ }+ const newItem: SemanticItem = {+ dirty: false,+ mode: "NORMAL",+ item: create(SemanticTypeSetting_SemanticTypeSchema, {+ ...template,+ }),+ };+ const next = [...prev, newItem];+ const types = next+ .filter((d) => d.mode === "NORMAL")+ .map((d) => d.item);+ pendingActionRef.current.push(() =>+ upsertSetting(types, t("common.created"))+ );+ return next;+ });+ setShowTemplateDrawer(false);+ },+ [upsertSetting, t]+ );++ const isConfirmDisabled = (data: SemanticItem): boolean => {+ if (!data.item.title) return true;+ if (data.mode === "EDIT" && !data.dirty) return true;+ return false;+ };++ return (+ <div className="w-full px-4 py-4 flex flex-col gap-y-4">+ <FeatureAttentionBanner+ hasFeature={hasSensitiveDataFeature}+ existInstanceWithoutLicense={existInstanceWithoutLicense}+ />+ <div className="flex justify-end">+ <div className="flex items-center gap-x-2">+ <Button+ variant="outline"+ disabled={isReadonly}+ onClick={() => setShowTemplateDrawer(true)}+ >+ {t("settings.sensitive-data.semantic-types.use-predefined-type")}+ </Button>+ <Button disabled={isReadonly} onClick={onAdd}>+ <Plus className="h-4 w-4" />+ {t("common.add")}+ </Button>+ </div>+ </div>++ <p className="text-sm text-control-placeholder">+ {t("settings.sensitive-data.semantic-types.label")}+ </p>++ <div className="border border-control-border rounded-md">+ <table className="w-full text-sm">+ <thead>+ <tr className="bg-gray-50 border-b border-control-border">+ <th className="px-3 py-2 font-medium w-20 text-center">+ {t("settings.sensitive-data.semantic-types.table.icon")}+ </th>+ <th className="px-3 py-2 text-left font-medium w-36">ID</th>+ <th className="px-3 py-2 text-left font-medium">+ {t(+ "settings.sensitive-data.semantic-types.table.semantic-type"+ )}+ </th>+ <th className="px-3 py-2 text-left font-medium w-48">+ {t("settings.sensitive-data.semantic-types.table.description")}+ </th>+ <th className="px-3 py-2 text-left font-medium">+ {t(+ "settings.sensitive-data.semantic-types.table.masking-algorithm"+ )}+ </th>+ {!isReadonly && (+ <th className="px-3 py-2 text-right font-medium w-28">+ {t("common.edit")}+ </th>+ )}+ </tr>+ </thead>+ <tbody>+ {items.map((row, index) => (+ <SemanticTypeRow+ key={row.item.id}+ row={row}+ index={index}+ readonly={isReadonly}+ isConfirmDisabled={isConfirmDisabled}+ onInput={onInput}+ onRemove={onRemove}+ onConfirm={onConfirm}+ onCancel={onCancel}+ onStartEdit={onStartEdit}+ onOpenAlgorithmDrawer={onOpenAlgorithmDrawer}+ />+ ))}+ {items.length === 0 && (+ <tr>+ <td+ colSpan={isReadonly ? 5 : 6}+ className="px-3 py-8 text-center text-control-placeholder"+ >+ {t("common.no-data")}+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>++ {showTemplateDrawer && (+ <SemanticTemplateDrawer+ onApply={onTemplateApply}+ onDismiss={() => setShowTemplateDrawer(false)}+ />+ )}++ {algorithmDrawer !== null && (+ <MaskingAlgorithmDrawer+ algorithm={algorithmDrawer.algorithm}+ onApply={onAlgorithmApply}+ onDismiss={() => setAlgorithmDrawer(null)}+ />+ )}+ </div>+ );+}++// --- FeatureAttentionBanner ---++function FeatureAttentionBanner({+ hasFeature,+ existInstanceWithoutLicense,+}: {+ hasFeature: boolean;+ existInstanceWithoutLicense: boolean;+}) {+ const { t } = useTranslation();+ const subscriptionStore = useSubscriptionV1Store();++ const showBanner = !hasFeature || existInstanceWithoutLicense;+ if (!showBanner) return null;++ const isWarning = !hasFeature;+ // eslint-disable-next-line @intlify/vue-i18n/no-missing-keys+ const featureDesc = t(+ "dynamic.subscription.features.FEATURE_DATA_MASKING.desc"+ );++ let description: string;+ if (!hasFeature) {+ const startTrial = subscriptionStore.isTrialing+ ? ""+ : t("subscription.trial-for-days", {+ days: subscriptionStore.trialingDays,+ });+ const requiredPlan = subscriptionStore.getMinimumRequiredPlan(+ PlanFeature.FEATURE_DATA_MASKING+ );+ if (+ requiredPlan === PlanType.FREE &&+ subscriptionStore.hasFeature(PlanFeature.FEATURE_DATA_MASKING)+ ) {+ description = `${featureDesc}\n${startTrial}`;+ } else {+ const trialText = t("subscription.required-plan-with-trial", {+ requiredPlan: t(+ `subscription.plan.${PlanType[requiredPlan].toLowerCase()}.title`+ ),+ startTrial,+ });+ description = `${featureDesc}\n${trialText}`;+ }+ } else {+ const attention = t(+ "subscription.instance-assignment.missing-license-attention"+ );+ description = `${featureDesc}\n${attention}`;+ }++ return (+ <div+ className={`rounded-md border px-4 py-3 text-sm whitespace-pre-line ${+ isWarning+ ? "border-yellow-300 bg-yellow-50 text-yellow-800"+ : "border-blue-200 bg-blue-50 text-blue-800"+ }`}+ >+ {description}+ </div>+ );+}++// --- MaskingAlgorithmDrawer (React) ---++interface MaskingAlgorithmDrawerProps {+ algorithm?: Algorithm;+ onApply: (algorithm: Algorithm) => void;+ onDismiss: () => void;+}++interface RangeMaskSlice {+ start: number;+ end: number;+ substitution: string;+}++function MaskingAlgorithmDrawer({+ algorithm,+ onApply,+ onDismiss,+}: MaskingAlgorithmDrawerProps) {+ const { t } = useTranslation();+ useEscapeKey(onDismiss);++ const initialType = getMaskingType(algorithm) ?? "full-mask";+ const [maskingType, setMaskingType] = useState<MaskingType>(initialType);+ const [fullMaskSubstitution, setFullMaskSubstitution] = useState(+ algorithm?.mask?.case === "fullMask"+ ? (algorithm.mask.value.substitution ?? "")+ : ""+ );+ const [rangeMaskSlices, setRangeMaskSlices] = useState<RangeMaskSlice[]>(+ algorithm?.mask?.case === "rangeMask"+ ? algorithm.mask.value.slices.map((s) => ({+ start: s.start,+ end: s.end,+ substitution: s.substitution,+ }))+ : [{ start: 0, end: 1, substitution: "*" }]+ );+ const [md5Salt, setMd5Salt] = useState(+ algorithm?.mask?.case === "md5Mask" ? (algorithm.mask.value.salt ?? "") : ""+ );+ const [innerOuterType, setInnerOuterType] = useState(+ algorithm?.mask?.case === "innerOuterMask"+ ? algorithm.mask.value.type+ : Algorithm_InnerOuterMask_MaskType.INNER+ );+ const [innerOuterPrefix, setInnerOuterPrefix] = useState(+ algorithm?.mask?.case === "innerOuterMask"+ ? algorithm.mask.value.prefixLen+ : 0+ );+ const [innerOuterSuffix, setInnerOuterSuffix] = useState(+ algorithm?.mask?.case === "innerOuterMask"+ ? algorithm.mask.value.suffixLen+ : 0+ );+ const [innerOuterSubstitution, setInnerOuterSubstitution] = useState(+ algorithm?.mask?.case === "innerOuterMask"+ ? (algorithm.mask.value.substitution ?? "*")+ : "*"+ );++ const maskingTypeOptions: { value: MaskingType; label: string }[] = [+ {+ value: "full-mask",+ label: t("settings.sensitive-data.algorithms.full-mask.self"),+ },+ {+ value: "range-mask",+ label: t("settings.sensitive-data.algorithms.range-mask.self"),+ },+ {+ value: "md5-mask",+ label: t("settings.sensitive-data.algorithms.md5-mask.self"),+ },+ {+ value: "inner-outer-mask",+ label: t("settings.sensitive-data.algorithms.inner-outer-mask.self"),+ },+ ];++ const onMaskingTypeChange = (type: MaskingType) => {+ setMaskingType(type);+ if (type === "full-mask") setFullMaskSubstitution("");+ if (type === "range-mask")+ setRangeMaskSlices([{ start: 0, end: 1, substitution: "*" }]);+ if (type === "md5-mask") setMd5Salt("");+ if (type === "inner-outer-mask") {+ setInnerOuterType(Algorithm_InnerOuterMask_MaskType.INNER);+ setInnerOuterPrefix(0);+ setInnerOuterSuffix(0);+ setInnerOuterSubstitution("*");+ }+ };++ const rangeMaskErrorMessage = useMemo(() => {+ if (rangeMaskSlices.length === 0) {+ return t("settings.sensitive-data.algorithms.error.slice-required");+ }+ for (let i = 0; i < rangeMaskSlices.length; i++) {+ const slice = rangeMaskSlices[i];+ if (Number.isNaN(slice.start) || Number.isNaN(slice.end)) {+ return t(+ "settings.sensitive-data.algorithms.error.slice-invalid-number"+ );+ }+ for (let j = 0; j < i; j++) {+ const pre = rangeMaskSlices[j];+ if (!(slice.start >= pre.end || pre.start >= slice.end)) {+ return t("settings.sensitive-data.algorithms.error.slice-overlap");+ }+ }+ if (!slice.substitution) {+ return t(+ "settings.sensitive-data.algorithms.error.substitution-required"+ );+ }+ if (slice.substitution.length > 16) {+ return t(+ "settings.sensitive-data.algorithms.error.substitution-length"+ );+ }+ }+ return "";+ }, [rangeMaskSlices, t]);++ const errorMessage = useMemo(() => {+ switch (maskingType) {+ case "full-mask":+ if (!fullMaskSubstitution)+ return t(+ "settings.sensitive-data.algorithms.error.substitution-required"+ );+ if (fullMaskSubstitution.length > 16)+ return t(+ "settings.sensitive-data.algorithms.error.substitution-length"+ );+ return "";+ case "md5-mask":+ if (!md5Salt)+ return t("settings.sensitive-data.algorithms.error.salt-required");+ return "";+ case "range-mask":+ return rangeMaskErrorMessage;+ case "inner-outer-mask":+ if (!innerOuterSubstitution)+ return t(+ "settings.sensitive-data.algorithms.error.substitution-required"+ );+ if (innerOuterSubstitution.length > 16)+ return t(+ "settings.sensitive-data.algorithms.error.substitution-length"+ );+ return "";+ }+ return "";+ }, [+ maskingType,+ fullMaskSubstitution,+ md5Salt,+ rangeMaskErrorMessage,+ innerOuterSubstitution,+ t,+ ]);++ const buildAlgorithm = (): Algorithm => {+ switch (maskingType) {+ case "full-mask":+ return create(AlgorithmSchema, {+ mask: {+ case: "fullMask",+ value: create(FullMaskSchema, {+ substitution: fullMaskSubstitution,+ }),+ },+ });+ case "range-mask":+ return create(AlgorithmSchema, {+ mask: {+ case: "rangeMask",+ value: create(RangeMaskSchema, {+ slices: rangeMaskSlices.map((s) =>+ create(Algorithm_RangeMask_SliceSchema, s)+ ),+ }),+ },+ });+ case "md5-mask":+ return create(AlgorithmSchema, {+ mask: {+ case: "md5Mask",+ value: create(MD5MaskSchema, { salt: md5Salt }),+ },+ });+ case "inner-outer-mask":+ return create(AlgorithmSchema, {+ mask: {+ case: "innerOuterMask",+ value: create(Algorithm_InnerOuterMaskSchema, {+ type: innerOuterType,+ prefixLen: innerOuterPrefix,+ suffixLen: innerOuterSuffix,+ substitution: innerOuterSubstitution,+ }),+ },+ });+ }+ };++ const updateSlice = (index: number, patch: Partial<RangeMaskSlice>) => {+ setRangeMaskSlices((prev) => {+ const next = [...prev];+ next[index] = { ...next[index], ...patch };+ return next;+ });+ };++ return (+ <div className="fixed inset-0 z-50 flex justify-end">+ <div className="absolute inset-0 bg-black/40" onClick={onDismiss} />+ <div className="relative w-[40rem] max-w-[calc(100vw-5rem)] bg-white shadow-xl flex flex-col">+ <div className="flex items-center justify-between px-6 py-4 border-b border-control-border">+ <h2 className="text-lg font-medium">+ {algorithm+ ? t("settings.sensitive-data.algorithms.edit")+ : t("settings.sensitive-data.algorithms.add")}+ </h2>+ <button+ className="p-1 rounded hover:bg-gray-200 text-gray-500"+ onClick={onDismiss}+ >+ <X className="w-5 h-5" />+ </button>+ </div>++ <div className="flex-1 overflow-y-auto p-6">+ {/* Masking type selector */}+ <div className="mb-6">+ <label className="text-sm font-medium">+ {t("settings.sensitive-data.algorithms.table.masking-type")}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <div className="grid grid-cols-3 gap-2 mt-2">+ {maskingTypeOptions.map((opt) => (+ <button+ key={opt.value}+ className={`px-3 py-2 text-sm border rounded-md transition-colors ${+ maskingType === opt.value+ ? "border-accent bg-accent/10 text-accent"+ : "border-control-border hover:bg-gray-50"+ }`}+ onClick={() => onMaskingTypeChange(opt.value)}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </div>++ <div className="border-t border-control-border pt-6 flex flex-col gap-y-6">+ {maskingType === "full-mask" && (+ <div>+ <label className="text-sm font-medium">+ {t(+ "settings.sensitive-data.algorithms.full-mask.substitution"+ )}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <p className="text-sm text-control-placeholder mt-1">+ {t(+ "settings.sensitive-data.algorithms.full-mask.substitution-label"+ )}+ </p>+ <Input+ value={fullMaskSubstitution}+ className="mt-2"+ placeholder={t(+ "settings.sensitive-data.algorithms.full-mask.substitution"+ )}+ onChange={(e) => setFullMaskSubstitution(e.target.value)}+ />+ </div>+ )}++ {maskingType === "range-mask" && (+ <>+ <p className="text-sm text-control-placeholder">+ {t("settings.sensitive-data.algorithms.range-mask.label")}+ </p>+ {rangeMaskSlices.map((slice, i) => (+ <div key={i} className="flex gap-x-2 items-end">+ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium">+ {t(+ "settings.sensitive-data.algorithms.range-mask.slice-start"+ )}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <Input+ type="number"+ value={slice.start}+ className="w-20"+ onChange={(e) =>+ updateSlice(i, {+ start: Number(e.target.value),+ end: Math.max(+ Number(e.target.value) + 1,+ slice.end+ ),+ })+ }+ />+ </div>+ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium">+ {t(+ "settings.sensitive-data.algorithms.range-mask.slice-end"+ )}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <Input+ type="number"+ value={slice.end}+ className="w-20"+ onChange={(e) =>+ updateSlice(i, { end: Number(e.target.value) })+ }+ />+ </div>+ <div className="flex-1 flex flex-col gap-y-1">+ <label className="text-sm font-medium">+ {t(+ "settings.sensitive-data.algorithms.range-mask.substitution"+ )}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <Input+ value={slice.substitution}+ onChange={(e) =>+ updateSlice(i, { substitution: e.target.value })+ }+ />+ </div>+ <button+ className="p-1 rounded hover:bg-red-100 text-red-500 mb-0.5"+ onClick={() =>+ setRangeMaskSlices((prev) =>+ prev.filter((_, idx) => idx !== i)+ )+ }+ >+ <Trash2 className="w-4 h-4" />+ </button>+ </div>+ ))}+ {rangeMaskErrorMessage && (+ <p className="text-red-600 text-sm">+ {rangeMaskErrorMessage}+ </p>+ )}+ <Button+ variant="outline"+ className="ml-auto"+ onClick={() =>+ setRangeMaskSlices((prev) => {+ const last = prev[prev.length - 1];+ return [+ ...prev,+ {+ start: (last?.start ?? -1) + 1,+ end: (last?.end ?? 0) + 1,+ substitution: "*",+ },+ ];+ })+ }+ >+ {t("common.add")}+ </Button>+ </>+ )}++ {maskingType === "md5-mask" && (+ <div>+ <label className="text-sm font-medium">+ {t("settings.sensitive-data.algorithms.md5-mask.salt")}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <p className="text-sm text-control-placeholder mt-1">+ {t("settings.sensitive-data.algorithms.md5-mask.salt-label")}+ </p>+ <Input+ value={md5Salt}+ className="mt-2"+ placeholder={t(+ "settings.sensitive-data.algorithms.md5-mask.salt"+ )}+ onChange={(e) => setMd5Salt(e.target.value)}+ />+ </div>+ )}++ {maskingType === "inner-outer-mask" && (+ <>+ <div>+ <label className="text-sm font-medium">+ {t(+ "settings.sensitive-data.algorithms.inner-outer-mask.type"+ )}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <p className="text-sm text-control-placeholder mt-1">+ {innerOuterType === Algorithm_InnerOuterMask_MaskType.INNER+ ? t(+ "settings.sensitive-data.algorithms.inner-outer-mask.inner-label"+ )+ : t(+ "settings.sensitive-data.algorithms.inner-outer-mask.outer-label"+ )}+ </p>+ <div className="flex gap-x-4 mt-2">+ <label className="flex items-center gap-x-2 cursor-pointer">+ <input+ type="radio"+ name="innerOuterType"+ checked={+ innerOuterType ===+ Algorithm_InnerOuterMask_MaskType.INNER+ }+ onChange={() =>+ setInnerOuterType(+ Algorithm_InnerOuterMask_MaskType.INNER+ )+ }+ />+ {t(+ "settings.sensitive-data.algorithms.inner-outer-mask.inner-mask"+ )}+ </label>+ <label className="flex items-center gap-x-2 cursor-pointer">+ <input+ type="radio"+ name="innerOuterType"+ checked={+ innerOuterType ===+ Algorithm_InnerOuterMask_MaskType.OUTER+ }+ onChange={() =>+ setInnerOuterType(+ Algorithm_InnerOuterMask_MaskType.OUTER+ )+ }+ />+ {t(+ "settings.sensitive-data.algorithms.inner-outer-mask.outer-mask"+ )}+ </label>+ </div>+ </div>+ <div className="flex gap-x-2 items-end">+ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium">+ {t(+ "settings.sensitive-data.algorithms.inner-outer-mask.prefix-length"+ )}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <Input+ type="number"+ value={innerOuterPrefix}+ className="w-24"+ onChange={(e) => {+ const val = Number(e.target.value);+ if (!Number.isNaN(val) && val >= 0)+ setInnerOuterPrefix(val);+ }}+ />+ </div>+ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium">+ {t(+ "settings.sensitive-data.algorithms.inner-outer-mask.suffix-length"+ )}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <Input+ type="number"+ value={innerOuterSuffix}+ className="w-24"+ onChange={(e) => {+ const val = Number(e.target.value);+ if (!Number.isNaN(val) && val >= 0)+ setInnerOuterSuffix(val);+ }}+ />+ </div>+ <div className="flex-1 flex flex-col gap-y-1">+ <label className="text-sm font-medium">+ {t(+ "settings.sensitive-data.algorithms.range-mask.substitution"+ )}+ <span className="text-red-500 ml-0.5">*</span>+ </label>+ <Input+ value={innerOuterSubstitution}+ onChange={(e) =>+ setInnerOuterSubstitution(e.target.value)+ }+ />+ </div>+ </div>+ </>+ )}+ </div>+ </div>++ <div className="flex justify-end gap-x-2 px-6 py-4 border-t border-control-border">+ <Button variant="outline" onClick={onDismiss}>+ {t("common.cancel")}+ </Button>+ <Button+ disabled={!!errorMessage}+ onClick={() => onApply(buildAlgorithm())}+ title={errorMessage || undefined}+ >+ {t("common.confirm")}+ </Button>+ </div>+ </div>+ </div>+ );+}++// --- SemanticTemplateDrawer (React) ---++interface SemanticTemplateDrawerProps {+ onApply: (template: SemanticTypeSetting_SemanticType) => void;+ onDismiss: () => void;+}++function SemanticTemplateDrawer({+ onApply,+ onDismiss,+}: SemanticTemplateDrawerProps) {+ const { t } = useTranslation();+ useEscapeKey(onDismiss);+ const templates = useMemo(() => getSemanticTemplateList(), []);++ return (+ <div className="fixed inset-0 z-50 flex justify-end">+ <div className="absolute inset-0 bg-black/40" onClick={onDismiss} />+ <div className="relative w-2xl max-w-[100vw] bg-white shadow-xl flex flex-col">+ <div className="flex items-center justify-between px-6 py-4 border-b border-control-border">+ <h2 className="text-lg font-medium">+ {t("settings.sensitive-data.semantic-types.add-from-template")}+ </h2>+ <button+ className="p-1 rounded hover:bg-gray-200 text-gray-500"+ onClick={onDismiss}+ >+ <X className="w-5 h-5" />+ </button>+ </div>+ <div className="flex-1 overflow-y-auto p-6">+ <p className="text-sm text-control-placeholder mb-4">+ {t("settings.sensitive-data.semantic-types.template.description")}+ </p>+ <div className="border border-control-border rounded-md overflow-hidden">+ <table className="w-full text-sm">+ <thead>+ <tr className="bg-gray-50 border-b border-control-border">+ <th className="px-3 py-2 text-left font-medium">ID</th>+ <th className="px-3 py-2 text-left font-medium">+ {t(+ "settings.sensitive-data.semantic-types.table.semantic-type"+ )}+ </th>+ <th className="px-3 py-2 text-left font-medium">+ {t(+ "settings.sensitive-data.semantic-types.table.description"+ )}+ </th>+ <th className="px-3 py-2 text-left font-medium">+ {t(+ "settings.sensitive-data.semantic-types.table.masking-algorithm"+ )}+ </th>+ </tr>+ </thead>+ <tbody>+ {templates.map((template) => {+ const key = template.id.split(".").join("-");+ return (+ <tr+ key={template.id}+ className="border-b border-control-border last:border-b-0 hover:bg-gray-50 cursor-pointer"+ onClick={() => onApply(template)}+ >+ <td className="px-3 py-2">{template.id}</td>+ <td className="px-3 py-2">{template.title}</td>+ <td className="px-3 py-2">{template.description}</td>+ <td className="px-3 py-2">+ <div className="flex items-center gap-x-1">+ <span>+ {t(+ `dynamic.settings.sensitive-data.semantic-types.template.${key}.title`+ )}+ </span>+ <span+ className="text-gray-400 cursor-help"+ title={t(+ `dynamic.settings.sensitive-data.semantic-types.template.${key}.algorithm.description`+ )}+ >+ <Info className="w-4 h-4" />+ </span>+ </div>+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ </div>+ <div className="flex justify-end px-6 py-4 border-t border-control-border">+ <Button variant="outline" onClick={onDismiss}>+ {t("common.cancel")}+ </Button>+ </div>+ </div>+ </div>+ );+}++// --- SemanticTypeRow ---++interface SemanticTypeRowProps {+ row: SemanticItem;+ index: number;+ readonly: boolean;+ isConfirmDisabled: (data: SemanticItem) => boolean;+ onInput: (+ index: number,+ updater: (+ item: SemanticTypeSetting_SemanticType+ ) => SemanticTypeSetting_SemanticType+ ) => void;+ onRemove: (index: number) => void;+ onConfirm: (index: number) => void;+ onCancel: (index: number) => void;+ onStartEdit: (index: number) => void;+ onOpenAlgorithmDrawer: (index: number, algorithm?: Algorithm) => void;+}++function SemanticTypeRow({+ row,+ index,+ readonly,+ isConfirmDisabled,+ onInput,+ onRemove,+ onConfirm,+ onCancel,+ onStartEdit,+ onOpenAlgorithmDrawer,+}: SemanticTypeRowProps) {+ const { t } = useTranslation();+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);+ const isBuiltin = isBuiltinSemanticType(row.item);+ const isItemReadonly = readonly || isBuiltin;+ const isEditing = row.mode !== "NORMAL";++ return (+ <tr className="border-b border-control-border last:border-b-0 even:bg-gray-50/50">+ <td className="px-3 py-2 text-center">+ {isEditing && !isItemReadonly ? (+ <IconPicker+ value={row.item.icon ?? ""}+ onChange={(icon) => onInput(index, (item) => ({ ...item, icon }))}+ />+ ) : row.item.icon ? (+ <div className="flex items-center justify-center">+ <img+ src={row.item.icon}+ className="w-6 h-6 object-contain"+ alt=""+ />+ </div>+ ) : (+ <span className="text-gray-400">-</span>+ )}+ </td>+ <td className="px-3 py-2 truncate max-w-36" title={row.item.id}>+ {row.item.id}+ </td>+ <td className="px-3 py-2">+ {isEditing ? (+ <Input+ value={row.item.title}+ className="h-8"+ placeholder={t(+ "settings.sensitive-data.semantic-types.table.semantic-type"+ )}+ onChange={(e) =>+ onInput(index, (item) => ({ ...item, title: e.target.value }))+ }+ />+ ) : (+ <span className="truncate">{row.item.title}</span>+ )}+ </td>+ <td className="px-3 py-2">+ {isEditing ? (+ <Input+ value={row.item.description}+ className="h-8"+ placeholder={t(+ "settings.sensitive-data.semantic-types.table.description"+ )}+ onChange={(e) =>+ onInput(index, (item) => ({+ ...item,+ description: e.target.value,+ }))+ }+ />+ ) : (+ <span className="truncate">{row.item.description}</span>+ )}+ </td>+ <td className="px-3 py-2">+ <div className="flex items-center gap-x-1">+ {isBuiltin ? (+ <>+ <span>+ {t(+ `dynamic.settings.sensitive-data.semantic-types.template.${row.item.id.split(".").join("-")}.title`+ )}+ </span>+ <span+ className="text-gray-400 cursor-help"+ title={t(+ `dynamic.settings.sensitive-data.semantic-types.template.${row.item.id.split(".").join("-")}.algorithm.description`+ )}+ >+ <Info className="w-4 h-4" />+ </span>+ </>+ ) : (+ <span>+ {getMaskingType(row.item.algorithm)+ ? t(+ `settings.sensitive-data.algorithms.${getMaskingType(row.item.algorithm)?.toLowerCase()}.self`+ )+ : "N/A"}+ </span>+ )}+ {!isItemReadonly && (+ <button+ className="p-1 rounded hover:bg-gray-200 text-gray-500"+ onClick={() => {+ const algo = getMaskingType(row.item.algorithm)+ ? row.item.algorithm+ : undefined;+ onOpenAlgorithmDrawer(index, algo);+ }}+ >+ <Pencil className="w-4 h-4" />+ </button>+ )}+ </div>+ </td>+ {!readonly && (+ <td className="px-3 py-2">+ <div className="flex items-center justify-end gap-x-1">+ {isBuiltin ? (+ <DeleteConfirmButton+ show={showDeleteConfirm}+ onShowChange={setShowDeleteConfirm}+ message={t(+ "settings.sensitive-data.semantic-types.table.delete"+ )}+ onConfirm={() => onRemove(index)}+ />+ ) : (+ <>+ {isEditing && (+ <button+ className="p-1 rounded hover:bg-gray-200 text-gray-500"+ onClick={() => onCancel(index)}+ >+ <Undo2 className="w-4 h-4" />+ </button>+ )}+ {row.mode === "EDIT" && (+ <DeleteConfirmButton+ show={showDeleteConfirm}+ onShowChange={setShowDeleteConfirm}+ message={t(+ "settings.sensitive-data.semantic-types.table.delete"+ )}+ onConfirm={() => onRemove(index)}+ />+ )}+ {isEditing && (+ <button+ className="p-1 rounded hover:bg-accent/10 text-accent disabled:opacity-50 disabled:cursor-not-allowed"+ disabled={isConfirmDisabled(row)}+ onClick={() => onConfirm(index)}+ >+ <Check className="w-4 h-4" />+ </button>+ )}+ {row.mode === "NORMAL" && (+ <button+ className="p-1 rounded hover:bg-gray-200 text-gray-500"+ onClick={() => onStartEdit(index)}+ >+ <Pencil className="w-4 h-4" />+ </button>+ )}+ </>+ )}+ </div>+ </td>+ )}+ </tr>+ );+}++// --- DeleteConfirmButton ---++// --- IconPicker ---++const SUPPORTED_IMAGE_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp", ".svg"];+const MAX_FILE_SIZE_BYTES = 2 * 1024 * 1024; // 2 MiB++interface IconPickerProps {+ value: string;+ onChange: (base64: string) => void;+}++function IconPicker({ value, onChange }: IconPickerProps) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const [tempValue, setTempValue] = useState(value);+ const popoverRef = useRef<HTMLDivElement>(null);+ const fileInputRef = useRef<HTMLInputElement>(null);+ const dismiss = useCallback(() => setOpen(false), []);+ useClickOutside(popoverRef, dismiss);++ const handleOpen = () => {+ setTempValue(value);+ setOpen(true);+ };++ const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file) return;+ if (file.size > MAX_FILE_SIZE_BYTES) return;+ const reader = new FileReader();+ reader.onload = () => setTempValue(reader.result as string);+ reader.readAsDataURL(file);+ // Reset input so the same file can be re-selected+ e.target.value = "";+ };++ return (+ <div className="relative flex items-center justify-center" ref={popoverRef}>+ {value ? (+ <div className="flex items-center gap-1">+ <img src={value} className="w-6 h-6 object-contain" alt="" />+ <button+ className="p-0.5 rounded hover:bg-gray-200 text-gray-500"+ onClick={handleOpen}+ >+ <Pencil className="w-3 h-3" />+ </button>+ </div>+ ) : (+ <button+ className="p-1 rounded hover:bg-gray-200 text-gray-500"+ onClick={handleOpen}+ >+ <Pencil className="w-4 h-4" />+ </button>+ )}+ {open && (+ <div className="absolute left-0 top-full z-20 mt-1 bg-white border border-control-border rounded-md shadow-lg p-3">+ <div+ className="w-48 h-48 flex justify-center items-center border border-dashed border-gray-300 rounded-md relative cursor-pointer"+ onClick={() => fileInputRef.current?.click()}+ >+ {tempValue ? (+ <div+ className="w-1/3 h-1/3 bg-no-repeat bg-contain bg-center rounded-md"+ style={{ backgroundImage: `url(${tempValue})` }}+ />+ ) : (+ <span className="text-sm text-gray-400">+ {t("common.upload")}+ </span>+ )}+ <input+ ref={fileInputRef}+ type="file"+ className="hidden"+ accept={SUPPORTED_IMAGE_EXTENSIONS.join(",")}+ onChange={handleFileSelect}+ />+ </div>+ <div className="flex justify-end gap-x-2 mt-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => setTempValue("")}+ >+ {t("common.clear")}+ </Button>+ <Button variant="outline" size="sm" onClick={() => setOpen(false)}>+ {t("common.cancel")}+ </Button>+ <Button+ size="sm"+ onClick={() => {+ onChange(tempValue);+ setOpen(false);+ }}+ >+ {t("common.confirm")}+ </Button>+ </div>+ </div>+ )}+ </div>+ );+}++// --- DeleteConfirmButton ---++interface DeleteConfirmButtonProps {+ show: boolean;+ onShowChange: (show: boolean) => void;+ message: string;+ onConfirm: () => void;+}++function DeleteConfirmButton({+ show,+ onShowChange,+ message,+ onConfirm,+}: DeleteConfirmButtonProps) {+ const { t } = useTranslation();+ const popoverRef = useRef<HTMLDivElement>(null);+ const dismiss = useCallback(() => onShowChange(false), [onShowChange]);+ useClickOutside(popoverRef, dismiss);++ return (+ <div className="relative" ref={popoverRef}>+ <button+ className="p-1 rounded hover:bg-red-100 text-red-500"+ onClick={() => onShowChange(!show)}+ >+ <Trash2 className="w-4 h-4" />+ </button>+ {show && (+ <div className="absolute right-0 top-full z-10 mt-1 bg-white border border-control-border rounded-md shadow-lg p-3 whitespace-nowrap">+ <p className="text-sm mb-2">{message}</p>+ <div className="flex justify-end gap-x-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => onShowChange(false)}+ >+ {t("common.cancel")}+ </Button>+ <Button+ variant="destructive"+ size="sm"+ onClick={() => {+ onConfirm();+ onShowChange(false);+ }}+ >+ {t("common.confirm")}+ </Button>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.tsindex 93f8febe50..1784c8b1b3 100644--- a/frontend/src/router/dashboard/workspace.ts+++ b/frontend/src/router/dashboard/workspace.ts@@ -271,8 +271,8 @@ const workspaceRoutes: RouteRecordRaw[] = [title: () => t("settings.sensitive-data.semantic-types.self"),requiredPermissionList: () => ["bb.settings.get"],},- component: () => import("@/views/SettingWorkspaceSemanticTypes.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: () => ({ page: "SemanticTypesPage" }),},{path: "data-classification",diff --git a/frontend/src/views/SettingWorkspaceSemanticTypes.vue b/frontend/src/views/SettingWorkspaceSemanticTypes.vuedeleted file mode 100644index ce7e06105b..0000000000--- a/frontend/src/views/SettingWorkspaceSemanticTypes.vue+++ /dev/null@@ -1,12 +0,0 @@-<template>- <div class="w-full px-4 py-4 flex flex-col gap-y-4">- <FeatureAttention :feature="PlanFeature.FEATURE_DATA_MASKING" />- <SemanticTypesView />- </div>-</template>--<script lang="tsx" setup>-import { FeatureAttention } from "@/components/FeatureGuard";-import { SemanticTypesView } from "@/components/SensitiveData";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-</script>diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex aca798df8d..f8daa2a799 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -41,7 +41,10 @@ export default defineConfig({if (id !== "\0virtual:react-locales") return undefined;const localesDir = resolve(__dirname, "src/locales");const locales = ["en-US", "zh-CN", "es-ES", "ja-JP", "vi-VN"];- const data: Record<string, { main: string; sub: string }> = {};+ const data: Record<+ string,+ { main: string; sub: string; dynamic: string }+ > = {};for (const locale of locales) {data[locale] = {main: readFileSync(`${localesDir}/${locale}.json`, "utf-8"),@@ -49,6 +52,10 @@ export default defineConfig({`${localesDir}/subscription/${locale}.json`,"utf-8"),+ dynamic: readFileSync(+ `${localesDir}/dynamic/${locale}.json`,+ "utf-8"+ ),};}return `export default ${JSON.stringify(data)};`;