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 projects page to React (#19787)
Danny Xudd420a0d0da4
diff --git a/frontend/eslint.config.mjs b/frontend/eslint.config.mjsindex b1b5750f45..f5b408ed85 100644--- a/frontend/eslint.config.mjs+++ b/frontend/eslint.config.mjs@@ -33,7 +33,14 @@ export default [{src: "./src",extensions: [".js", ".vue", ".ts", ".tsx"],- ignores: [],+ ignores: [+ // Used in React .tsx via tVue() wrapper — linter can't detect these+ "project.batch.selected",+ "project.batch.archive.title",+ "project.batch.archive.success",+ "project.batch.delete.title",+ "project.batch.delete.success",+ ],enableFix: true,},],diff --git a/frontend/src/components/v2/Model/Project/ProjectOperations.vue b/frontend/src/components/v2/Model/Project/ProjectOperations.vuedeleted file mode 100644index 5e7bb935ec..0000000000--- a/frontend/src/components/v2/Model/Project/ProjectOperations.vue+++ /dev/null@@ -1,255 +0,0 @@-<template>- <div- v-bind="$attrs"- class="text-sm flex flex-col lg:flex-row items-start lg:items-center bg-blue-100 py-3 px-4 text-main gap-y-2 gap-x-4 overflow-x-auto"- >- <span class="whitespace-nowrap">- {{ $t("project.batch.selected", { count: projectList.length }) }}- </span>- <div class="flex items-center gap-x-2">- <template v-for="action in actions" :key="action.text">- <component :is="action.render()" v-if="action.render" />- <NButton- v-else- quaternary- size="small"- type="primary"- :disabled="action.disabled"- @click="action.click"- >- <template v-if="action.icon" #icon>- <component :is="action.icon" class="h-4 w-4" />- </template>- <span class="text-sm">{{ action.text }}</span>- </NButton>- </template>- </div>- </div>-- <BBAlert- v-model:show="state.showArchiveConfirm"- type="warning"- :title="$t('project.batch.archive.title', { count: projectList.length })"- :description="$t('project.batch.archive.description')"- :ok-text="$t('common.archive')"- @ok="handleBatchArchive"- @cancel="state.showArchiveConfirm = false"- >- <!-- Project List -->- <div class="flex flex-col gap-y-3">- <div class="max-h-40 overflow-y-auto border rounded-sm p-2 bg-gray-50">- <div class="text-xs font-medium text-gray-600 mb-2">- {{ $t("project.batch.projects-to-archive") }}:- </div>- <div class="flex flex-col gap-y-1">- <div- v-for="project in projectList"- :key="project.name"- class="text-sm flex items-center gap-x-2"- >- <CheckIcon class="w-3 h-3 text-green-600" />- <span>{{ project.title }}</span>- <span class="text-gray-500"- >({{ extractProjectResourceName(project.name) }})</span- >- </div>- </div>- </div>-- <!-- Warning for projects with resources -->- <NAlert- v-if="projectsWithResources.length > 0"- type="warning"- size="small"- >- <template #header>- {{ $t("project.batch.resource-warning.title") }}- </template>- <div class="text-sm">- {{ $t("project.batch.resource-warning.description") }}- <ul class="mt-1 list-disc list-inside">- <li v-for="project in projectsWithResources" :key="project.name">- {{ project.title }} ({{- extractProjectResourceName(project.name)- }})- </li>- </ul>- </div>- </NAlert>- </div>- </BBAlert>-- <BBAlert- v-model:show="state.showDeleteConfirm"- type="error"- :title="$t('project.batch.delete.title', { count: projectList.length })"- :description="$t('project.batch.delete.description')"- :ok-text="$t('common.delete')"- @ok="handleBatchDelete"- @cancel="state.showDeleteConfirm = false"- >- <!-- Project List -->- <div class="flex flex-col gap-y-3">- <div class="max-h-40 overflow-y-auto border rounded-sm p-2 bg-gray-50">- <div class="text-xs font-medium text-gray-600 mb-2">- {{ $t("project.batch.projects-to-delete") }}:- </div>- <div class="flex flex-col gap-y-1">- <div- v-for="project in projectList"- :key="project.name"- class="text-sm flex items-center gap-x-2"- >- <CheckIcon class="w-3 h-3 text-red-600" />- <span>{{ project.title }}</span>- <span class="text-gray-500"- >({{ extractProjectResourceName(project.name) }})</span- >- </div>- </div>- </div>-- <!-- Warning about permanent deletion -->- <NAlert type="error" size="small">- <template #header>- {{ $t("common.cannot-undo-this-action") }}- </template>- <div class="text-sm">- {{ $t("project.batch.delete.warning") }}- </div>- </NAlert>- </div>- </BBAlert>-</template>--<script setup lang="tsx">-import { ArchiveIcon, CheckIcon, Trash2Icon } from "lucide-vue-next";-import { NAlert, NButton } from "naive-ui";-import type { VNode } from "vue";-import { computed, h, reactive } from "vue";-import { useI18n } from "vue-i18n";-import { BBAlert } from "@/bbkit";-import { pushNotification, useProjectV1Store } from "@/store";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { extractProjectResourceName, hasWorkspacePermissionV2 } from "@/utils";--interface Action {- icon?: VNode;- render?: () => VNode;- text: string;- disabled?: boolean;- click?: () => void;-}--interface LocalState {- loading: boolean;- showArchiveConfirm: boolean;- showDeleteConfirm: boolean;-}--const props = defineProps<{- projectList: Project[];-}>();--const emit = defineEmits<{- (event: "update"): void;-}>();--const { t } = useI18n();-const projectStore = useProjectV1Store();-const state = reactive<LocalState>({- loading: false,- showArchiveConfirm: false,- showDeleteConfirm: false,-});--// For now, we'll assume no projects have resources - this would need to be enhanced-// to actually check for databases and open issues-const projectsWithResources = computed((): Project[] => {- // TODO: Implement actual resource checking- return [];-});--const actions = computed((): Action[] => {- const list: Action[] = [];-- if (hasWorkspacePermissionV2("bb.projects.delete")) {- list.push({- icon: h(ArchiveIcon),- text: t("common.archive"),- disabled: props.projectList.length === 0,- click: () => (state.showArchiveConfirm = true),- });- list.push({- icon: h(Trash2Icon),- text: t("common.delete"),- disabled: props.projectList.length === 0,- click: () => (state.showDeleteConfirm = true),- });- }-- return list;-});--const handleBatchArchive = async () => {- try {- state.loading = true;-- // Use the batch delete API- await projectStore.batchDeleteProjects(- props.projectList.map((p) => p.name)- );-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("project.batch.archive.success", {- count: props.projectList.length,- }),- });-- state.showArchiveConfirm = false;- emit("update");- } catch (error: unknown) {- const err = error as { message?: string };- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("project.batch.archive.error"),- description: err.message,- });- } finally {- state.loading = false;- }-};--const handleBatchDelete = async () => {- try {- state.loading = true;-- // Use the batch purge API- await projectStore.batchPurgeProjects(props.projectList.map((p) => p.name));-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("project.batch.delete.success", {- count: props.projectList.length,- }),- });-- state.showDeleteConfirm = false;- emit("update");- } catch (error: unknown) {- const err = error as { message?: string };- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("project.batch.delete.error"),- description: err.message,- });- } finally {- state.loading = false;- }-};-</script>diff --git a/frontend/src/components/v2/Model/Project/index.ts b/frontend/src/components/v2/Model/Project/index.tsdeleted file mode 100644index 657c3db5ac..0000000000--- a/frontend/src/components/v2/Model/Project/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as ProjectOperations } from "./ProjectOperations.vue";diff --git a/frontend/src/components/v2/Model/index.ts b/frontend/src/components/v2/Model/index.tsindex 6d088822ed..53ff723f6c 100644--- a/frontend/src/components/v2/Model/index.ts+++ b/frontend/src/components/v2/Model/index.ts@@ -12,7 +12,6 @@ import RichDatabaseName from "./RichDatabaseName.vue";export * from "./Instance";export * from "./Plan";export * from "./DatabaseV1Table";-export * from "./Project";export {DatabaseV1Name,RichDatabaseName,diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 4c4207f385..4881cf919d 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1985,12 +1985,6 @@"warning": "This action cannot be undone. All project data including issues, configurations, and history will be permanently removed.","success": "Successfully deleted {count} project | Successfully deleted {count} projects","error": "Failed to delete projects"- },- "projects-to-archive": "Projects to archive",- "projects-to-delete": "Projects to delete",- "resource-warning": {- "title": "Projects with Resources",- "description": "The following projects contain databases or open issues:"}}},diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex e863c56d4d..ce543b72d6 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1985,12 +1985,6 @@"warning": "Esta acción no se puede deshacer. Todos los datos del proyecto, incluidos problemas, configuraciones e historial, se eliminarán permanentemente.","success": "Proyecto {count} eliminado correctamente | Proyectos {count} eliminados correctamente","error": "No se pudieron eliminar los proyectos"- },- "projects-to-archive": "Proyectos para archivar",- "projects-to-delete": "Proyectos para eliminar",- "resource-warning": {- "title": "Proyectos con recursos",- "description": "Los siguientes proyectos contienen bases de datos o problemas abiertos:"}}},diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex e7ba68b9d6..92fdd9bd8a 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1985,12 +1985,6 @@"warning": "この操作は元に戻せません。イシュー、設定、履歴を含むすべてのプロジェクトデータが完全に削除されます。","success": "{count} 件のプロジェクトを正常に削除しました | {count} 件のプロジェクトを正常に削除しました","error": "プロジェクトを削除できませんでした"- },- "projects-to-archive": "アーカイブするプロジェクト",- "projects-to-delete": "削除するプロジェクト",- "resource-warning": {- "title": "リソースのあるプロジェクト",- "description": "次のプロジェクトには、データベースまたは未解決のイシューが含まれています。"}}},diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 40eb445cf3..07adf5911a 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1985,12 +1985,6 @@"warning": "Hành động này không thể hoàn tác. Tất cả dữ liệu dự án bao gồm vấn đề, cấu hình và lịch sử sẽ bị xóa vĩnh viễn.","success": "Đã xóa thành công {count} dự án | Đã xóa thành công {count} dự án","error": "Không xóa được dự án"- },- "projects-to-archive": "Dự án để lưu trữ",- "projects-to-delete": "Dự án để xóa",- "resource-warning": {- "title": "Dự án có nguồn lực",- "description": "Các dự án sau đây chứa cơ sở dữ liệu hoặc các vấn đề chưa giải quyết:"}}},diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 566f6bde58..e5a247e382 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1985,12 +1985,6 @@"warning": "此操作无法撤消。包括工单、配置和历史记录在内的所有项目数据将被永久删除。","success": "成功删除 {count} 个项目 | 成功删除 {count} 个项目","error": "无法删除项目"- },- "projects-to-archive": "要归档的项目",- "projects-to-delete": "要删除的项目",- "resource-warning": {- "title": "项目与资源",- "description": "以下项目包含数据库或未解决的工单:"}}},diff --git a/frontend/src/react/components/AdvancedSearch.tsx b/frontend/src/react/components/AdvancedSearch.tsxnew file mode 100644index 0000000000..0a3bceb7e7--- /dev/null+++ b/frontend/src/react/components/AdvancedSearch.tsx@@ -0,0 +1,552 @@+import { Filter, X } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { cn } from "@/react/lib/utils";++// ============================================================+// Types+// ============================================================++export interface SearchScope {+ id: string;+ value: string;+ readonly?: boolean;+}++export interface SearchParams {+ query: string;+ scopes: SearchScope[];+}++export interface ValueOption {+ value: string;+ keywords: string[];+ render?: () => React.ReactNode;+ custom?: boolean;+}++export interface ScopeOption {+ id: string;+ title: string;+ description?: string;+ options?: ValueOption[];+ allowMultiple?: boolean;+}++export function emptySearchParams(): SearchParams {+ return { query: "", scopes: [] };+}++export function getValueFromScopes(params: SearchParams, id: string): string {+ return params.scopes.find((s) => s.id === id)?.value ?? "";+}++// ============================================================+// AdvancedSearch component+// ============================================================++interface AdvancedSearchProps {+ params: SearchParams;+ scopeOptions?: ScopeOption[];+ placeholder?: string;+ onParamsChange: (params: SearchParams) => void;+}++export function AdvancedSearch({+ params,+ scopeOptions = [],+ placeholder,+ onParamsChange,+}: AdvancedSearchProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);++ const [inputText, setInputText] = useState(params.query);+ const [menuView, setMenuView] = useState<"scope" | "value" | undefined>();+ const [currentScope, setCurrentScope] = useState<string | undefined>();+ const [menuIndex, setMenuIndex] = useState(0);+ const [focusedTagIndex, setFocusedTagIndex] = useState<number | undefined>();++ // Sync external query changes+ useEffect(() => {+ if (params.query !== inputText) {+ setInputText(params.query);+ }+ }, [params.query]);++ // Click outside to close+ useEffect(() => {+ const handler = (e: MouseEvent) => {+ if (+ containerRef.current &&+ !containerRef.current.contains(e.target as Node)+ ) {+ setMenuView(undefined);+ setFocusedTagIndex(undefined);+ }+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, []);++ const editableScopes = useMemo(+ () => params.scopes.filter((s) => !s.readonly),+ [params.scopes]+ );++ const clearable = useMemo(+ () => params.query.trim().length > 0 || editableScopes.length > 0,+ [params.query, editableScopes]+ );++ // Current scope option definition+ const currentScopeOption = useMemo(+ () => scopeOptions.find((opt) => opt.id === currentScope),+ [scopeOptions, currentScope]+ );++ // Available scopes (hide already-selected unless allowMultiple)+ const availableScopeOptions = useMemo(() => {+ const existing = new Set(params.scopes.map((s) => s.id));+ return scopeOptions.filter(+ (opt) => !existing.has(opt.id) || opt.allowMultiple+ );+ }, [scopeOptions, params.scopes]);++ // Value extracted from input after "scope:" prefix+ const currentValueForScope = useMemo(() => {+ if (!currentScope) return "";+ // If user typed a prefix like "state:", strip it; otherwise use full input as filter+ const prefix = `${currentScope}:`;+ if (inputText.startsWith(prefix)) {+ return inputText.trim().toLowerCase().substring(prefix.length);+ }+ return inputText.trim().toLowerCase();+ }, [currentScope, inputText]);++ // Visible scope options (filtered by typing)+ const visibleScopeOptions = useMemo(() => {+ if (currentScopeOption) return [currentScopeOption];+ const keyword = inputText.trim().replace(/:.*$/, "").toLowerCase();+ if (!keyword) return availableScopeOptions;+ return availableScopeOptions.filter(+ (opt) =>+ opt.id.toLowerCase().includes(keyword) ||+ opt.title.toLowerCase().includes(keyword)+ );+ }, [currentScopeOption, inputText, availableScopeOptions]);++ // Visible value options (filtered, de-duped)+ const visibleValueOptions = useMemo(() => {+ if (!currentScope || !currentScopeOption) return [];+ const selectedValues = new Set(+ params.scopes.filter((s) => s.id === currentScope).map((s) => s.value)+ );+ let options = (currentScopeOption.options ?? []).filter(+ (opt) => !selectedValues.has(opt.value)+ );+ const keyword = currentValueForScope.trim().toLowerCase();+ if (keyword) {+ options = options.filter(+ (opt) =>+ opt.value.toLowerCase().includes(keyword) ||+ opt.keywords.some((k) => k.toLowerCase().includes(keyword))+ );+ }+ return options;+ }, [currentScope, currentScopeOption, params.scopes, currentValueForScope]);++ const showMenu = useMemo(() => {+ if (menuView === "scope") return visibleScopeOptions.length > 0;+ if (menuView === "value") return true;+ return false;+ }, [menuView, visibleScopeOptions]);++ // ---- Actions ----++ const selectScope = useCallback((id: string | undefined) => {+ setCurrentScope(id);+ if (id) {+ setMenuView("value");+ setMenuIndex(0);+ // Clear the input so the value menu is unobstructed+ setInputText("");+ } else {+ setMenuView("scope");+ }+ }, []);++ const selectValue = useCallback(+ (value: string) => {+ if (!currentScope || !currentScopeOption) {+ setMenuView(undefined);+ return;+ }+ const allowMultiple = currentScopeOption.allowMultiple;+ const updated = { ...params, scopes: [...params.scopes] };+ if (allowMultiple) {+ updated.scopes.push({ id: currentScope, value });+ } else {+ const idx = updated.scopes.findIndex((s) => s.id === currentScope);+ if (idx >= 0) {+ updated.scopes[idx] = { id: currentScope, value };+ } else {+ updated.scopes.push({ id: currentScope, value });+ }+ }+ updated.query = "";+ setInputText("");+ setCurrentScope(undefined);+ setMenuView(undefined);+ setFocusedTagIndex(undefined);+ onParamsChange(updated);+ },+ [currentScope, currentScopeOption, params, onParamsChange]+ );++ const removeScope = useCallback(+ (index: number) => {+ const removed = params.scopes[index];+ // If we're editing the scope being removed, reset menu state+ if (removed && currentScope === removed.id) {+ setCurrentScope(undefined);+ setMenuView(undefined);+ }+ onParamsChange({+ ...params,+ scopes: params.scopes.filter((_, i) => i !== index),+ });+ },+ [params, onParamsChange, currentScope]+ );++ const handleClear = useCallback(() => {+ const readonlyScopes = params.scopes.filter((s) => s.readonly);+ onParamsChange({ query: "", scopes: readonlyScopes });+ setInputText("");+ setMenuView(undefined);+ setCurrentScope(undefined);+ setFocusedTagIndex(undefined);+ }, [params, onParamsChange]);++ // Debounced query emit+ const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);+ const emitQuery = useCallback(+ (text: string) => {+ clearTimeout(debounceRef.current);+ debounceRef.current = setTimeout(() => {+ // Only emit if not editing a scoped value+ if (currentScope && text.startsWith(`${currentScope}:`)) return;+ if (text !== params.query) {+ onParamsChange({ ...params, query: text });+ }+ }, 300);+ },+ [currentScope, params, onParamsChange]+ );++ const handleInputChange = useCallback(+ (text: string) => {+ setInputText(text);++ if (menuView === "value") {+ // In value mode, input text is used to filter values — don't change mode+ return;+ }++ // Check if text matches a scope prefix+ const matched = availableScopeOptions.find((opt) =>+ text.startsWith(`${opt.id}:`)+ );+ if (matched) {+ selectScope(matched.id);+ return;+ }+ if (!menuView) {+ setMenuView("scope");+ }++ emitQuery(text);+ },+ [menuView, availableScopeOptions, selectScope, emitQuery]+ );++ const handleInputClick = useCallback(() => {+ if (menuView === "value") {+ // Already showing value options, keep it+ return;+ }+ // Check scope prefix match+ const matched = availableScopeOptions.find((opt) =>+ inputText.startsWith(`${opt.id}:`)+ );+ if (matched) {+ selectScope(matched.id);+ return;+ }+ if (!menuView) {+ setMenuView("scope");+ }+ }, [availableScopeOptions, inputText, menuView, selectScope]);++ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ if (e.nativeEvent.isComposing) return;++ if (e.key === "Backspace" && inputText === "") {+ e.stopPropagation();+ e.preventDefault();+ if (focusedTagIndex !== undefined) {+ removeScope(focusedTagIndex);+ setFocusedTagIndex(undefined);+ } else {+ const lastEditable = editableScopes.length - 1;+ if (lastEditable >= 0) {+ // Map back to original index+ const scope = editableScopes[lastEditable];+ const origIdx = params.scopes.indexOf(scope);+ setFocusedTagIndex(origIdx);+ }+ }+ return;+ }++ setFocusedTagIndex(undefined);++ if (e.key === "ArrowUp") {+ e.preventDefault();+ setMenuIndex((prev) => Math.max(0, prev - 1));+ return;+ }+ if (e.key === "ArrowDown") {+ e.preventDefault();+ const maxIdx =+ menuView === "scope"+ ? visibleScopeOptions.length - 1+ : visibleValueOptions.length - 1;+ setMenuIndex((prev) => Math.min(maxIdx, prev + 1));+ return;+ }++ if (e.key === "Escape") {+ setMenuView(undefined);+ setCurrentScope(undefined);+ // Emit current text as query+ if (!currentScope && inputText !== params.query) {+ onParamsChange({ ...params, query: inputText });+ }+ return;+ }++ if (e.key === "Enter") {+ e.preventDefault();+ if (menuView === "scope") {+ const opt = visibleScopeOptions[menuIndex];+ if (opt) selectScope(opt.id);+ } else if (menuView === "value") {+ if (+ visibleValueOptions.length > 0 &&+ visibleValueOptions[menuIndex]+ ) {+ selectValue(visibleValueOptions[menuIndex].value);+ } else if (currentScope && inputText.trim()) {+ selectValue(inputText.trim());+ }+ }+ }+ },+ [+ inputText,+ focusedTagIndex,+ editableScopes,+ params,+ menuView,+ visibleScopeOptions,+ visibleValueOptions,+ menuIndex,+ currentScope,+ removeScope,+ selectScope,+ selectValue,+ onParamsChange,+ ]+ );++ // Reset menuIndex when options change+ useEffect(() => {+ setMenuIndex(0);+ }, [menuView]);++ // Render scope tags+ const visibleTags = useMemo(+ () =>+ params.scopes+ .map((scope, originalIndex) => ({ scope, originalIndex }))+ .filter(({ scope }) => !scope.readonly),+ [params.scopes]+ );++ const renderTagValue = useCallback(+ (scope: SearchScope) => {+ const opt = scopeOptions+ .find((o) => o.id === scope.id)+ ?.options?.find((o) => o.value === scope.value);+ if (opt?.render) return opt.render();+ return <span>{scope.value}</span>;+ },+ [scopeOptions]+ );++ return (+ <div ref={containerRef} className="w-full min-w-0 relative">+ {/* Input container */}+ <div+ className="flex items-center border border-gray-300 rounded-md focus-within:border-gray-400 bg-white transition-colors"+ onClick={() => inputRef.current?.focus()}+ >+ {/* Prefix: filter icon + tags */}+ <div className="flex items-center gap-x-2 pl-2 shrink-0">+ <Filter className="w-4 h-4 text-control-placeholder shrink-0" />+ </div>++ {/* Scope tags */}+ <div className="flex items-center gap-1 overflow-x-auto pl-1 shrink-0 hide-scrollbar">+ {visibleTags.map(({ scope, originalIndex }) => (+ <span+ key={`${originalIndex}-${scope.id}`}+ className={cn(+ "inline-flex items-center gap-1 rounded bg-gray-100 px-1.5 py-0.5 text-xs whitespace-nowrap shrink-0",+ focusedTagIndex === originalIndex && "ring-1 ring-accent"+ )}+ onClick={(e) => {+ e.stopPropagation();+ // Re-enter editing for this scope+ if (scopeOptions.some((o) => o.id === scope.id)) {+ selectScope(scope.id);+ }+ }}+ >+ <span className="text-control">{scope.id}:</span>+ {renderTagValue(scope)}+ <button+ className="ml-0.5 hover:text-error"+ onClick={(e) => {+ e.stopPropagation();+ removeScope(originalIndex);+ }}+ >+ <X className="h-3 w-3" />+ </button>+ </span>+ ))}+ </div>++ {/* Input */}+ <input+ ref={inputRef}+ className="flex-1 min-w-[120px] h-9 bg-transparent px-2 text-sm text-main placeholder:text-control-placeholder focus:outline-none"+ value={inputText}+ placeholder={visibleTags.length > 0 ? "" : placeholder}+ onClick={handleInputClick}+ onChange={(e) => handleInputChange(e.target.value)}+ onKeyDown={handleKeyDown}+ />++ {/* Clear button */}+ {clearable && (+ <button+ className="p-1.5 mr-1 hover:bg-control-bg rounded-full shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleClear();+ }}+ >+ <X className="h-3 w-3 text-control-placeholder" />+ </button>+ )}+ </div>++ {/* Dropdown menu */}+ {showMenu && (+ <div+ className="absolute top-[38px] w-full bg-gray-100 shadow-xl origin-top-left rounded-[3px] overflow-hidden z-50"+ onMouseDown={(e) => e.preventDefault()}+ >+ {/* Scope menu */}+ {menuView === "scope" && visibleScopeOptions.length > 0 && (+ <div className="max-h-[480px] overflow-auto">+ {visibleScopeOptions.map((option, index) => (+ <div+ key={option.id}+ className={cn(+ "flex gap-x-2 px-3 py-2 cursor-pointer text-sm items-center",+ index > 0 && "border-t border-block-border",+ index === menuIndex && "bg-gray-200/75"+ )}+ onMouseEnter={() => setMenuIndex(index)}+ onClick={() => selectScope(option.id)}+ >+ <span className="text-accent">{option.id}</span>+ {option.description && (+ <span className="text-control-light truncate">+ {option.description}+ </span>+ )}+ </div>+ ))}+ </div>+ )}++ {/* Value menu */}+ {menuView === "value" && currentScopeOption && (+ <div className="flex flex-col overflow-hidden">+ <div className="px-3 py-2">+ <div className="text-sm text-control font-semibold">+ {currentScopeOption.title}+ </div>+ {currentScopeOption.description && (+ <div className="text-xs text-control-light">+ {currentScopeOption.description}+ </div>+ )}+ </div>+ {visibleValueOptions.length > 0 ? (+ <div className="max-h-[240px] overflow-auto">+ {visibleValueOptions.map((option, index) => (+ <div+ key={option.value}+ className={cn(+ "h-[38px] flex gap-x-2 px-3 items-center cursor-pointer border-t border-block-border overflow-hidden",+ index === menuIndex && "bg-gray-200/75"+ )}+ onMouseEnter={() => setMenuIndex(index)}+ onClick={() => selectValue(option.value)}+ >+ {option.render && (+ <span className="text-control text-sm">+ {option.render()}+ </span>+ )}+ {!option.custom && (+ <span className="text-control-light text-sm">+ {option.value}+ </span>+ )}+ </div>+ ))}+ </div>+ ) : !(currentScopeOption.options ?? []).length ? (+ <div className="px-3 py-2 text-xs text-control-light border-t border-block-border">+ Type a value and press Enter+ </div>+ ) : (+ <div className="py-4 text-center text-sm text-control-placeholder">+ —+ </div>+ )}+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/react/pages/settings/ProjectsPage.tsx b/frontend/src/react/pages/settings/ProjectsPage.tsxnew file mode 100644index 0000000000..0338e8adaa--- /dev/null+++ b/frontend/src/react/pages/settings/ProjectsPage.tsx@@ -0,0 +1,1278 @@+import { Code, ConnectError } from "@connectrpc/connect";+import { sortBy, uniq } from "lodash-es";+import {+ Archive,+ Check,+ ChevronDown,+ EllipsisVertical,+ Plus,+ Trash2,+ X,+} from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ AdvancedSearch,+ getValueFromScopes,+ type ScopeOption,+ type SearchParams,+} from "@/react/components/AdvancedSearch";+import {+ ResourceIdField,+ type ResourceIdFieldRef,+} 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 { cn } from "@/react/lib/utils";+import { router } from "@/router";+import { PROJECT_V1_ROUTE_DETAIL } from "@/router/dashboard/projectV1";+import {+ pushNotification,+ useAuthStore,+ useCurrentUserV1,+ useProjectV1Store,+ useUIStateStore,+} from "@/store";+import { getProjectName, projectNamePrefix } from "@/store/modules/v1/common";+import { unknownProject } from "@/types";+import { State } from "@/types/proto-es/v1/common_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import {+ extractProjectResourceName,+ getDefaultPagination,+ hasProjectPermissionV2,+ hasWorkspacePermissionV2,+} from "@/utils";++// ============================================================+// i18n helpers for vue-i18n compat+// ============================================================++// vue-i18n uses "@:key" for linked messages and "singular | plural" for pluralization.+// react-i18next doesn't support either, so we resolve them manually.++function resolveLinkedMessages(+ value: string,+ t: (key: string) => string+): string {+ return value.replace(/@:(?:\{'([^']+)'\}|(\S+))/g, (_match, quoted, plain) =>+ t(quoted ?? plain)+ );+}++function tVue(+ t: (key: string, options?: Record<string, unknown>) => string,+ key: string,+ options?: Record<string, unknown>+): string {+ const raw = t(key, { ...options, interpolation: { escapeValue: false } });+ // Handle vue-i18n pipe pluralization: "singular | plural"+ if (raw.includes(" | ")) {+ const parts = raw.split(" | ");+ const count = typeof options?.count === "number" ? options.count : 1;+ const chosen = count === 1 ? parts[0] : parts[parts.length - 1];+ // Re-interpolate {count} etc.+ const interpolated = chosen.replace(/\{(\w+)\}/g, (_m, k) =>+ String(options?.[k] ?? `{${k}}`)+ );+ return resolveLinkedMessages(interpolated, t);+ }+ return resolveLinkedMessages(raw, t);+}++// ============================================================+// Escape key stack for overlays+// ============================================================++// Track the topmost overlay's escape handler. Only active (enabled) overlays+// participate. The ref ensures the latest callback is always invoked.+const escapeStack: React.RefObject<(() => void) | null>[] = [];++function useEscapeKey(onEscape: () => void, enabled = true) {+ const callbackRef = useRef(onEscape);+ callbackRef.current = onEscape;++ useEffect(() => {+ if (!enabled) return;+ escapeStack.push(callbackRef);+ const handler = (e: KeyboardEvent) => {+ if (+ e.key === "Escape" &&+ escapeStack[escapeStack.length - 1] === callbackRef+ ) {+ callbackRef.current?.();+ }+ };+ document.addEventListener("keydown", handler);+ return () => {+ document.removeEventListener("keydown", handler);+ const idx = escapeStack.indexOf(callbackRef);+ if (idx >= 0) escapeStack.splice(idx, 1);+ };+ }, [enabled]);+}++// ============================================================+// Pagination helpers+// ============================================================++const PAGE_SIZE_OPTIONS = [50, 100, 200, 500];++function getPageSizeOptions(): number[] {+ const defaultSize = getDefaultPagination();+ return sortBy(uniq([defaultSize, ...PAGE_SIZE_OPTIONS]));+}++function useSessionPageSize(+ sessionKey: string+): [number, (size: number) => void] {+ const currentUser = useCurrentUserV1();+ const email = useVueState(() => currentUser.value.email);+ const storageKey = `bb.paged-table.${sessionKey}.${email}`;++ const [pageSize, setPageSize] = useState<number>(() => {+ try {+ const stored = localStorage.getItem(storageKey);+ if (stored) {+ const parsed = JSON.parse(stored);+ const size = parsed?.pageSize;+ const options = getPageSizeOptions();+ if (typeof size === "number" && options.includes(size)) {+ return Math.max(options[0], size);+ }+ }+ } catch {+ // ignore+ }+ return getPageSizeOptions()[0];+ });++ const updatePageSize = useCallback(+ (size: number) => {+ setPageSize(size);+ try {+ localStorage.setItem(storageKey, JSON.stringify({ pageSize: size }));+ } catch {+ // ignore+ }+ },+ [storageKey]+ );++ return [pageSize, updatePageSize];+}++// ============================================================+// ConfirmDialog+// ============================================================++function ConfirmDialog({+ open,+ variant,+ title,+ description,+ okText,+ onOk,+ onCancel,+ children,+}: {+ open: boolean;+ variant: "warning" | "error";+ title: string;+ description: string;+ okText: string;+ onOk: () => void;+ onCancel: () => void;+ children?: React.ReactNode;+}) {+ const { t } = useTranslation();+ const onClose = useCallback(() => onCancel(), [onCancel]);+ useEscapeKey(onClose, open);++ if (!open) return null;++ const borderColor = variant === "error" ? "border-error" : "border-warning";+ const okBg =+ variant === "error"+ ? "bg-error hover:bg-error-hover text-white"+ : "bg-warning hover:bg-warning-hover text-white";++ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center">+ <div className="fixed inset-0 bg-black/50" onClick={onCancel} />+ <div+ className={cn(+ "relative bg-white rounded-lg shadow-lg max-w-lg w-full mx-4 border-t-4",+ borderColor+ )}+ >+ <div className="p-6">+ <h3 className="text-lg font-semibold mb-2">{title}</h3>+ <p className="text-sm text-control-light mb-4">{description}</p>+ {children}+ </div>+ <div className="flex justify-end gap-x-2 px-6 pb-6">+ <Button variant="outline" onClick={onCancel}>+ {t("common.cancel")}+ </Button>+ <button+ className={cn(+ "inline-flex items-center justify-center rounded-md px-4 py-2 text-sm font-medium",+ okBg+ )}+ onClick={onOk}+ >+ {okText}+ </button>+ </div>+ </div>+ </div>+ );+}++// ============================================================+// CreateProjectDrawer+// ============================================================++function CreateProjectDrawer({+ open,+ onClose,+ onCreated,+}: {+ open: boolean;+ onClose: () => void;+ onCreated: (project: Project) => void;+}) {+ const { t } = useTranslation();+ const projectStore = useProjectV1Store();+ const [title, setTitle] = useState("");+ const [resourceId, setResourceId] = useState("");+ const [isCreating, setIsCreating] = useState(false);+ const [isResourceIdValid, setIsResourceIdValid] = useState(false);+ const resourceIdFieldRef = useRef<ResourceIdFieldRef>(null);++ const closeDrawer = useCallback(() => {+ onClose();+ setTitle("");+ setResourceId("");+ setIsCreating(false);+ }, [onClose]);++ useEscapeKey(closeDrawer, open);++ const allowCreate = useMemo(() => {+ if (!title.trim()) return false;+ if (!isResourceIdValid) return false;+ if (!hasWorkspacePermissionV2("bb.projects.create")) return false;+ return true;+ }, [title, isResourceIdValid]);++ const handleCreate = useCallback(async () => {+ if (!allowCreate || isCreating) return;+ try {+ setIsCreating(true);+ const project = { ...unknownProject(), title };+ const created = await projectStore.createProject(project, resourceId);++ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.create-modal.success-prompt", {+ name: created.title,+ }),+ });++ onCreated(created);+ closeDrawer();+ } catch (error) {+ if (error instanceof ConnectError && error.code === Code.AlreadyExists) {+ resourceIdFieldRef.current?.addValidationError(+ (error as ConnectError).message+ );+ } else {+ throw error;+ }+ } finally {+ setIsCreating(false);+ }+ }, [+ allowCreate,+ isCreating,+ title,+ resourceId,+ projectStore,+ t,+ onCreated,+ closeDrawer,+ ]);++ const validate = useCallback(+ async (id: string) => {+ try {+ await projectStore.getOrFetchProjectByName(+ `${projectNamePrefix}${id}`,+ true+ );+ return [+ {+ type: "error" as const,+ message: t("resource-id.validation.duplicated", {+ resource: "project",+ }),+ },+ ];+ } catch {+ return [];+ }+ },+ [projectStore, t]+ );++ if (!open) return null;++ return (+ <div className="fixed inset-0 z-50 flex">+ <div className="fixed inset-0 bg-black/50" onClick={closeDrawer} />+ <div className="ml-auto relative bg-white w-[40rem] max-w-[100vw] h-full shadow-lg flex flex-col">+ <div className="flex items-center justify-between px-6 py-4 border-b border-control-border">+ <h2 className="text-lg font-semibold">+ {tVue(t, "quick-action.create-project")}+ </h2>+ <button+ className="p-1 hover:bg-control-bg rounded"+ onClick={closeDrawer}+ >+ <X className="h-5 w-5" />+ </button>+ </div>++ <div className="flex-1 overflow-y-auto p-6">+ <div className="flex flex-col gap-y-6">+ <div>+ <label className="text-base leading-6 font-medium text-control">+ {tVue(t, "project.create-modal.project-name")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <Input+ className="mt-2 mb-1"+ value={title}+ maxLength={200}+ placeholder={tVue(t, "project.create-modal.project-name")}+ onChange={(e) => setTitle(e.target.value)}+ />+ <ResourceIdField+ ref={resourceIdFieldRef}+ value={resourceId}+ resourceType="project"+ resourceName={title}+ resourceTitle={title}+ validate={validate}+ onChange={setResourceId}+ onValidationChange={setIsResourceIdValid}+ />+ </div>+ </div>++ {isCreating && (+ <div className="absolute inset-0 bg-white/50 flex justify-center items-center">+ <div className="animate-spin h-6 w-6 border-2 border-accent border-t-transparent rounded-full" />+ </div>+ )}+ </div>++ <div className="flex justify-end items-center gap-x-3 px-6 py-4 border-t border-control-border">+ <Button variant="ghost" onClick={closeDrawer}>+ {t("common.cancel")}+ </Button>+ <Button disabled={!allowCreate} onClick={handleCreate}>+ {t("common.create")}+ </Button>+ </div>+ </div>+ </div>+ );+}++// ============================================================+// BatchOperationsBar+// ============================================================++function BatchOperationsBar({+ selectedProjects,+ onUpdate,+}: {+ selectedProjects: Project[];+ onUpdate: () => void;+}) {+ const { t } = useTranslation();+ const projectStore = useProjectV1Store();+ const [showArchiveConfirm, setShowArchiveConfirm] = useState(false);+ const [showRestoreConfirm, setShowRestoreConfirm] = useState(false);+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);++ // Determine which actions to show based on selected projects' actual state+ const hasActiveProjects = selectedProjects.some(+ (p) => p.state === State.ACTIVE+ );+ const hasArchivedProjects = selectedProjects.some(+ (p) => p.state === State.DELETED+ );++ const handleBatchArchive = useCallback(async () => {+ try {+ const activeProjects = selectedProjects.filter(+ (p) => p.state === State.ACTIVE+ );+ await projectStore.batchDeleteProjects(activeProjects.map((p) => p.name));+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: tVue(t, "project.batch.archive.success", {+ count: activeProjects.length,+ }),+ });+ setShowArchiveConfirm(false);+ onUpdate();+ } catch (error: unknown) {+ const err = error as { message?: string };+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("project.batch.archive.error"),+ description: err.message,+ });+ }+ }, [selectedProjects, projectStore, t, onUpdate]);++ const handleBatchRestore = useCallback(async () => {+ try {+ const archivedProjects = selectedProjects.filter(+ (p) => p.state === State.DELETED+ );+ await Promise.all(+ archivedProjects.map((project) => projectStore.restoreProject(project))+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.restored"),+ });+ setShowRestoreConfirm(false);+ onUpdate();+ } catch (error: unknown) {+ const err = error as { message?: string };+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.restore"),+ description: err.message,+ });+ }+ }, [selectedProjects, projectStore, t, onUpdate]);++ const handleBatchDelete = useCallback(async () => {+ try {+ await projectStore.batchPurgeProjects(+ selectedProjects.map((p) => p.name)+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: tVue(t, "project.batch.delete.success", {+ count: selectedProjects.length,+ }),+ });+ setShowDeleteConfirm(false);+ onUpdate();+ } catch (error: unknown) {+ const err = error as { message?: string };+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("project.batch.delete.error"),+ description: err.message,+ });+ }+ }, [selectedProjects, projectStore, t, onUpdate]);++ if (selectedProjects.length === 0) return null;++ return (+ <>+ <div className="text-sm flex flex-col lg:flex-row items-start lg:items-center bg-blue-100 py-3 px-4 text-main gap-y-2 gap-x-4 overflow-x-auto">+ <span className="whitespace-nowrap">+ {tVue(t, "project.batch.selected", {+ count: selectedProjects.length,+ })}+ </span>+ <div className="flex items-center gap-x-2">+ {hasActiveProjects && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setShowArchiveConfirm(true)}+ >+ <Archive className="h-4 w-4 mr-1" />+ {t("common.archive")}+ </Button>+ )}+ {hasArchivedProjects && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setShowRestoreConfirm(true)}+ >+ {t("common.restore")}+ </Button>+ )}+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setShowDeleteConfirm(true)}+ >+ <Trash2 className="h-4 w-4 mr-1" />+ {t("common.delete")}+ </Button>+ </div>+ </div>++ <ConfirmDialog+ open={showArchiveConfirm}+ variant="warning"+ title={tVue(t, "project.batch.archive.title", {+ count: selectedProjects.length,+ })}+ description={t("project.batch.archive.description")}+ okText={t("common.archive")}+ onOk={handleBatchArchive}+ onCancel={() => setShowArchiveConfirm(false)}+ >+ <ProjectListPreview+ projects={selectedProjects}+ iconColor="text-green-600"+ />+ </ConfirmDialog>++ <ConfirmDialog+ open={showRestoreConfirm}+ variant="warning"+ title={t("common.restore")}+ description={t("common.restore")}+ okText={t("common.restore")}+ onOk={handleBatchRestore}+ onCancel={() => setShowRestoreConfirm(false)}+ >+ <ProjectListPreview+ projects={selectedProjects}+ iconColor="text-green-600"+ />+ </ConfirmDialog>++ <ConfirmDialog+ open={showDeleteConfirm}+ variant="error"+ title={tVue(t, "project.batch.delete.title", {+ count: selectedProjects.length,+ })}+ description={t("project.batch.delete.description")}+ okText={t("common.delete")}+ onOk={handleBatchDelete}+ onCancel={() => setShowDeleteConfirm(false)}+ >+ <div className="flex flex-col gap-y-3">+ <ProjectListPreview+ projects={selectedProjects}+ iconColor="text-red-600"+ />+ <div className="rounded-md border border-error bg-error/5 p-3">+ <p className="text-sm font-medium text-error">+ {t("common.cannot-undo-this-action")}+ </p>+ <p className="text-sm text-error/80 mt-1">+ {t("project.batch.delete.warning")}+ </p>+ </div>+ </div>+ </ConfirmDialog>+ </>+ );+}++function ProjectListPreview({+ projects,+ iconColor,+}: {+ projects: Project[];+ iconColor: string;+}) {+ return (+ <div className="max-h-40 overflow-y-auto border rounded-sm p-2 bg-gray-50">+ <div className="flex flex-col gap-y-1">+ {projects.map((project) => (+ <div key={project.name} className="text-sm flex items-center gap-x-2">+ <Check className={cn("w-3 h-3", iconColor)} />+ <span>{project.title}</span>+ <span className="text-gray-500">+ ({extractProjectResourceName(project.name)})+ </span>+ </div>+ ))}+ </div>+ </div>+ );+}++// ============================================================+// ProjectActionDropdown+// ============================================================++function ProjectActionDropdown({+ project,+ onAction,+}: {+ project: Project;+ onAction: () => void;+}) {+ const { t } = useTranslation();+ const projectStore = useProjectV1Store();+ const [open, setOpen] = useState(false);+ const dropdownRef = useRef<HTMLDivElement>(null);++ const canDelete = hasProjectPermissionV2(project, "bb.projects.delete");+ const canUndelete = hasProjectPermissionV2(project, "bb.projects.undelete");++ useEffect(() => {+ if (!open) return;+ const handler = (e: MouseEvent) => {+ if (+ dropdownRef.current &&+ !dropdownRef.current.contains(e.target as Node)+ ) {+ setOpen(false);+ }+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, [open]);++ const handleArchive = useCallback(async () => {+ setOpen(false);+ await projectStore.archiveProject(project);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.archived"),+ });+ onAction();+ }, [project, projectStore, t, onAction]);++ const handleRestore = useCallback(async () => {+ setOpen(false);+ await projectStore.restoreProject(project);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.restored"),+ });+ onAction();+ }, [project, projectStore, t, onAction]);++ if (!canDelete && !canUndelete) return null;++ const isActive = project.state === State.ACTIVE;++ return (+ <div ref={dropdownRef} className="relative">+ <button+ className="p-1 hover:bg-control-bg rounded"+ onClick={(e) => {+ e.stopPropagation();+ setOpen(!open);+ }}+ >+ <EllipsisVertical className="h-4 w-4" />+ </button>+ {open && (+ <div className="absolute right-0 top-full mt-1 bg-white border border-control-border rounded-md shadow-lg z-10 min-w-[120px]">+ {isActive && canDelete && (+ <button+ className="w-full text-left px-3 py-2 text-sm hover:bg-control-bg flex items-center gap-x-2"+ onClick={(e) => {+ e.stopPropagation();+ handleArchive();+ }}+ >+ <Archive className="h-4 w-4" />+ {t("common.archive")}+ </button>+ )}+ {!isActive && canUndelete && (+ <button+ className="w-full text-left px-3 py-2 text-sm hover:bg-control-bg flex items-center gap-x-2"+ onClick={(e) => {+ e.stopPropagation();+ handleRestore();+ }}+ >+ {t("common.restore")}+ </button>+ )}+ </div>+ )}+ </div>+ );+}++// ============================================================+// HighlightText+// ============================================================++function HighlightText({ text, keyword }: { text: string; keyword: string }) {+ if (!keyword) return <>{text}</>;++ const lowerText = text.toLowerCase();+ const lowerKeyword = keyword.toLowerCase();+ const index = lowerText.indexOf(lowerKeyword);++ if (index === -1) return <>{text}</>;++ return (+ <>+ {text.substring(0, index)}+ <span className="bg-yellow-100">+ {text.substring(index, index + keyword.length)}+ </span>+ {text.substring(index + keyword.length)}+ </>+ );+}++// ============================================================+// ProjectsPage (main)+// ============================================================++export function ProjectsPage() {+ const { t } = useTranslation();+ const projectStore = useProjectV1Store();+ const authStore = useAuthStore();++ // Search state — managed as SearchParams (query + scopes)+ const [searchParams, setSearchParams] = useState<SearchParams>(() => {+ const currentRoute = router.currentRoute.value;+ // Migrate old URL format+ const queryState = currentRoute.query.state as string;+ if (queryState === "archived" || queryState === "all") {+ const stateValue = queryState === "archived" ? "DELETED" : "ALL";+ return { query: "", scopes: [{ id: "state", value: stateValue }] };+ }+ const queryString = currentRoute.query.q as string;+ if (queryString) {+ const scopes: { id: string; value: string }[] = [];+ const queryParts: string[] = [];+ for (const token of queryString.split(/\s+/).filter(Boolean)) {+ const colonIdx = token.indexOf(":");+ if (colonIdx > 0) {+ const id = token.substring(0, colonIdx);+ const value = token.substring(colonIdx + 1);+ if (value && (id === "state" || id === "label")) {+ scopes.push({ id, value });+ continue;+ }+ }+ queryParts.push(token);+ }+ return { query: queryParts.join(" "), scopes };+ }+ return { query: "", scopes: [] };+ });++ // Scope options for the AdvancedSearch+ const canUndelete = hasWorkspacePermissionV2("bb.projects.undelete");+ const scopeOptions: ScopeOption[] = useMemo(() => {+ const stateOption: ScopeOption = {+ id: "state",+ title: t("common.state"),+ description: t("common.state"),+ options: [+ { value: "ACTIVE", keywords: ["active"] },+ ...(canUndelete+ ? [+ { value: "DELETED", keywords: ["archived", "deleted"] },+ { value: "ALL", keywords: ["all"] },+ ]+ : []),+ ],+ };+ const labelOption: ScopeOption = {+ id: "label",+ title: t("common.labels"),+ description: t("common.labels"),+ allowMultiple: true,+ };+ return [labelOption, stateOption];+ }, [t, canUndelete]);++ // Derived values from searchParams+ const searchText = searchParams.query;+ const stateFilter = useMemo(() => {+ const val = getValueFromScopes(searchParams, "state");+ if (val === "DELETED") return "DELETED" as const;+ if (val === "ALL") return "ALL" as const;+ return "ACTIVE" as const;+ }, [searchParams]);+ const selectedLabels = useMemo(+ () =>+ searchParams.scopes.filter((s) => s.id === "label").map((s) => s.value),+ [searchParams]+ );++ // Mark project visit on mount+ useEffect(() => {+ const uiStateStore = useUIStateStore();+ if (!uiStateStore.getIntroStateByKey("project.visit")) {+ uiStateStore.saveIntroStateByKey({+ key: "project.visit",+ newState: true,+ });+ }+ }, []);++ // Sync search state to URL+ useEffect(() => {+ const parts: string[] = [];+ for (const scope of searchParams.scopes) {+ parts.push(`${scope.id}:${scope.value}`);+ }+ if (searchParams.query) parts.push(searchParams.query);+ const queryString = parts.join(" ");+ const currentQuery = router.currentRoute.value.query.q as string;+ if (queryString !== (currentQuery ?? "")) {+ router.replace({ query: queryString ? { q: queryString } : {} });+ }+ }, [searchParams]);++ // Data fetching state+ const [projects, setProjects] = useState<Project[]>([]);+ const [loading, setLoading] = useState(true);+ const nextPageTokenRef = useRef("");+ const [hasMore, setHasMore] = useState(false);+ const [isFetchingMore, setIsFetchingMore] = useState(false);+ const [pageSize, setPageSize] = useSessionPageSize("bb.project-table");+ const abortRef = useRef<AbortController | null>(null);+ const fetchIdRef = useRef(0);++ // Sort state+ const [sortKey, setSortKey] = useState<string | null>(null);+ const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");++ const orderBy = useMemo(() => {+ if (!sortKey) return "";+ return `${sortKey} ${sortOrder}`;+ }, [sortKey, sortOrder]);++ const toggleSort = useCallback(+ (key: string) => {+ if (sortKey === key) {+ if (sortOrder === "asc") setSortOrder("desc");+ else {+ setSortKey(null);+ setSortOrder("asc");+ }+ } else {+ setSortKey(key);+ setSortOrder("asc");+ }+ },+ [sortKey, sortOrder]+ );++ const selectedState = useMemo(() => {+ if (stateFilter === "DELETED") return State.DELETED;+ if (stateFilter === "ALL") return undefined;+ return State.ACTIVE;+ }, [stateFilter]);++ const fetchProjects = useCallback(+ async (isRefresh: boolean) => {+ if (!authStore.isLoggedIn) return;++ abortRef.current?.abort();+ abortRef.current = new AbortController();+ const currentFetchId = ++fetchIdRef.current;++ if (isRefresh) {+ setLoading(true);+ } else {+ setIsFetchingMore(true);+ }++ try {+ const token = isRefresh ? "" : nextPageTokenRef.current;+ const result = await projectStore.fetchProjectList({+ pageToken: token,+ pageSize,+ filter: {+ query: searchText,+ excludeDefault: true,+ state: selectedState,+ labels: selectedLabels.length > 0 ? selectedLabels : undefined,+ },+ orderBy,+ cache: true,+ });++ if (currentFetchId !== fetchIdRef.current) return;++ if (isRefresh) {+ setProjects(result.projects);+ } else {+ setProjects((prev) => [...prev, ...result.projects]);+ }+ nextPageTokenRef.current = result.nextPageToken ?? "";+ setHasMore(Boolean(result.nextPageToken));+ } catch (e) {+ if (e instanceof Error && e.name === "AbortError") return;+ console.error(e);+ } finally {+ if (currentFetchId === fetchIdRef.current) {+ setLoading(false);+ setIsFetchingMore(false);+ }+ }+ },+ [+ authStore.isLoggedIn,+ pageSize,+ searchText,+ selectedState,+ selectedLabels,+ orderBy,+ projectStore,+ ]+ );++ // Fetch on mount + re-fetch on filter/sort/pageSize changes (debounced after first load)+ const prevDepsRef = useRef<string>("");+ const isFirstLoad = useRef(true);+ useEffect(() => {+ const depsKey = `${searchText}|${stateFilter}|${selectedLabels.join(",")}|${pageSize}|${orderBy}`;+ if (prevDepsRef.current === depsKey) return;+ prevDepsRef.current = depsKey;++ if (isFirstLoad.current) {+ isFirstLoad.current = false;+ fetchProjects(true);+ return () => abortRef.current?.abort();+ }+ const timer = setTimeout(() => fetchProjects(true), 300);+ return () => clearTimeout(timer);+ }, [+ searchText,+ stateFilter,+ selectedLabels,+ pageSize,+ orderBy,+ fetchProjects,+ ]);++ const loadMore = useCallback(() => {+ if (nextPageTokenRef.current && !isFetchingMore) {+ fetchProjects(false);+ }+ }, [isFetchingMore, fetchProjects]);++ // Selection state+ const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());++ const selectedProjectList = useMemo(() => {+ if (selectedNames.size === 0) return [];+ return Array.from(selectedNames)+ .map((name) => projectStore.getProjectByName(name))+ .filter((p): p is Project => p !== undefined);+ }, [selectedNames, projectStore]);++ const toggleSelection = useCallback((name: string) => {+ setSelectedNames((prev) => {+ const next = new Set(prev);+ if (next.has(name)) next.delete(name);+ else next.add(name);+ return next;+ });+ }, []);++ const toggleSelectAll = useCallback(() => {+ setSelectedNames((prev) => {+ const selectableProjects = projects.filter(+ (p) => extractProjectResourceName(p.name) !== "default"+ );+ if (prev.size === selectableProjects.length) {+ return new Set();+ }+ return new Set(selectableProjects.map((p) => p.name));+ });+ }, [projects]);++ const handleBatchOperation = useCallback(() => {+ setSelectedNames(new Set());+ fetchProjects(true);+ }, [fetchProjects]);++ // Create drawer+ const [showCreateDrawer, setShowCreateDrawer] = useState(false);+ const canCreate = hasWorkspacePermissionV2("bb.projects.create");+ const canDelete = hasWorkspacePermissionV2("bb.projects.delete");++ const handleCreated = useCallback((project: Project) => {+ router.push({ path: `/${project.name}` });+ }, []);++ const handleRowClick = useCallback(+ (project: Project, e: React.MouseEvent) => {+ const route = router.resolve({+ name: PROJECT_V1_ROUTE_DETAIL,+ params: { projectId: getProjectName(project.name) },+ });+ if (e.ctrlKey || e.metaKey) {+ window.open(route.fullPath, "_blank");+ } else {+ router.push(route);+ }+ },+ []+ );++ const handleProjectAction = useCallback(() => {+ fetchProjects(true);+ }, [fetchProjects]);++ const renderSortIndicator = (columnKey: string) => {+ if (sortKey !== columnKey) {+ return <ChevronDown className="h-3 w-3 text-gray-300" />;+ }+ return (+ <ChevronDown+ className={cn(+ "h-3 w-3 text-accent transition-transform",+ sortOrder === "asc" && "rotate-180"+ )}+ />+ );+ };++ const selectableProjects = useMemo(+ () =>+ projects.filter((p) => extractProjectResourceName(p.name) !== "default"),+ [projects]+ );++ const allSelected =+ selectableProjects.length > 0 &&+ selectedNames.size === selectableProjects.length;++ const pageSizeOptions = getPageSizeOptions();++ return (+ <div className="py-4 flex flex-col">+ {/* Header: Search + Create */}+ <div className="flex items-center justify-between px-4 pb-2 gap-x-2">+ <AdvancedSearch+ params={searchParams}+ scopeOptions={scopeOptions}+ placeholder={t("project.filter-projects")}+ onParamsChange={setSearchParams}+ />+ {canCreate && (+ <Button onClick={() => setShowCreateDrawer(true)}>+ <Plus className="h-4 w-4 mr-1" />+ {tVue(t, "quick-action.new-project")}+ </Button>+ )}+ </div>++ {/* Batch operations */}+ {canDelete && (+ <BatchOperationsBar+ selectedProjects={selectedProjectList}+ onUpdate={handleBatchOperation}+ />+ )}++ {/* Table */}+ <div className="flex flex-col gap-y-4">+ <table className="w-full text-sm">+ <thead>+ <tr className="bg-gray-50 border-b border-control-border">+ {canDelete && (+ <th className="w-12 px-4 py-2">+ <input+ type="checkbox"+ checked={allSelected}+ onChange={toggleSelectAll}+ className="rounded border-control-border"+ />+ </th>+ )}+ <th className="px-4 py-2 text-left font-medium min-w-[128px]">+ {t("common.id")}+ </th>+ <th+ className="px-4 py-2 text-left font-medium min-w-[200px] cursor-pointer select-none"+ onClick={() => toggleSort("title")}+ >+ <div className="flex items-center gap-x-1">+ {tVue(t, "project.table.name")}+ {renderSortIndicator("title")}+ </div>+ </th>+ <th className="px-4 py-2 text-left font-medium min-w-[240px] hidden md:table-cell">+ {t("common.labels")}+ </th>+ <th className="w-[50px]" />+ </tr>+ </thead>+ <tbody>+ {loading && projects.length === 0 ? (+ <tr>+ <td+ colSpan={canDelete ? 5 : 4}+ className="px-4 py-8 text-center text-control-placeholder"+ >+ <div className="flex items-center justify-center gap-x-2">+ <div className="animate-spin h-4 w-4 border-2 border-accent border-t-transparent rounded-full" />+ {t("common.loading")}+ </div>+ </td>+ </tr>+ ) : projects.length === 0 ? (+ <tr>+ <td+ colSpan={canDelete ? 5 : 4}+ className="px-4 py-8 text-center text-control-placeholder"+ >+ {t("common.no-data")}+ </td>+ </tr>+ ) : (+ projects.map((project, i) => {+ const resourceName = extractProjectResourceName(project.name);+ const isDefault = resourceName === "default";+ const isSelected = selectedNames.has(project.name);++ return (+ <tr+ key={project.name}+ className={cn(+ "border-b last:border-b-0 cursor-pointer hover:bg-gray-50",+ i % 2 === 1 && "bg-gray-50/50"+ )}+ onClick={(e) => handleRowClick(project, e)}+ >+ {canDelete && (+ <td className="w-12 px-4 py-2">+ <input+ type="checkbox"+ checked={isSelected}+ disabled={isDefault}+ onChange={() => toggleSelection(project.name)}+ onClick={(e) => e.stopPropagation()}+ className="rounded border-control-border disabled:opacity-50"+ />+ </td>+ )}+ <td className="px-4 py-2">+ <HighlightText text={resourceName} keyword={searchText} />+ </td>+ <td className="px-4 py-2">+ <HighlightText+ text={project.title}+ keyword={searchText}+ />+ </td>+ <td className="px-4 py-2 hidden md:table-cell">+ <LabelsDisplay labels={project.labels} />+ </td>+ <td className="px-4 py-2">+ <div+ className="flex justify-end"+ onClick={(e) => e.stopPropagation()}+ >+ <ProjectActionDropdown+ project={project}+ onAction={handleProjectAction}+ />+ </div>+ </td>+ </tr>+ );+ })+ )}+ </tbody>+ </table>++ {/* Pagination footer */}+ <div className="flex items-center justify-end gap-x-2 mx-4">+ <div className="flex items-center gap-x-2">+ <span className="text-sm text-control-light">+ {t("common.rows-per-page")}+ </span>+ <select+ className="border border-control-border rounded-md text-sm pl-2 pr-6 py-1 min-w-[5rem]"+ value={pageSize}+ onChange={(e) => setPageSize(Number(e.target.value))}+ >+ {pageSizeOptions.map((size) => (+ <option key={size} value={size}>+ {size}+ </option>+ ))}+ </select>+ </div>+ {hasMore && (+ <Button+ variant="ghost"+ size="sm"+ disabled={isFetchingMore}+ onClick={loadMore}+ >+ <span className="text-sm text-control-light">+ {isFetchingMore ? t("common.loading") : t("common.load-more")}+ </span>+ </Button>+ )}+ </div>+ </div>++ {/* Create drawer */}+ <CreateProjectDrawer+ open={showCreateDrawer}+ onClose={() => setShowCreateDrawer(false)}+ onCreated={handleCreated}+ />+ </div>+ );+}++// ============================================================+// LabelsDisplay+// ============================================================++function LabelsDisplay({ labels }: { labels: { [key: string]: string } }) {+ const entries = Object.entries(labels);+ if (entries.length === 0)+ return <span className="text-control-placeholder">-</span>;++ const displayEntries = entries.slice(0, 3);+ const hasMore = entries.length > 3;++ return (+ <div className="flex items-center gap-x-1">+ {displayEntries.map(([key, value]) => (+ <span key={key} className="rounded-lg bg-gray-100 py-0.5 px-2 text-sm">+ {key}:{value}+ </span>+ ))}+ {hasMore && <span>...</span>}+ </div>+ );+}diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.tsindex 83fba21e00..776b59f37f 100644--- a/frontend/src/router/dashboard/workspace.ts+++ b/frontend/src/router/dashboard/workspace.ts@@ -59,10 +59,13 @@ const workspaceRoutes: RouteRecordRaw[] = [title: () => t("common.projects"),},components: {- content: () => import("@/views/ProjectDashboard.vue"),+ content: () => import("@/react/ReactPageMount.vue"),leftSidebar: () => import("@/views/DashboardSidebar.vue"),},- props: { content: true, leftSidebar: true },+ props: {+ content: () => ({ page: "ProjectsPage" }),+ leftSidebar: true,+ },},{path: "instances",diff --git a/frontend/src/views/ProjectDashboard.vue b/frontend/src/views/ProjectDashboard.vuedeleted file mode 100644index a7fa6d1b34..0000000000--- a/frontend/src/views/ProjectDashboard.vue+++ /dev/null@@ -1,224 +0,0 @@-<template>- <div class="py-4 flex flex-col">- <div class="flex items-center justify-between px-4 pb-2 gap-x-2">- <AdvancedSearch- v-model:params="state.params"- :scope-options="scopeOptions"- :autofocus="false"- :placeholder="$t('project.filter-projects')"- />- <PermissionGuardWrapper- v-slot="slotProps"- :permissions="['bb.projects.create']"- >- <NButton- type="primary"- :disabled="slotProps.disabled"- @click="state.showCreateDrawer = true"- >- <template #icon>- <PlusIcon class="h-4 w-4" />- </template>- {{ $t("quick-action.new-project") }}- </NButton>- </PermissionGuardWrapper>- </div>- <div>- <ProjectOperations- v-if="hasWorkspacePermissionV2('bb.projects.delete')"- :project-list="selectedProjectList"- @update="handleBatchOperation"- />- <PagedProjectTable- ref="pagedProjectTableRef"- session-key="bb.project-table"- :filter="filter"- :bordered="false"- :footer-class="'mx-4'"- :prevent-default="!!onRowClick"- :show-selection="true"- :show-actions="true"- :selected-project-names="selectedProjectNames"- @update:selected-project-names="updateSelectedProjects"- @row-click="onRowClick"- />- </div>- </div>- <Drawer- :auto-focus="true"- :close-on-esc="true"- :show="state.showCreateDrawer"- @close="state.showCreateDrawer = false"- >- <ProjectCreatePanel- :on-created="handleCreated"- @dismiss="state.showCreateDrawer = false"- />- </Drawer>-</template>--<script lang="ts" setup>-import { PlusIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, onMounted, reactive, ref, watch } from "vue";-import type { ComponentExposed } from "vue-component-type-helpers";-import { useRoute, useRouter } from "vue-router";-import AdvancedSearch, {- useCommonSearchScopeOptions,-} from "@/components/AdvancedSearch";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import ProjectCreatePanel from "@/components/Project/ProjectCreatePanel.vue";-import { Drawer, PagedProjectTable } from "@/components/v2";-import ProjectOperations from "@/components/v2/Model/Project/ProjectOperations.vue";-import { useProjectV1Store, useUIStateStore } from "@/store";-import { State } from "@/types/proto-es/v1/common_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import {- buildSearchParamsBySearchText,- buildSearchTextBySearchParams,- getValueFromSearchParams,- getValuesFromSearchParams,- hasWorkspacePermissionV2,- type SearchParams,-} from "@/utils";--interface LocalState {- params: SearchParams;- showCreateDrawer: boolean;- selectedProjects: Set<string>;-}--const props = defineProps<{- onRowClick?: (project: Project) => void;-}>();--const state = reactive<LocalState>({- params: {- query: "",- scopes: [],- },- showCreateDrawer: false,- selectedProjects: new Set(),-});--const route = useRoute();-const router = useRouter();-const projectStore = useProjectV1Store();--const pagedProjectTableRef = ref<ComponentExposed<typeof PagedProjectTable>>();--// Add label and state to the available scopes for filtering projects-// Filter state options based on permissions-const scopeOptions = computed(() => {- const baseOptions = useCommonSearchScopeOptions(["label", "state"]).value;-- // If user doesn't have undelete permission, remove DELETED and ALL from state scope- if (!hasWorkspacePermissionV2("bb.projects.undelete")) {- return baseOptions.map((scope) => {- if (scope.id === "state" && scope.options) {- return {- ...scope,- options: scope.options.filter((opt) => opt.value === "ACTIVE"),- };- }- return scope;- });- }-- return baseOptions;-});--// Extract labels from the search scopes-const selectedLabels = computed(() => {- return getValuesFromSearchParams(state.params, "label");-});--const selectedState = computed(() => {- const stateValue = getValueFromSearchParams(state.params, "state");- if (stateValue === "DELETED") return State.DELETED;- if (stateValue === "ALL") return undefined; // undefined = show all- return State.ACTIVE; // default-});--const filter = computed(() => ({- query: state.params.query,- excludeDefault: true,- labels: selectedLabels.value,- state: selectedState.value,-}));--const selectedProjectNames = computed(() => {- return Array.from(state.selectedProjects);-});--const selectedProjectList = computed(() => {- if (state.selectedProjects.size === 0) {- return [];- }- return Array.from(state.selectedProjects)- .map((name) => projectStore.getProjectByName(name))- .filter((p): p is Project => p !== undefined);-});--const updateSelectedProjects = (projectNames: string[]) => {- state.selectedProjects = new Set(projectNames);-};--const handleBatchOperation = () => {- state.selectedProjects.clear();- pagedProjectTableRef.value?.refresh();-};--onMounted(() => {- // Migrate old URL format (?state=archived) to new format (?q=state:archived)- const queryState = router.currentRoute.value.query.state as string;- if (queryState === "archived" || queryState === "all") {- const stateValue = queryState === "archived" ? "DELETED" : "ALL";- router.replace({- query: { q: `state:${stateValue}` },- });- }-- // Initialize params from URL query- const queryString = route.query.q as string;- if (queryString) {- state.params = buildSearchParamsBySearchText(queryString);- }-- const uiStateStore = useUIStateStore();- if (!uiStateStore.getIntroStateByKey("project.visit")) {- uiStateStore.saveIntroStateByKey({- key: "project.visit",- newState: true,- });- }-});--// Sync params to URL query when params change-watch(- () => state.params,- (params) => {- const queryString = buildSearchTextBySearchParams(params);- const currentQuery = route.query.q as string;-- // Only update URL if query string has actually changed- if (queryString !== currentQuery) {- router.replace({- query: queryString ? { q: queryString } : {},- });- }- },- { deep: true }-);--const handleCreated = async (project: Project) => {- if (props.onRowClick) {- return props.onRowClick(project);- }- const url = {- path: `/${project.name}`,- };- router.push(url);- state.showCreateDrawer = false;-};-</script>