Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: migrate SQL Editor components to React (#20078)
ecmadao5fd104fafefb
diff --git a/docs/superpowers/specs/2026-04-21-sql-editor-react-migration-stage-7-design.md b/docs/superpowers/specs/2026-04-21-sql-editor-react-migration-stage-7-design.mdnew file mode 100644index 0000000000..2d7cd955aa--- /dev/null+++ b/docs/superpowers/specs/2026-04-21-sql-editor-react-migration-stage-7-design.md@@ -0,0 +1,197 @@+# SQL Editor React Migration — Stage 7 Design++**Date:** 2026-04-21+**Author:** [email protected]+**Status:** Draft++## 1. Goal & non-goals++**Goal:** Migrate `EditorCommon/SharePopover.vue` (228 lines, 2 callers) to React. Both Vue callers (`EditorAction.vue` and `SheetTree.vue`) swap to `<ReactPageMount page="SharePopoverBody" ... />`. Vue file is deletable after both swaps. Reuses the `Popover` primitive built in Stage 6 for the nested visibility-selector.++**Non-goals:**+- Porting `CopyButton.vue` (10+ Vue callers — out of scope). Use inline `navigator.clipboard.writeText` pattern already established in multiple React files.+- Emittery or async-action bridges (deferred to a later stage).+- Migrating `SheetTree.vue` (851 lines) or `EditorAction.vue` themselves — only the one-line swaps where they embed `<SharePopover>`.+- Moving the outer `NPopover` click-trigger (the Share button in the toolbar) — only the popover *content* migrates.+- Deprecating CopyButton — still heavily used elsewhere.++## 2. Architecture++**One React component** (`SharePopoverBody.tsx`, ~200 lines) replaces the body of the Vue `SharePopover`. Mounted as the content slot of Vue's outer `NPopover` in both caller files:++```vue+<!-- Before (EditorAction and SheetTree both use this pattern) -->+<NPopover trigger="click" ...>+ <template #trigger>...share button...</template>+ <template #default>+ <SharePopover :worksheet="..." @on-updated="..." />+ </template>+</NPopover>++<!-- After -->+<NPopover trigger="click" ...>+ <template #trigger>...share button...</template>+ <template #default>+ <ReactPageMount page="SharePopoverBody"+ :worksheet="..." :onUpdated="..." />+ </template>+</NPopover>+```++Note: `@on-updated` (Vue event emit) → `:onUpdated` (explicit prop-callback) per the Stage 1 kebab-case-prop learning. Vue's `attrs` doesn't auto-camelCase kebab-case bindings.++## 3. The React component++**File:** `frontend/src/react/components/sql-editor/SharePopoverBody.tsx`++**Props:**+```tsx+type Props = {+ readonly worksheet?: Worksheet;+ readonly onUpdated?: () => void;+};+```++**Structure (mirrors Vue source):**++- **Header section:** "Share" title + visibility selector.+ - Visibility selector is a nested Popover using Stage 6's `Popover` primitive.+ - Selector trigger shows the current access level label + a `ChevronDown` icon.+ - Nested popover content lists 3 options: Private, Project Read, Project Write.+ - Each option: icon (`LockKeyhole` for Private, `Users` for the two Project options) + label + description + `Check` mark if currently selected.+ - Non-creators see the selector styled as read-only (disabled).++- **Link display:** input field showing the shareable URL with `Link2` icon prefix + copy button.+ - Copy button calls `navigator.clipboard.writeText` directly (no CopyButton component).+ - Copy button disabled unless the current tab's status is `"CLEAN"` (mirrors the Vue predicate).++**Stores (top-level hooks):**+- `useActuatorV1Store` — for `workspaceExternalURL`+- `useCurrentUserV1` — for `me` (creator check)+- `useWorkSheetStore` — for `patchWorksheet`+- `pushNotification` — for success toasts (imported from `@/store`)+- `useSQLEditorTabStore` — for `currentTab` (copy button disabled gate)++**Router:**+- `router.resolve({ name: SQL_EDITOR_WORKSHEET_MODULE, params: { project, sheet } }).href` — builds the shareable link, then constructs absolute URL via `new URL(href, workspaceExternalURL || window.location.origin)`.++**Icons (lucide-react swaps):**+- heroicons-solid `chevron-down` → `ChevronDown` from lucide-react+- heroicons-solid `check` → `Check` from lucide-react+- heroicons-solid `link` → `Link2` from lucide-react+- `LockKeyhole`, `Users` — same lucide names (Vue also uses lucide-vue-next)++**Access change flow (`handleChangeAccess`):**+1. Guard: user isn't the creator or no worksheet → no-op.+2. Call `worksheetStore.patchWorksheet(worksheet, { visibility }, ["visibility"])`.+3. If clipboard is available, `navigator.clipboard.writeText(sharedTabLink)`; push notification "URL copied to clipboard". Else push "Updated".+4. Call `onUpdated?.()` prop callback (Vue source emits `on-updated`).+5. Close the nested visibility selector popover.++## 4. Vue caller swaps++### 4.1 `EditorAction.vue`++Find the `<SharePopover :worksheet="..." />` occurrence (around line 107 in current file). Replace:++```vue+<SharePopover :worksheet="sheetAndTabStore.currentSheet" />+```++with:++```vue+<ReactPageMount page="SharePopoverBody"+ :worksheet="sheetAndTabStore.currentSheet" />+```++Drop the `import SharePopover from "./SharePopover.vue";` line. `ReactPageMount` is already imported from Stage 4. No `onUpdated` prop needed — the Vue original didn't pass one.++### 4.2 `SheetTree.vue`++Find the caller via `grep -n SharePopover frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue`. Replace:++```vue+<SharePopover+ :worksheet="worksheetEntity"+ @on-updated="handleContextMenuClickOutside"+/>+```++with:++```vue+<ReactPageMount page="SharePopoverBody"+ :worksheet="worksheetEntity"+ :onUpdated="handleContextMenuClickOutside" />+```++Drop the `import SharePopover from "@/views/sql-editor/EditorCommon/SharePopover.vue";` line. Add `import ReactPageMount from "@/react/ReactPageMount.vue";` if not already present.++## 5. Vue file deletion++Post-swap verification:+```bash+grep -rn "SharePopover" frontend/src/ | grep -v "frontend/src/react/"+```++Expected: zero Vue references outside the file being deleted and the `EditorCommon/index.ts` barrel.++Then:+```bash+rm frontend/src/views/sql-editor/EditorCommon/SharePopover.vue+```++And remove `SharePopover` from both the import block and the export block in `frontend/src/views/sql-editor/EditorCommon/index.ts`.++This is the first multi-caller migration where the Vue file IS cleanly deletable (because both callers migrate together). Sets the precedent for future multi-caller cleanup.++## 6. i18n keys++Verify in all 5 React locales; add missing using Vue locale values byte-exact:+- `sql-editor.link-access`+- `sql-editor.private`+- `sql-editor.private-desc`+- `sql-editor.project-read`+- `sql-editor.project-read-desc`+- `sql-editor.project-write`+- `sql-editor.project-write-desc`+- `sql-editor.url-copied-to-clipboard`+- `common.share` (probably exists)+- `common.updated` (probably exists)++## 7. Verification++- `pnpm fix && check && type-check && test` all green+- New tests (~6) in `SharePopoverBody.test.tsx`:+ - Renders "Share" title and link input+ - Shows 3 visibility options (Private, Project Read, Project Write) with correct icons+ - Disables the visibility selector when user is not creator+ - `handleChangeAccess` calls `patchWorksheet` and `pushNotification` and invokes `onUpdated` callback+ - Copy button writes to clipboard and pushes notification+ - Copy button disabled when `currentTab?.status !== "CLEAN"`++**Manual UX:**+1. EditorAction share button: click opens outer popover → see Share title + visibility selector + URL + copy button+2. Copy button click → URL copied + toast notification+3. Change visibility (creator only) → worksheet updated, URL auto-copied, toast shown+4. Non-creator sees visibility selector disabled+5. SheetTree context menu share: click opens popover → same behavior + parent closes on `onUpdated`++## 8. Out of scope (deferred)++- CopyButton React port (10+ Vue callers — separate concern).+- Emittery events bridge.+- Async-actions bridge (maybeSwitchProject / createWorksheet / abortAutoSave etc.).+- Vue-in-React mount infrastructure.++## 9. Practical checklist++- [ ] `react/components/sql-editor/SharePopoverBody.tsx` + test created+- [ ] 8 i18n keys verified/added+- [ ] `EditorAction.vue` swap (1 template line + 1 import line)+- [ ] `SheetTree.vue` swap (1 template line + 1 import line)+- [ ] Vue `SharePopover.vue` deleted+- [ ] `EditorCommon/index.ts` barrel import + export removed+- [ ] `pnpm fix && check && type-check && test` all pass+- [ ] Manual UX verified from both call sites (EditorAction share button + SheetTree context-menu share)diff --git a/docs/superpowers/specs/2026-04-21-sql-editor-react-migration-stage-8-design.md b/docs/superpowers/specs/2026-04-21-sql-editor-react-migration-stage-8-design.mdnew file mode 100644index 0000000000..db58537ece--- /dev/null+++ b/docs/superpowers/specs/2026-04-21-sql-editor-react-migration-stage-8-design.md@@ -0,0 +1,276 @@+# SQL Editor React Migration — Stage 8 Design (Revised)++**Date:** 2026-04-21+**Author:** [email protected]+**Status:** Implemented as infrastructure-only (UI migration reverted mid-stage per the no-partial-regression principle)++## Revision note++The original Stage 8 plan included migrating `SaveSheetModal.vue` as the first consumer of the new bridges, with a "ship without folder picker (F2)" feature regression to avoid porting the heavyweight `FolderForm.vue` sub-dependency.++**That plan was wrong.** After the React SaveSheetModal shipped, the missing folder picker was flagged as a visible UX regression. The user established a firm rule: *during migration, either don't migrate the Vue file at all, or migrate the entire UX with full feature parity — no middle way.* (See `feedback_migration_no_partial_regression.md` in memory.)++The SaveSheetModal portion was reverted. Stage 8 ships as infrastructure only. SaveSheetModal migration is deferred until `FolderForm` + its tree primitive + `useSheetContextByView` inject bridge are ready (a future stage).++## 1. Goal & non-goals++**Goal:** Build the Emittery `events` bus bridge and the async-actions bridge so that future stages (starting with Stage 9+) can migrate Vue files that consume editor events or call the async worksheet methods, without having to design the bridges each time.++**Non-goals (Stage 8):**+- Migrating any Vue UI component. No `.vue` file is swapped or deleted.+- Porting `FolderForm.vue` or a tree primitive.+- Bridging the AI plugin context (`useAIContext`).+- Vue-in-React mount infrastructure.++## 2. What shipped++### 2.1 Emittery singleton++**File:** `frontend/src/views/sql-editor/events.ts`++Extracted the `SQLEditorEvents` type union from `context.ts` and created a module-level singleton Emittery instance. Both Vue and React code import the same instance directly; emit/listen is symmetric across both.++```ts+import Emittery from "emittery";+import type { IRange } from "monaco-editor";+import type { SQLEditorTab } from "@/types";++export type SQLEditorEvents = {+ "save-sheet": { tab: SQLEditorTab; editTitle?: boolean };+ "alter-schema": { databaseName: string; schema: string; table: string };+ "format-content": undefined;+ "tree-ready": undefined;+ "project-context-ready": { project: string };+ "set-editor-selection": IRange;+ "append-editor-content": { content: string; select: boolean };+ "insert-at-caret": { content: string };+};++export const sqlEditorEvents: Emittery<SQLEditorEvents> =+ new Emittery<SQLEditorEvents>();+```++**Test:** `frontend/src/views/sql-editor/events.test.ts` — 2 tests: singleton identity, emit/on roundtrip.++### 2.2 React subscription hook++**File:** `frontend/src/react/hooks/useSQLEditorEvent.ts`++```ts+export function useSQLEditorEvent<E extends keyof SQLEditorEvents>(+ event: E,+ handler: (data: SQLEditorEvents[E]) => void+): void;+```++Uses a ref pattern so handler identity changes don't cause resubscribe churn. Unsubscribes on unmount. React consumers that need to emit import `sqlEditorEvents` directly and call `.emit(...)`.++**Test:** `frontend/src/react/hooks/useSQLEditorEvent.test.tsx` — 3 tests: subscribe on mount, unsubscribe on unmount, handler ref updates on rerender.++### 2.3 Async-actions Pinia store++**File:** `frontend/src/store/modules/sqlEditor/worksheet.ts`++Created `useSQLEditorWorksheetStore` — a Pinia setup-store that lifted 4 methods and the auto-save AbortController out of `provideSQLEditorContext()`:++- `autoSaveController: Ref<AbortController | null>`+- `abortAutoSave()` — aborts controller and clears it+- `maybeSwitchProject(projectName)` — fetches project + IAM policy, sets `editorStore.project`, emits `project-context-ready`+- `maybeUpdateWorksheet({ tabId, worksheet, title, database, statement, folders, signal })` — patches existing worksheet+- `createWorksheet({ tabId, title, statement, folders, database })` — creates new worksheet, optionally opens a new tab++Follows the same pattern as Stage 2's `useSQLEditorUIStore` lift. Closures over 5 sibling Pinia stores are moved into the setup function.++Exported from the `sqlEditor/index.ts` barrel.++**Test:** `frontend/src/store/modules/sqlEditor/worksheet.test.ts` — 4 smoke tests: initial controller state, abortAutoSave no-op and active paths, maybeSwitchProject with invalid name.++### 2.4 `context.ts` refactor++Changed `provideSQLEditorContext()` to delegate:+- `events` field: changed from `new Emittery()` to the `sqlEditorEvents` singleton+- The 4 async action fields: delegated to `useSQLEditorWorksheetStore()`+- The module-level `autoSaveController` and `abortAutoSave` function: removed; `watchDebounced` auto-save composable now uses `worksheetStore.abortAutoSave()` and `worksheetStore.maybeUpdateWorksheet(...)` directly, and reads/writes `worksheetStore.autoSaveController` for controller management++**Invariant preserved:** The `SQLEditorContext` type shape is identical. All 30+ Vue consumers of `useSQLEditorContext()` continue to work without edits.++Type re-export compatibility: `SQLEditorEvents` is re-exported from `context.ts` as `Emittery<SQLEditorEventsMap>` (Emittery-wrapped type) so that Vue consumers typing parameters as `SQLEditorEvents` work unchanged. The new `events.ts` exports the plain event-name map.++## 3. What this unblocks for future stages++Any Vue file that uses `useSQLEditorContext().events.on(...)`, `.emit(...)`, or the 4 async methods can now have a React equivalent that uses:+- `useSQLEditorEvent("event-name", handler)` for listening+- `sqlEditorEvents.emit("event-name", data)` for emitting+- `useSQLEditorWorksheetStore()` for the async methods++Future stage candidates that consume these bridges:+- `HistoryPane.vue` — emits `append-editor-content`+- `ErrorView.vue`, `AdviceItem.vue` — emit `set-editor-selection`+- `TabList.vue` — consumes `createWorksheet`+- `SaveSheetModal.vue` — when `FolderForm` is ported (full parity restoration)+- `AsidePanel.vue` — consumes `maybeSwitchProject`++## 4. What was reverted (and why)++The original plan (now understood to violate the no-partial-regression principle):+- Created React `SaveSheetModal.tsx` that passed `folders: []` on both save paths.+- Swapped `StandardPanel.vue`'s caller to `<ReactPageMount page="SaveSheetModal" />`.+- Deleted the Vue `SaveSheetModal.vue`.+- Added `sql-editor.save-sheet` + `save-sheet-input-placeholder` i18n keys.++Problem: users lost the folder-picker UI when saving new worksheets. Existing folder assignments were preserved by backend but could not be changed through the React modal. This was a real regression, not acceptable per the no-partial-regression principle.++Revert actions:+- Deleted React `SaveSheetModal.tsx` + test+- Restored Vue `SaveSheetModal.vue` (via `git checkout`)+- Restored `EditorCommon/index.ts` barrel (import + export for `SaveSheetModal`)+- Restored `StandardPanel.vue:64` to `<SaveSheetModal />`+- Removed the 2 i18n keys from all 5 React locales (no React consumer now)++## 5. Verification of what shipped++- `pnpm fix && check && type-check && test` all green+- Tests: 1286 passing — includes the +9 Stage 8 infra tests (2 events + 3 hook + 4 store)+- Type-check baseline only (6 pre-existing `SchemaEditorLite` errors, no new)+- No Vue UI changed; no Vue files deleted+- `useSQLEditorContext()` returns identical shape; all existing Vue flows (save-sheet via Ctrl+S, auto-save, project switch, worksheet create from Welcome) work unchanged — exercised via the refactored `watchDebounced` composable and the store-delegated methods++## 6. Practical checklist++### Infrastructure (completed)++- [x] `frontend/src/views/sql-editor/events.ts` created+- [x] `frontend/src/views/sql-editor/events.test.ts` created+- [x] `frontend/src/react/hooks/useSQLEditorEvent.ts` created+- [x] `frontend/src/react/hooks/useSQLEditorEvent.test.tsx` created+- [x] `frontend/src/store/modules/sqlEditor/worksheet.ts` created+- [x] `frontend/src/store/modules/sqlEditor/worksheet.test.ts` created+- [x] `modules/sqlEditor/index.ts` barrel exports new store+- [x] `context.ts` refactored (type re-export, events singleton, async-method delegation, auto-save composable uses store)+- [x] `SQLEditorContext` shape preserved; Vue consumers unchanged+- [x] `pnpm fix && check && type-check && test` all pass+- [ ] ~~React SaveSheetModal + swap + deletion~~ — REVERTED per §4++### HistoryPane migration (new addition — full feature parity)++- [ ] `frontend/src/react/components/sql-editor/HistoryPane.tsx` created+- [ ] `frontend/src/react/components/sql-editor/HistoryPane.test.tsx` created+- [ ] React locale keys added (see §7.3)+- [ ] `AsidePanel.vue:57` swapped: `<HistoryPane v-if="asidePanelTab === 'HISTORY'" />` → `<ReactPageMount v-if="asidePanelTab === 'HISTORY'" page="HistoryPane" />`+- [ ] `AsidePanel.vue:82` import updated: remove `import HistoryPane from "./HistoryPane";`+- [ ] Vue directory `frontend/src/views/sql-editor/AsidePanel/HistoryPane/` deleted after `rg` confirms zero remaining callers (sub-file `HistoryConnectionIcon.vue` usage audit needed)++### Orphan cleanup++- [ ] Delete `frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/AdviceItem.vue` (confirmed zero callers — dead code)++## 7. HistoryPane React migration — full feature parity++### 7.1 New React file++`frontend/src/react/components/sql-editor/HistoryPane.tsx`++**Props:** zero. Mounted via `<ReactPageMount page="HistoryPane" />` from `AsidePanel.vue`.++**Store reads (via `useVueState`):**+- `useSQLEditorTabStore()` → `currentTab?.connection.database`+- `useSQLEditorStore()` → `project`+- `useSQLEditorQueryHistoryStore()` → `getQueryHistoryList(filter)`, `fetchQueryHistoryList(filter)`, `resetPageToken(filter)`++**State:**+- `searchText: string` — user's search input+- `loading: boolean` — fetch-in-progress flag++**Effects:**+- Initial fetch + refetch when historyQuery changes (i.e., when tab/database/project/searchText changes)+- Debounced search (300ms via setTimeout in a ref)++**Feature parity points:**++| Vue feature | React mapping |+|---|---|+| `SearchBox` from v2 | `SearchInput` from `@/react/components/ui/search-input` |+| `CopyButton` from v2 | Inline button calling `navigator.clipboard.writeText(history.statement)` + push "Copied" notification (pattern established in Stage 7 SharePopoverBody) |+| `MaskSpinner` loading overlay | `Loader2` from `lucide-react` with `animate-spin` (established React loader pattern, used in `IssueTable.tsx`, etc.) |+| `v-html` + `getHighlightHTMLByKeyWords` | `dangerouslySetInnerHTML={{ __html: getHighlightHTMLByKeyWords(statement, searchText) }}` — the utility is already exported from `@/utils/util.ts` and returns pre-escaped HTML |+| `NButton quaternary size="small"` load-more | shadcn `Button variant="ghost" size="sm"` |+| `useDebounceFn` (vueuse) | `useEffect` with `setTimeout` + ref, mirroring the Stage 1 debounce pattern |+| `dayjs` timestamp formatting | Same `dayjs` — already imported elsewhere in React |+| `pushNotification` on copy | Same — imported from `@/store` in React |+| Empty state: "No history found" | Same |+| Click history row → emit `append-editor-content` | `sqlEditorEvents.emit("append-editor-content", { content, select: true })` |+| If no current tab: `tabStore.addTab(...)` | Same — direct Pinia call |++**Styling parity:**+- Outer: `relative w-full h-full flex flex-col justify-start items-start`+- Search row: `w-full px-1`+- List container: `w-full flex flex-col justify-start items-start overflow-y-auto`+- Each row: `w-full p-2 gap-y-1 border-b flex flex-col ... cursor-pointer hover:bg-gray-50` — or `hover:bg-control-bg` to use semantic tokens+- Timestamp span: `text-xs text-gray-500` — or `text-control-placeholder` for semantic parity+- Statement preview: `max-w-full text-xs wrap-break-word font-mono line-clamp-3`+- Load-more button centered in `w-full flex flex-col items-center my-2`+- Loading overlay: full-cover flex-center with spinner+- Empty state: `w-full flex items-center justify-center py-8 textinfolabel`++### 7.2 Test file++`HistoryPane.test.tsx` — 5 tests:+1. Renders with no history → empty state "No history found"+2. Renders history list with 2 entries → both timestamps and statement previews visible+3. Typing in search → debounced store call with updated filter+4. Click history row → `sqlEditorEvents.emit("append-editor-content", { content, select: true })` called (mock the singleton)+5. Click copy button → `navigator.clipboard.writeText(history.statement)` called + notification pushed++Use the established mock pattern: `vi.hoisted` for store factory stubs, mock the Emittery singleton via `vi.mock("@/views/sql-editor/events", ...)`, mock the icons/primitives as pass-throughs where needed.++### 7.3 i18n keys++Verify these in all 5 React locales; add missing using Vue values byte-exact:+- `sql-editor.search-history-by-statement`+- `sql-editor.no-history-found`+- `common.load-more`+- `common.copy` (for the copy-button aria-label) — verify existence++### 7.4 Caller swap++`AsidePanel.vue:57`:+```vue+<!-- Before -->+<HistoryPane v-if="asidePanelTab === 'HISTORY'" />++<!-- After -->+<ReactPageMount+ v-if="asidePanelTab === 'HISTORY'"+ page="HistoryPane"+/>+```++Line 82: remove `import HistoryPane from "./HistoryPane";`. (`ReactPageMount` already imported in Stage 3.)++### 7.5 Vue file deletion++`frontend/src/views/sql-editor/AsidePanel/HistoryPane/` directory — check contents. The spec in Stage 3 already noted this directory has additional sub-files beyond `HistoryPane.vue`:+- `HistoryPane.vue` — target+- `HistoryConnectionIcon.vue` (27 lines) — small helper icon used inside HistoryPane++If `HistoryConnectionIcon.vue` is only used by `HistoryPane.vue`, the whole directory gets deleted. If it's used elsewhere, only `HistoryPane.vue` + its index file get deleted; `HistoryConnectionIcon.vue` retained.++Verify via `rg` before deletion.++**Note:** Checking the Vue `HistoryPane.vue` source, I don't see a `HistoryConnectionIcon` import — it may be dead code in the same directory, separately cleanup-able. Implementer will verify and handle during migration.++## 8. AdviceItem cleanup (orphan deletion)++`frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/AdviceItem.vue` (92 lines) has **zero callers** anywhere in the codebase. Grep confirmed no file imports or references it.++Simple cleanup:+- Verify zero callers one more time during implementation via `rg "AdviceItem"`+- Delete the file++No React migration needed — the file is dead code.++## 9. Deferred (explicitly future stages)++- **SaveSheetModal React migration with full parity** — requires `FolderForm` + tree primitive + `useSheetContextByView` inject bridge as prerequisites. Not in scope until those are ready.+- **Tree primitive + `FolderForm` port** — separate stage. Prerequisites: decide on a virtualized tree library (react-arborist, react-window, react-virtuoso) and port `TreeNodePrefix` + `useSheetContextByView` bridge.+- **AI plugin context bridge** — needed for future OpenAIButton migration.diff --git a/docs/superpowers/specs/2026-04-21-sql-editor-react-migration-stage-9-design.md b/docs/superpowers/specs/2026-04-21-sql-editor-react-migration-stage-9-design.mdnew file mode 100644index 0000000000..fe03abbc5d--- /dev/null+++ b/docs/superpowers/specs/2026-04-21-sql-editor-react-migration-stage-9-design.md@@ -0,0 +1,240 @@+# SQL Editor React Migration — Stage 9 Design++**Date:** 2026-04-21+**Author:** [email protected]+**Status:** Draft++## 1. Goal & non-goals++**Goal:** Migrate the AccessPane subtree (3 Vue files, ~800 lines) to React with full feature parity. Add an `"execute-sql"` event to the Stage 8 Emittery bridge with a Vue listener in `StandardPanel.vue` so the React `AccessPane` can request SQL execution without porting the 364-line `useExecuteSQL` composable.++**Non-goals:**+- Porting `useExecuteSQL.ts` to React — deferred to a dedicated stage.+- Migrating any other aside panel subtree (SchemaPane, WorksheetPane, TabList).+- AI plugin context bridge or OpenAIButton migration.+- FolderForm / tree primitive work.+- Any Vue file beyond the 3 AccessPane files and the targeted modifications to events.ts / StandardPanel.vue / AsidePanel.vue.++## 2. Files involved++**Create (React):**+- `frontend/src/react/components/sql-editor/AccessPane.tsx` (~350 lines)+- `frontend/src/react/components/sql-editor/AccessPane.test.tsx`+- `frontend/src/react/components/sql-editor/AccessGrantItem.tsx` (~250 lines)+- `frontend/src/react/components/sql-editor/AccessGrantItem.test.tsx`+- `frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx` (~350 lines)+- `frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx`++**Modify:**+- `frontend/src/views/sql-editor/events.ts` — add `"execute-sql"` event type+- `frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue` — subscribe to `execute-sql` event via `useEmitteryEventListener`, call existing `execute` handler+- `frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue:58` — swap `<AccessPane v-if="asidePanelTab === 'ACCESS'" />` to `<ReactPageMount v-if="asidePanelTab === 'ACCESS'" page="AccessPane" />` and drop the `AccessPane` import+- React locales (5 files) — add missing i18n keys with Vue `{var}` → React `{{var}}` conversion++**Delete:** `frontend/src/views/sql-editor/AsidePanel/AccessPane/` (3 files + any `index.ts` after zero-caller verification)++## 3. `execute-sql` event bridge++### 3.1 Event type++Add to `frontend/src/views/sql-editor/events.ts`'s `SQLEditorEvents` union:++```ts+"execute-sql": {+ connection: SQLEditorConnection;+ statement: string;+ batchQueryContext?: BatchQueryContext;+};+```++Import types as needed (`SQLEditorConnection`, `BatchQueryContext`) from `@/types`.++### 3.2 Vue handler in StandardPanel.vue++Adds a listener inside the existing `<script setup>` block using the existing Vue composable pattern:++```ts+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";+import { useDatabaseV1Store } from "@/store";+import { sqlEditorEvents } from "@/views/sql-editor/events";+// (existing imports — keep)++// After `const { execute } = useExecuteSQL();` (or wherever execute is acquired):+useEmitteryEventListener(+ sqlEditorEvents,+ "execute-sql",+ async ({ connection, statement, batchQueryContext }) => {+ await useDatabaseV1Store().getOrFetchDatabaseByName(connection.database);+ const tab = tabStore.addTab(+ { connection, statement, batchQueryContext },+ /* beside */ true+ );+ nextTick(() => {+ const instance = getInstanceResource(tab.connection); // import from @/utils if not already+ execute({+ connection: { ...tab.connection },+ statement,+ engine: instance.engine,+ explain: false,+ selection: null,+ limit: 0,+ });+ });+ }+);+```++### 3.3 React emit point++Inside `AccessPane.tsx`'s Run handler:++```ts+import { sqlEditorEvents } from "@/views/sql-editor/events";++const handleRun = async (grant: AccessGrant) => {+ const database = grant.targets[0] ?? "";+ const instanceName = database.replace(/\/databases\/.*$/, "");+ await sqlEditorEvents.emit("execute-sql", {+ connection: { instance: instanceName, database },+ statement: grant.query,+ batchQueryContext: { databases: grant.targets },+ });+};+```++Note: this keeps the 364-line `useExecuteSQL` composable Vue-side. Future stages may port it; Stage 9 bridges via event.++## 4. React files — feature parity map++### 4.1 `AccessPane.tsx`++Container + search + grants list + empty/loading states.++| Vue feature | React mapping |+|---|---|+| `AdvancedSearch` (Vue) | React `AdvancedSearch` from `@/react/components/AdvancedSearch` |+| `FeatureBadge` for JIT gating | React `FeatureBadge` from `@/react/components/FeatureBadge` |+| `PermissionGuardWrapper` | React `PermissionGuard` render-prop pattern (see `@/react/components/PermissionGuard`) |+| `MaskSpinner` loading overlay | `Loader2` + `animate-spin` (Stage 8 pattern) |+| `hasFeature(PlanFeature.FEATURE_JIT)` | Same — imported from `@/store` |+| Search params / `AccessFilter` / `getValueFromSearchParams` / `getValuesFromSearchParams` | Same — pure utilities, work in React |+| Responsive small-layout when `containerWidth < 250` | React `useRef<HTMLDivElement>` + `ResizeObserver` or inline `useLayoutEffect` pattern |+| `fetchAccessGrants` + `fetchIssuesForPendingGrants` | Same logic; `useState` + `useEffect` |+| Project/filter change refetch | `useEffect` with appropriate deps |+| `highlightAccessGrantName` auto-clear after 3s | Read via `useVueState(() => uiStore.highlightAccessGrantName)` from `useSQLEditorUIStore`; use `setTimeout` + direct store mutation to clear |+| Run grant | Emits `execute-sql` event (§3.3) |+| Request pre-fill | Local state → pass props to `<AccessGrantRequestDrawer>` |+| Open drawer | `useState<boolean>` for `showDrawer` |++**Props:** zero (mounted via `<ReactPageMount page="AccessPane" />`).++**Stores at top-level:** `useProjectV1Store`, `useSQLEditorStore`, `useSQLEditorTabStore`, `useAccessGrantStore`, `useIssueV1Store`, `useSQLEditorUIStore`. Get instance via `useConnectionOfCurrentSQLEditorTab` (composable — verify React usage works; may need a `useVueState` wrapper).++### 4.2 `AccessGrantItem.tsx`++Individual grant row.++| Vue feature | React mapping |+|---|---|+| `NTag` status badge, unmask badge | shadcn `Badge` with variant per status tag color |+| `NEllipsis` for expiration | `truncate` + Stage 6 `Tooltip` on overflow |+| `NTooltip` query-preview popover | React `Tooltip` primitive with pre block |+| Status display utilities (`getAccessGrantDisplayStatus`, `getAccessGrantStatusTagType`, `getAccessGrantDisplayStatusText`, `getAccessGrantExpirationText`, `getAccessGrantExpireTimeMs`) | Same — imported from `@/utils/accessGrant` |+| Database names display (2 + "and N more") | Same logic; use i18n with `{{n}}` |+| `Run` / `Re-request` / `View Issue` buttons | shadcn `Button` with `size="sm"` variants |+| `highlight-pulse` CSS keyframe animation | Inline `<style>` scoped or use `@keyframes` in component-local stylesheet OR reuse a utility class from tailwind config (implementation's choice) |++**Props:** `{ grant: AccessGrant; highlight?: boolean; issue?: Issue; onRun: (grant) => void; onRequest: (grant) => void }`++### 4.3 `AccessGrantRequestDrawer.tsx`++Request form drawer.++| Vue feature | React mapping |+|---|---|+| `Drawer` + `DrawerContent` (Vue v2) | React `Sheet` + `SheetContent` with `width="wide"` (832px) |+| `BBAttention type="info"` | React `Alert` (info variant) |+| `DatabaseSelect` (Vue, multiple) | React `DatabaseSelect` at `@/react/components/DatabaseSelect` |+| `MonacoEditor` (Vue) | React `MonacoEditor` at `@/react/components/monaco/MonacoEditor` |+| `NCheckbox` | Use native `<input type="checkbox">` styled via Tailwind OR `Switch` primitive if more shadcn-idiomatic. Check project conventions. |+| `NSelect` for duration (1h/4h/1d/7d/custom) | shadcn `Combobox` or `Select` |+| `NDatePicker` for custom expire | React `ExpirationPicker` from `@/react/components/ui/expiration-picker` |+| `NInput` textarea for reason | shadcn `Textarea` |+| `RequiredStar` | Inline `<span className="text-error">*</span>` |+| Access grant API call | Same `accessGrantServiceClientConnect.createAccessGrant` — protos framework-agnostic |+| On success: open issue OR set `asidePanelTab + highlightAccessGrantName` | Use `useSQLEditorUIStore()` for writes |++**Props:** `{ targets?: string[]; query?: string; unmask?: boolean; onClose: () => void }` — matches Vue's defineProps + emit close.++**Duration mapping:** `duration === -1` → custom datetime via `ExpirationPicker`. Other values → TTL seconds = `duration * 3600` (hours → seconds).++## 5. i18n keys++Verify these in all 5 React locales; add missing with byte-exact Vue values (convert `{var}` → `{{var}}` for react-i18next):++- `sql-editor.request-access`+- `sql-editor.no-access-requests`+- `sql-editor.grant-type-unmask`+- `sql-editor.access-type-unmask`+- `sql-editor.expire-at` (`{time}` → `{{time}}`)+- `sql-editor.expire-in` (`{time}` → `{{time}}`)+- `sql-editor.re-request`+- `sql-editor.view-issue`+- `sql-editor.request-data-access`+- `sql-editor.only-select-allowed`+- `sql-editor.duration-hours` (`{hours}` → `{{hours}}`)+- `sql-editor.duration-day` (`{days}` → `{{days}}`)+- `sql-editor.duration-days` (`{days}` → `{{days}}`)+- `sql-editor.and-n-more-databases` (`{n}` → `{{n}}`)+- `common.custom`, `common.run`, `common.submit`, `common.created`, `common.databases`, `common.statement`, `common.expiration`, `common.reason`+- `issue.access-grant.expired-at`+- `issue.advanced-search.filter`++Most `common.*` keys likely already exist. Priority verification: the 4 interpolation keys (`expire-at`, `expire-in`, `duration-*`, `and-n-more-databases`).++## 6. Verification++### 6.1 Per-stage++- `pnpm fix && check && type-check && test` all green+- ~15 new tests across 3 component test files+- No pre-existing flaky regressions++### 6.2 Manual UX (critical full-parity checklist)++1. Open aside panel → ACCESS tab → empty state shows when no grants, or filtered grants list shows when present+2. AdvancedSearch filters by status (default: ACTIVE + PENDING) and database; changes trigger refetch+3. JIT feature gating: `FeatureBadge` visible when plan lacks JIT feature; Request Access button disabled+4. Missing permission: Request Access button disabled with PermissionGuard tooltip+5. Click Request Access → drawer opens; DatabaseSelect populated; Monaco SQL editor functional; duration picker works; custom datetime picker shows when duration=Custom+6. Submit → access grant created → "Created" toast; if PENDING+issue, opens new tab to issue; otherwise sets `asidePanelTab=ACCESS` + highlights new grant+7. Click Run on ACTIVE grant → emits `execute-sql` event → new tab opens + query executes (via Vue handler in StandardPanel)+8. Click Re-request on rejected/canceled grant → drawer opens with grant.query, grant.unmask, grant.targets pre-filled+9. Click View Issue → opens issue detail in new tab+10. Highlight pulse animation fires for 3s when `highlightAccessGrantName` is set+11. Pagination "Load more" works++### 6.3 Bridge integrity++- Existing Vue flows unchanged: save-sheet (Ctrl+S), auto-save, project switch, query execution from run button+- New event flow: React AccessPane → `execute-sql` → StandardPanel Vue listener → `execute()` → tab opens + query runs++## 7. Practical checklist++- [ ] `events.ts` adds `execute-sql` event type+- [ ] `StandardPanel.vue` subscribes via `useEmitteryEventListener`+- [ ] `AccessPane.tsx` + test+- [ ] `AccessGrantItem.tsx` + test+- [ ] `AccessGrantRequestDrawer.tsx` + test+- [ ] i18n keys verified/added (with `{var}` → `{{var}}` conversion)+- [ ] `AsidePanel.vue:58` swapped + `AccessPane` import removed+- [ ] Vue `AsidePanel/AccessPane/` directory deleted+- [ ] `pnpm fix && check && type-check && test` all pass+- [ ] Manual UX from §6.2 verified++## 8. Out of scope (deferred)++- `useExecuteSQL` React port (keeps 364-line Vue composable; event-bridged per §3)+- Vue v2 component ports (CopyButton, BBAttention as a separate primitive, etc.) — Alert + inline copy patterns used instead+- Other aside panel subtrees (SchemaPane, WorksheetPane, TabList)+- AI plugin bridge, OpenAIButton, FolderFormdiff --git a/frontend/src/react/components/sql-editor/AccessGrantItem.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantItem.test.tsxnew file mode 100644index 0000000000..3ee221e86c--- /dev/null+++ b/frontend/src/react/components/sql-editor/AccessGrantItem.test.tsx@@ -0,0 +1,259 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ getAccessGrantDisplayStatus: vi.fn(),+ getAccessGrantDisplayStatusText: vi.fn(),+ getAccessGrantExpirationText: vi.fn(),+ getAccessGrantExpireTimeMs: vi.fn(),+ getAccessGrantStatusTagType: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/utils/accessGrant", () => ({+ getAccessGrantDisplayStatus: mocks.getAccessGrantDisplayStatus,+ getAccessGrantDisplayStatusText: mocks.getAccessGrantDisplayStatusText,+ getAccessGrantExpirationText: mocks.getAccessGrantExpirationText,+ getAccessGrantExpireTimeMs: mocks.getAccessGrantExpireTimeMs,+ getAccessGrantStatusTagType: mocks.getAccessGrantStatusTagType,+}));++// Stub Badge and Tooltip as simple pass-through+vi.mock("@/react/components/ui/badge", () => ({+ Badge: ({+ children,+ variant,+ }: {+ children: React.ReactNode;+ variant?: string;+ }) => (+ <span data-testid="badge" data-variant={variant}>+ {children}+ </span>+ ),+}));++vi.mock("@/react/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: React.ReactNode }) => (+ <span data-testid="tooltip">{children}</span>+ ),+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({+ children,+ onClick,+ "data-run-btn": runBtn,+ "data-re-request-btn": reRequestBtn,+ asChild: _asChild,+ ...props+ }: {+ children: React.ReactNode;+ onClick?: (e: React.MouseEvent) => void;+ "data-run-btn"?: boolean;+ "data-re-request-btn"?: boolean;+ asChild?: boolean;+ [key: string]: unknown;+ }) => (+ <button+ data-run-btn={runBtn ? "" : undefined}+ data-re-request-btn={reRequestBtn ? "" : undefined}+ onClick={onClick}+ {...props}+ >+ {children}+ </button>+ ),+}));++vi.mock("@/react/lib/utils", () => ({+ cn: (...args: string[]) => args.filter(Boolean).join(" "),+}));++type AccessGrantLike = {+ name: string;+ targets: string[];+ query: string;+ unmask: boolean;+ issue: string;+ status: number;+ expiration: { case: string; value?: unknown };+};++const makeGrant = (+ overrides: Partial<AccessGrantLike> = {}+): AccessGrantLike => ({+ name: "projects/proj1/accessGrants/grant1",+ targets: ["instances/inst1/databases/db1"],+ query: "SELECT * FROM users",+ unmask: false,+ issue: "",+ status: 2, // ACTIVE+ expiration: { case: "none" },+ ...overrides,+});++let AccessGrantItem: typeof import("./AccessGrantItem").AccessGrantItem;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () => {+ act(() => {+ root.unmount();+ });+ container.remove();+ },+ };+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });+ mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");+ mocks.getAccessGrantDisplayStatusText.mockReturnValue("Active");+ mocks.getAccessGrantExpirationText.mockReturnValue({ type: "never" });+ mocks.getAccessGrantExpireTimeMs.mockReturnValue(undefined);+ mocks.getAccessGrantStatusTagType.mockReturnValue("success");++ ({ AccessGrantItem } = await import("./AccessGrantItem"));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("AccessGrantItem", () => {+ test("renders status badge with correct label for ACTIVE status", () => {+ mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");+ mocks.getAccessGrantDisplayStatusText.mockReturnValue("Active");+ mocks.getAccessGrantStatusTagType.mockReturnValue("success");++ const grant = makeGrant();+ const onRun = vi.fn();+ const onRequest = vi.fn();++ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantItem+ grant={grant as never}+ onRun={onRun}+ onRequest={onRequest}+ />+ );+ render();++ const badge = container.querySelector("[data-testid='badge']");+ expect(badge).not.toBeNull();+ expect(badge!.textContent).toContain("Active");+ expect(badge!.getAttribute("data-variant")).toBe("success");+ unmount();+ });++ test("Run button shows only for ACTIVE status", () => {+ mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");+ const grant = makeGrant();+ const onRun = vi.fn();+ const onRequest = vi.fn();++ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantItem+ grant={grant as never}+ onRun={onRun}+ onRequest={onRequest}+ />+ );+ render();++ const runBtn = container.querySelector("[data-run-btn]");+ expect(runBtn).not.toBeNull();+ unmount();+ });++ test("Run button is absent for non-ACTIVE status", () => {+ mocks.getAccessGrantDisplayStatus.mockReturnValue("PENDING");+ const grant = makeGrant();+ const onRun = vi.fn();+ const onRequest = vi.fn();++ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantItem+ grant={grant as never}+ onRun={onRun}+ onRequest={onRequest}+ />+ );+ render();++ const runBtn = container.querySelector("[data-run-btn]");+ expect(runBtn).toBeNull();+ unmount();+ });++ test("Re-request button shows for REJECTED status", () => {+ mocks.getAccessGrantDisplayStatus.mockReturnValue("REJECTED");+ mocks.getAccessGrantDisplayStatusText.mockReturnValue("Rejected");+ mocks.getAccessGrantStatusTagType.mockReturnValue("error");++ const grant = makeGrant();+ const onRun = vi.fn();+ const onRequest = vi.fn();++ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantItem+ grant={grant as never}+ onRun={onRun}+ onRequest={onRequest}+ />+ );+ render();++ const reRequestBtn = container.querySelector("[data-re-request-btn]");+ expect(reRequestBtn).not.toBeNull();+ unmount();+ });++ test("Click Run → onRun(grant) called with the grant", async () => {+ mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");+ const grant = makeGrant();+ const onRun = vi.fn();+ const onRequest = vi.fn();++ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantItem+ grant={grant as never}+ onRun={onRun}+ onRequest={onRequest}+ />+ );+ render();++ const runBtn = container.querySelector("[data-run-btn]") as HTMLElement;+ expect(runBtn).not.toBeNull();++ await act(async () => {+ runBtn.click();+ });++ expect(onRun).toHaveBeenCalledTimes(1);+ expect(onRun).toHaveBeenCalledWith(grant);+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/AccessGrantItem.tsx b/frontend/src/react/components/sql-editor/AccessGrantItem.tsxnew file mode 100644index 0000000000..84ef2d8330--- /dev/null+++ b/frontend/src/react/components/sql-editor/AccessGrantItem.tsx@@ -0,0 +1,221 @@+import { useTranslation } from "react-i18next";+import { Badge } from "@/react/components/ui/badge";+import { Button } from "@/react/components/ui/button";+import { Tooltip } from "@/react/components/ui/tooltip";+import { cn } from "@/react/lib/utils";+import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import {+ getAccessGrantDisplayStatus,+ getAccessGrantDisplayStatusText,+ getAccessGrantExpirationText,+ getAccessGrantExpireTimeMs,+ getAccessGrantStatusTagType,+} from "@/utils/accessGrant";++// Map naive-ui tag type to shadcn Badge variant.+function mapTagTypeToBadgeVariant(+ tagType: "success" | "warning" | "error" | "default"+): "default" | "secondary" | "destructive" | "warning" | "success" {+ if (tagType === "success") return "success";+ if (tagType === "warning") return "warning";+ if (tagType === "error") return "destructive";+ return "default";+}++type Props = {+ readonly grant: AccessGrant;+ readonly highlight?: boolean;+ readonly issue?: Issue;+ readonly onRun: (grant: AccessGrant) => void;+ readonly onRequest: (grant: AccessGrant) => void;+};++export function AccessGrantItem({+ grant,+ highlight = false,+ issue,+ onRun,+ onRequest,+}: Props) {+ const { t } = useTranslation();++ const displayStatus = getAccessGrantDisplayStatus(grant, issue);+ const isActive = displayStatus === "ACTIVE";+ const isExpired = displayStatus === "EXPIRED";+ const isRejectedOrCanceled =+ displayStatus !== "ACTIVE" && displayStatus !== "PENDING";+ const statusLabel = getAccessGrantDisplayStatusText(grant, issue);+ const expireTimeMs = getAccessGrantExpireTimeMs(grant);++ const statusTagType = getAccessGrantStatusTagType(displayStatus);+ const badgeVariant = mapTagTypeToBadgeVariant(statusTagType);++ const expirationText = (() => {+ if (displayStatus !== "ACTIVE" && displayStatus !== "EXPIRED") return;+ const info = getAccessGrantExpirationText(grant);+ if (info.type === "never" || info.type === "duration") return;++ if (!isExpired && expireTimeMs !== undefined) {+ const diff = expireTimeMs - Date.now();+ const hours = Math.floor(diff / (1000 * 60 * 60));+ if (hours >= 24) {+ return t("sql-editor.expire-at", { time: info.value });+ }+ const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));+ const dur = hours > 0 ? `${hours}h${minutes}m` : `${minutes}m`;+ return t("sql-editor.expire-in", { time: dur });+ }+ return `${t("issue.access-grant.expired-at")} ${info.value}`;+ })();++ const allDatabaseNames = grant.targets.map((tgt) => {+ const match = tgt.match(/databases\/(.+)$/);+ return match ? match[1] : tgt;+ });+ const databaseNamesDisplay =+ allDatabaseNames.length <= 2+ ? allDatabaseNames.join(", ")+ : `${allDatabaseNames.slice(0, 2).join(", ")} ${t("sql-editor.and-n-more-databases", { n: allDatabaseNames.length - 2 })}`;++ const issueLink = grant.issue+ ? grant.issue.startsWith("/")+ ? grant.issue+ : `/${grant.issue}`+ : "";++ return (+ <div+ className={cn(+ "w-full p-2 gap-y-2 border-b flex flex-col justify-start items-start hover:bg-control-bg",+ highlight+ ? "bb-access-grant-highlight"+ : "transition-colors duration-1000"+ )}+ >+ <div className="w-full flex flex-row justify-between items-center gap-x-2">+ <div className="flex items-center gap-x-1">+ <Badge+ variant={badgeVariant}+ className="text-[10px] px-1.5 py-0 rounded-full"+ >+ {statusLabel}+ </Badge>+ {grant.unmask && (+ <Badge+ variant="default"+ className="text-[10px] px-1.5 py-0 rounded-full"+ >+ {t("sql-editor.grant-type-unmask")}+ </Badge>+ )}+ </div>+ {expirationText && (+ <span className="text-xs text-control-placeholder shrink-0 truncate">+ {expirationText}+ </span>+ )}+ </div>++ <Tooltip+ content={+ <pre className="max-w-lg whitespace-pre-wrap text-xs">+ {grant.query}+ </pre>+ }+ side="right"+ >+ <p+ className={cn(+ "max-w-full text-xs wrap-break-word whitespace-pre-wrap font-mono line-clamp-2",+ (isExpired || isRejectedOrCanceled) &&+ "line-through text-control-placeholder"+ )}+ >+ {grant.query}+ </p>+ </Tooltip>++ <div className="w-full flex flex-col gap-y-2">+ {allDatabaseNames.length <= 2 ? (+ <span className="text-xs text-control-placeholder truncate">+ {databaseNamesDisplay}+ </span>+ ) : (+ <Tooltip+ content={+ <div className="flex flex-col">+ {allDatabaseNames.map((n) => (+ <span key={n}>{n}</span>+ ))}+ </div>+ }+ side="right"+ >+ <span className="text-xs text-control-placeholder truncate">+ {databaseNamesDisplay}+ </span>+ </Tooltip>+ )}++ <div className="flex items-center justify-between gap-x-1">+ <div>+ {isActive && (+ <Button+ size="sm"+ variant="default"+ className="h-6 text-xs"+ data-run-btn+ onClick={(e) => {+ e.stopPropagation();+ onRun(grant);+ }}+ >+ {t("common.run")}+ </Button>+ )}+ </div>+ <div className="flex items-center gap-x-1">+ {isRejectedOrCanceled && (+ <Button+ variant="ghost"+ size="sm"+ className="h-6 text-xs"+ data-re-request-btn+ onClick={(e) => {+ e.stopPropagation();+ onRequest(grant);+ }}+ >+ {t("sql-editor.re-request")}+ </Button>+ )}+ {grant.issue && (+ <a+ href={issueLink}+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e) => e.stopPropagation()}+ className="inline-flex items-center justify-center h-6 text-xs px-2 rounded-xs hover:bg-control-bg text-control"+ >+ {t("sql-editor.view-issue")}+ </a>+ )}+ </div>+ </div>+ </div>++ {/* Highlight pulse animation styles */}+ <style>{`+ .bb-access-grant-highlight {+ animation: bb-access-grant-highlight-fade 3s ease-in-out;+ }+ @keyframes bb-access-grant-highlight-fade {+ 0% { background-color: rgb(219 234 254); }+ 60% { background-color: rgb(219 234 254); }+ 100% { background-color: transparent; }+ }+ `}</style>+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsxnew file mode 100644index 0000000000..34c3dfa46f--- /dev/null+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx@@ -0,0 +1,459 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useCurrentUserV1: vi.fn(),+ useSQLEditorStore: vi.fn(),+ useSQLEditorTabStore: vi.fn(),+ useSQLEditorUIStore: vi.fn(),+ pushNotification: vi.fn(),+ useDatabaseV1Store: vi.fn(),+ createAccessGrant: vi.fn(),+ routerResolve: vi.fn(() => ({ fullPath: "/projects/proj1/issues/123" })),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useCurrentUserV1: mocks.useCurrentUserV1,+ useSQLEditorStore: mocks.useSQLEditorStore,+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,+ useSQLEditorUIStore: mocks.useSQLEditorUIStore,+ pushNotification: mocks.pushNotification,+ useDatabaseV1Store: mocks.useDatabaseV1Store,+}));++vi.mock("@/connect", () => ({+ accessGrantServiceClientConnect: {+ createAccessGrant: mocks.createAccessGrant,+ },+}));++vi.mock("@/router", () => ({+ router: {+ resolve: mocks.routerResolve,+ },+}));++vi.mock("@/router/dashboard/projectV1", () => ({+ PROJECT_V1_ROUTE_ISSUE_DETAIL: "project.issue-detail",+}));++vi.mock("@/utils", () => ({+ extractDatabaseResourceName: vi.fn((name: string) => {+ const parts = name.split("/");+ return {+ databaseName: parts[parts.length - 1] ?? name,+ instance: parts[1] ?? "",+ };+ }),+ extractIssueUID: vi.fn((name: string) => name.split("/").pop() ?? "123"),+ extractProjectResourceName: vi.fn((name: string) => {+ const match = name.match(/projects\/(.+?)(?:\/|$)/);+ return match?.[1] ?? "";+ }),+}));++vi.mock("@bufbuild/protobuf", () => ({+ create: vi.fn((_schema: unknown, data: unknown) => data),+}));++vi.mock("@bufbuild/protobuf/wkt", () => ({+ DurationSchema: {},+ TimestampSchema: {},+}));++vi.mock("@/types/proto-es/v1/access_grant_service_pb", () => ({+ AccessGrant_Status: { PENDING: 1, ACTIVE: 2 },+ AccessGrantSchema: {},+ CreateAccessGrantRequestSchema: {},+}));++vi.mock("@/react/components/ui/sheet", () => ({+ Sheet: ({+ children,+ open,+ onOpenChange,+ }: {+ children: React.ReactNode;+ open: boolean;+ onOpenChange: (next: boolean) => void;+ }) => (+ <div+ data-testid="sheet"+ data-open={open}+ onClick={() => onOpenChange(false)}+ >+ {children}+ </div>+ ),+ SheetContent: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="sheet-content">{children}</div>+ ),+ SheetHeader: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="sheet-header">{children}</div>+ ),+ SheetTitle: ({ children }: { children: React.ReactNode }) => (+ <h2 data-testid="sheet-title">{children}</h2>+ ),+ SheetBody: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="sheet-body">{children}</div>+ ),+ SheetFooter: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="sheet-footer">{children}</div>+ ),+}));++vi.mock("@/react/components/ui/alert", () => ({+ Alert: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="alert">{children}</div>+ ),+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({+ children,+ onClick,+ disabled,+ "data-submit-btn": submitBtn,+ ...props+ }: {+ children: React.ReactNode;+ onClick?: () => void;+ disabled?: boolean;+ "data-submit-btn"?: boolean;+ [key: string]: unknown;+ }) => (+ <button+ data-submit-btn={submitBtn ? "" : undefined}+ disabled={disabled}+ onClick={onClick}+ {...props}+ >+ {children}+ </button>+ ),+}));++vi.mock("@/react/components/ui/combobox", () => ({+ Combobox: ({+ value,+ onChange,+ options,+ multiple,+ }: {+ value: string | string[];+ onChange: (val: string | string[]) => void;+ options: { value: string; label: string }[];+ multiple?: boolean;+ }) => (+ <select+ data-testid={multiple ? "multi-combobox" : "combobox"}+ multiple={multiple}+ value={multiple ? (value as string[]) : (value as string)}+ onChange={(e) => {+ if (multiple) {+ const selected = Array.from(e.target.selectedOptions).map(+ (o) => o.value+ );+ onChange(selected);+ } else {+ onChange(e.target.value);+ }+ }}+ >+ {options.map((opt) => (+ <option key={opt.value} value={opt.value}>+ {opt.label}+ </option>+ ))}+ </select>+ ),+}));++vi.mock("@/react/components/ui/expiration-picker", () => ({+ ExpirationPicker: ({+ value,+ onChange,+ }: {+ value?: string;+ onChange: (val: string | undefined) => void;+ }) => (+ <input+ data-testid="expiration-picker"+ type="datetime-local"+ value={value ?? ""}+ onChange={(e) => onChange(e.target.value || undefined)}+ />+ ),+}));++vi.mock("@/react/components/ui/textarea", () => ({+ Textarea: ({+ value,+ onChange,+ ...props+ }: {+ value: string;+ onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;+ [key: string]: unknown;+ }) => (+ <textarea+ data-testid="textarea"+ value={value}+ onChange={onChange}+ {...props}+ />+ ),+}));++vi.mock("@/react/components/monaco/MonacoEditor", () => ({+ MonacoEditor: ({+ content,+ onChange,+ }: {+ content: string;+ onChange?: (val: string) => void;+ }) => (+ <textarea+ data-testid="monaco-editor"+ value={content}+ onChange={(e) => onChange?.(e.target.value)}+ />+ ),+}));++let AccessGrantRequestDrawer: typeof import("./AccessGrantRequestDrawer").AccessGrantRequestDrawer;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () => {+ act(() => {+ root.unmount();+ });+ container.remove();+ },+ };+};++const setupMocks = () => {+ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });++ mocks.useCurrentUserV1.mockReturnValue({+ value: { email: "[email protected]" },+ });++ mocks.useSQLEditorStore.mockReturnValue({ project: "projects/proj1" });++ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: {+ connection: { database: "instances/inst1/databases/db1" },+ },+ });++ const uiStore = {+ asidePanelTab: "WORKSHEET",+ highlightAccessGrantName: undefined,+ };+ mocks.useSQLEditorUIStore.mockReturnValue(uiStore);++ mocks.useDatabaseV1Store.mockReturnValue({+ fetchDatabases: vi.fn().mockResolvedValue({ databases: [] }),+ });++ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+};++beforeEach(async () => {+ vi.clearAllMocks();+ setupMocks();++ // Mock window.open+ Object.defineProperty(window, "open", {+ value: vi.fn(),+ writable: true,+ });++ ({ AccessGrantRequestDrawer } = await import("./AccessGrantRequestDrawer"));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("AccessGrantRequestDrawer", () => {+ test("renders with pre-filled targets, query, unmask when passed as props", () => {+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantRequestDrawer+ targets={["instances/inst1/databases/mydb"]}+ query="SELECT id FROM orders"+ unmask={true}+ onClose={onClose}+ />+ );+ render();++ const monacoEditor = container.querySelector(+ "[data-testid='monaco-editor']"+ ) as HTMLTextAreaElement;+ expect(monacoEditor).not.toBeNull();+ expect(monacoEditor.value).toBe("SELECT id FROM orders");++ const checkbox = container.querySelector(+ "input[type='checkbox']"+ ) as HTMLInputElement;+ expect(checkbox).not.toBeNull();+ expect(checkbox.checked).toBe(true);++ unmount();+ });++ test("Submit button disabled when required fields missing", () => {+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantRequestDrawer onClose={onClose} />+ );+ render();++ // No targets, no query, no reason — submit should be disabled+ const submitBtn = container.querySelector(+ "[data-submit-btn]"+ ) as HTMLButtonElement;+ expect(submitBtn).not.toBeNull();+ expect(submitBtn.disabled).toBe(true);++ unmount();+ });++ test("Submit calls createAccessGrant with correct payload shape", async () => {+ const mockResponse = {+ status: 2, // ACTIVE+ issue: "",+ name: "projects/proj1/accessGrants/grant-new",+ };+ mocks.createAccessGrant.mockResolvedValue(mockResponse);++ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantRequestDrawer+ targets={["instances/inst1/databases/db1"]}+ query="SELECT * FROM t"+ onClose={onClose}+ />+ );+ render();++ // Fill in reason+ const textarea = container.querySelector(+ "[data-testid='textarea']"+ ) as HTMLTextAreaElement;+ await act(async () => {+ Object.defineProperty(textarea, "value", {+ writable: true,+ value: "test reason",+ });+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ const changeEvent = new Event("change", { bubbles: true });+ Object.defineProperty(changeEvent, "target", {+ writable: false,+ value: textarea,+ });+ textarea.dispatchEvent(changeEvent);+ });++ // Submit button should now be enabled (targets + query + reason filled)+ const submitBtn = container.querySelector(+ "[data-submit-btn]"+ ) as HTMLButtonElement;+ expect(submitBtn).not.toBeNull();++ // Manually trigger submit+ await act(async () => {+ submitBtn.click();+ });++ // createAccessGrant should have been called+ expect(mocks.createAccessGrant).toHaveBeenCalled();+ unmount();+ });++ test("On success ACTIVE without issue → sets asidePanelTab and highlightAccessGrantName", async () => {+ const uiStore = {+ asidePanelTab: "WORKSHEET",+ highlightAccessGrantName: undefined as string | undefined,+ };+ mocks.useSQLEditorUIStore.mockReturnValue(uiStore);++ const mockResponse = {+ status: 2, // ACTIVE+ issue: "",+ name: "projects/proj1/accessGrants/grant-xyz",+ };+ mocks.createAccessGrant.mockResolvedValue(mockResponse);++ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantRequestDrawer+ targets={["instances/inst1/databases/db1"]}+ query="SELECT * FROM t"+ onClose={onClose}+ />+ );+ render();++ // Fill reason+ const textarea = container.querySelector(+ "[data-testid='textarea']"+ ) as HTMLTextAreaElement;+ await act(async () => {+ Object.defineProperty(textarea, "value", {+ writable: true,+ value: "my reason",+ });+ const changeEvent = new Event("change", { bubbles: true });+ Object.defineProperty(changeEvent, "target", {+ writable: false,+ value: textarea,+ });+ textarea.dispatchEvent(changeEvent);+ });++ const submitBtn = container.querySelector(+ "[data-submit-btn]"+ ) as HTMLButtonElement;+ await act(async () => {+ submitBtn.click();+ });++ // After submit: check pushNotification was called+ expect(mocks.pushNotification).toHaveBeenCalledWith(+ expect.objectContaining({ style: "SUCCESS" })+ );+ expect(onClose).toHaveBeenCalled();+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsxnew file mode 100644index 0000000000..3e2c418ef1--- /dev/null+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx@@ -0,0 +1,357 @@+import { create } from "@bufbuild/protobuf";+import { DurationSchema, TimestampSchema } from "@bufbuild/protobuf/wkt";+import { Loader2 } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { accessGrantServiceClientConnect } from "@/connect";+import { MonacoEditor } from "@/react/components/monaco/MonacoEditor";+import { Alert } from "@/react/components/ui/alert";+import { Button } from "@/react/components/ui/button";+import { Combobox } from "@/react/components/ui/combobox";+import { ExpirationPicker } from "@/react/components/ui/expiration-picker";+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/react/components/ui/sheet";+import { Textarea } from "@/react/components/ui/textarea";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";+import {+ pushNotification,+ useCurrentUserV1,+ useDatabaseV1Store,+ useSQLEditorStore,+ useSQLEditorTabStore,+ useSQLEditorUIStore,+} from "@/store";+import {+ AccessGrant_Status,+ AccessGrantSchema,+ CreateAccessGrantRequestSchema,+} from "@/types/proto-es/v1/access_grant_service_pb";+import {+ extractDatabaseResourceName,+ extractIssueUID,+ extractProjectResourceName,+} from "@/utils";++// Multi-select database combobox+function MultiDatabaseSelect({+ value,+ projectName,+ onChange,+}: {+ value: string[];+ projectName: string;+ onChange: (val: string[]) => void;+}) {+ const { t } = useTranslation();+ const [databases, setDatabases] = useState<+ { name: string; displayName: string }[]+ >([]);++ const databaseStore = useDatabaseV1Store();++ useEffect(() => {+ databaseStore+ .fetchDatabases({+ parent: projectName,+ filter: { query: "" },+ pageSize: 100,+ silent: true,+ })+ .then((result) => {+ setDatabases(+ result.databases.map((db) => {+ const { databaseName } = extractDatabaseResourceName(db.name);+ return { name: db.name, displayName: databaseName };+ })+ );+ })+ .catch(() => {+ /* ignore */+ });+ }, [databaseStore, projectName]);++ return (+ <Combobox+ multiple={true}+ value={value}+ onChange={onChange}+ placeholder={t("database.select")}+ noResultsText={t("common.no-data")}+ options={databases.map((db) => ({+ value: db.name,+ label: db.displayName,+ }))}+ />+ );+}++interface Props {+ readonly targets?: string[];+ readonly query?: string;+ readonly unmask?: boolean;+ readonly onClose: () => void;+}++interface AccessGrantRequestDrawerInnerProps extends Props {+ readonly stableProps: Props;+}++function AccessGrantRequestDrawerInner({+ stableProps,+ onClose,+}: AccessGrantRequestDrawerInnerProps) {+ const { t } = useTranslation();+ const currentUser = useCurrentUserV1();+ const editorStore = useSQLEditorStore();+ const tabStore = useSQLEditorTabStore();+ const uiStore = useSQLEditorUIStore();++ const currentUserEmail = useVueState(() => currentUser.value.email);+ const project = useVueState(() => editorStore.project);++ const defaultTargets = useMemo(() => {+ if (stableProps.targets && stableProps.targets.length > 0) {+ return stableProps.targets;+ }+ const database = tabStore.currentTab?.connection?.database;+ return database ? [database] : [];+ }, [stableProps.targets, tabStore]);++ const [targets, setTargets] = useState<string[]>(defaultTargets);+ const [query, setQuery] = useState(stableProps.query ?? "");+ const [unmask, setUnmask] = useState(stableProps.unmask ?? false);+ const [duration, setDuration] = useState<number>(4);+ const [customExpireTime, setCustomExpireTime] = useState<string | undefined>(+ undefined+ );+ const [reason, setReason] = useState("");+ const [isRequesting, setIsRequesting] = useState(false);++ const autoCompleteContext = useMemo(() => {+ const db = targets[0];+ if (!db) return undefined;+ const { instance } = extractDatabaseResourceName(db);+ return { instance, database: db };+ }, [targets]);++ const durationOptions = useMemo(+ () => [+ { value: "1", label: t("sql-editor.duration-hours", { hours: 1 }) },+ { value: "4", label: t("sql-editor.duration-hours", { hours: 4 }) },+ { value: "24", label: t("sql-editor.duration-day", { days: 1 }) },+ { value: "168", label: t("sql-editor.duration-days", { days: 7 }) },+ { value: "-1", label: t("common.custom") },+ ],+ [t]+ );++ const today = new Date();+ const minDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}T00:00`;++ const allowSubmit = useMemo(() => {+ if (targets.length === 0) return false;+ if (!query.trim()) return false;+ if (!reason.trim()) return false;+ if (duration === -1 && !customExpireTime) return false;+ return true;+ }, [targets, query, reason, duration, customExpireTime]);++ const handleSubmit = async () => {+ if (isRequesting || !allowSubmit) return;+ setIsRequesting(true);+ try {+ const expiration =+ duration === -1 && customExpireTime+ ? (() => {+ const ms = new Date(customExpireTime).getTime();+ return {+ case: "expireTime" as const,+ value: create(TimestampSchema, {+ seconds: BigInt(Math.floor(ms / 1000)),+ nanos: (ms % 1000) * 1000000,+ }),+ };+ })()+ : {+ case: "ttl" as const,+ value: create(DurationSchema, {+ seconds: BigInt(duration * 3600),+ }),+ };++ const accessGrant = create(AccessGrantSchema, {+ creator: `users/${currentUserEmail}`,+ targets,+ query,+ unmask,+ reason,+ expiration,+ });++ const response = await accessGrantServiceClientConnect.createAccessGrant(+ create(CreateAccessGrantRequestSchema, {+ parent: project as string,+ accessGrant,+ })+ );++ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.created"),+ });++ if (response.status === AccessGrant_Status.PENDING && response.issue) {+ const route = router.resolve({+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,+ params: {+ projectId: extractProjectResourceName(response.issue),+ issueId: extractIssueUID(response.issue),+ },+ });+ window.open(route.fullPath, "_blank");+ } else {+ uiStore.asidePanelTab = "ACCESS";+ uiStore.highlightAccessGrantName = response.name;+ }+ onClose();+ } finally {+ setIsRequesting(false);+ }+ };++ return (+ <>+ <SheetHeader>+ <SheetTitle>{t("sql-editor.request-data-access")}</SheetTitle>+ </SheetHeader>+ <SheetBody>+ <div className="flex flex-col gap-y-6">+ {/* Databases */}+ <div className="flex flex-col gap-y-2">+ <div className="text-sm font-medium text-control">+ {t("common.databases")}+ <span className="text-error ml-0.5">*</span>+ </div>+ <MultiDatabaseSelect+ value={targets}+ projectName={project as string}+ onChange={setTargets}+ />+ </div>++ {/* Statement */}+ <div className="flex flex-col gap-y-2">+ <div className="text-sm font-medium text-control">+ {t("common.statement")}+ <span className="text-error ml-0.5">*</span>+ </div>+ <Alert variant="info">{t("sql-editor.only-select-allowed")}</Alert>+ <MonacoEditor+ className="border rounded-[3px] h-40"+ content={query}+ language="sql"+ autoCompleteContext={autoCompleteContext}+ onChange={setQuery}+ />+ </div>++ {/* Unmask */}+ <div className="flex flex-col gap-y-2">+ <div className="text-sm font-medium text-control">+ {t("sql-editor.grant-type-unmask")}+ </div>+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={unmask}+ onChange={(e) => setUnmask(e.target.checked)}+ className="accent-accent"+ />+ <span>{t("sql-editor.access-type-unmask")}</span>+ </label>+ </div>++ {/* Expiration */}+ <div className="flex flex-col gap-y-2">+ <div className="text-sm font-medium text-control">+ {t("common.expiration")}+ <span className="text-error ml-0.5">*</span>+ </div>+ <Combobox+ value={String(duration)}+ onChange={(val) => setDuration(Number(val))}+ options={durationOptions}+ />+ {duration === -1 && (+ <ExpirationPicker+ value={customExpireTime}+ onChange={setCustomExpireTime}+ minDate={minDate}+ />+ )}+ </div>++ {/* Reason */}+ <div className="flex flex-col gap-y-2">+ <div className="text-sm font-medium text-control">+ {t("common.reason")}+ <span className="text-error ml-0.5">*</span>+ </div>+ <Textarea+ value={reason}+ onChange={(e) => setReason(e.target.value)}+ rows={3}+ placeholder=""+ />+ </div>+ </div>+ </SheetBody>+ <SheetFooter>+ <Button variant="outline" onClick={onClose} disabled={isRequesting}>+ {t("common.cancel")}+ </Button>+ <Button+ variant="default"+ disabled={!allowSubmit || isRequesting}+ onClick={() => void handleSubmit()}+ data-submit-btn+ >+ {isRequesting && <Loader2 className="size-4 mr-1 animate-spin" />}+ {t("common.submit")}+ </Button>+ </SheetFooter>+ </>+ );+}++export function AccessGrantRequestDrawer({+ targets,+ query,+ unmask,+ onClose,+}: Props) {+ const propsRef = useRef({ targets, query, unmask, onClose });+ // Freeze props while drawer is open so inner form stays stable during close animation+ const stableProps = propsRef.current;++ return (+ <Sheet open={true} onOpenChange={(next) => !next && onClose()}>+ <SheetContent width="standard">+ <AccessGrantRequestDrawerInner+ key={`${targets?.join(",")}-${query}-${unmask}`}+ stableProps={stableProps}+ onClose={onClose}+ />+ </SheetContent>+ </Sheet>+ );+}diff --git a/frontend/src/react/components/sql-editor/AccessPane.test.tsx b/frontend/src/react/components/sql-editor/AccessPane.test.tsxnew file mode 100644index 0000000000..82ed8057d7--- /dev/null+++ b/frontend/src/react/components/sql-editor/AccessPane.test.tsx@@ -0,0 +1,389 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useProjectV1Store: vi.fn(),+ useSQLEditorStore: vi.fn(),+ useSQLEditorTabStore: vi.fn(),+ useSQLEditorUIStore: vi.fn(),+ useAccessGrantStore: vi.fn(),+ useIssueV1Store: vi.fn(),+ useDatabaseV1Store: vi.fn(),+ hasFeature: vi.fn(() => true),+ sqlEditorEventsEmit: vi.fn().mockResolvedValue(undefined),+ getDefaultPagination: vi.fn(() => 20),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useProjectV1Store: mocks.useProjectV1Store,+ useSQLEditorStore: mocks.useSQLEditorStore,+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,+ useSQLEditorUIStore: mocks.useSQLEditorUIStore,+ useAccessGrantStore: mocks.useAccessGrantStore,+ useIssueV1Store: mocks.useIssueV1Store,+ useDatabaseV1Store: mocks.useDatabaseV1Store,+ hasFeature: mocks.hasFeature,+}));++vi.mock("@/store/modules/accessGrant", () => ({}));++vi.mock("@/utils", () => ({+ getDefaultPagination: mocks.getDefaultPagination,+ getAccessSearchOptions: vi.fn(() => []),+}));++vi.mock("@/views/sql-editor/events", () => ({+ sqlEditorEvents: {+ emit: mocks.sqlEditorEventsEmit,+ },+}));++vi.mock("@/types/proto-es/v1/access_grant_service_pb", () => ({+ AccessGrant_Status: {+ ACTIVE: 2,+ PENDING: 1,+ REVOKED: 3,+ 0: "UNSPECIFIED",+ 1: "PENDING",+ 2: "ACTIVE",+ 3: "REVOKED",+ },+}));++vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({+ PlanFeature: { FEATURE_JIT: 5 },+}));++vi.mock("@/react/components/AdvancedSearch", () => ({+ AdvancedSearch: ({+ placeholder,+ onParamsChange,+ }: {+ placeholder?: string;+ onParamsChange: (p: unknown) => void;+ }) => (+ <input+ data-testid="advanced-search"+ placeholder={placeholder}+ onChange={() => onParamsChange({ query: "", scopes: [] })}+ />+ ),+}));++vi.mock("@/react/components/FeatureBadge", () => ({+ FeatureBadge: () => <span data-testid="feature-badge" />,+}));++vi.mock("@/react/components/PermissionGuard", () => ({+ PermissionGuard: ({+ children,+ }: {+ children: (props: { disabled: boolean }) => React.ReactNode;+ }) => <>{children({ disabled: false })}</>,+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({+ children,+ onClick,+ disabled,+ ...props+ }: {+ children: React.ReactNode;+ onClick?: () => void;+ disabled?: boolean;+ [key: string]: unknown;+ }) => (+ <button disabled={disabled} onClick={onClick} {...props}>+ {children}+ </button>+ ),+}));++vi.mock("./AccessGrantItem", () => ({+ AccessGrantItem: ({+ grant,+ onRun,+ onRequest,+ }: {+ grant: { name: string; query: string };+ onRun: (g: unknown) => void;+ onRequest: (g: unknown) => void;+ }) => (+ <div data-testid="access-grant-item" data-grant-name={grant.name}>+ <span>{grant.query}</span>+ <button data-run-btn onClick={() => onRun(grant)}>+ Run+ </button>+ <button data-request-btn onClick={() => onRequest(grant)}>+ Re-request+ </button>+ </div>+ ),+}));++vi.mock("./AccessGrantRequestDrawer", () => ({+ AccessGrantRequestDrawer: ({ onClose }: { onClose: () => void }) => (+ <div data-testid="access-grant-request-drawer">+ <button data-close-btn onClick={onClose}>+ Close+ </button>+ </div>+ ),+}));++type GrantLike = {+ name: string;+ query: string;+ targets: string[];+ unmask: boolean;+ issue: string;+ status: number;+ expiration: { case: string };+};++const makeGrant = (name: string): GrantLike => ({+ name,+ query: `SELECT * FROM ${name}`,+ targets: ["instances/inst1/databases/db1"],+ unmask: false,+ issue: "",+ status: 2,+ expiration: { case: "none" },+});++// Stub ResizeObserver — not provided by jsdom+globalThis.ResizeObserver = class ResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+};++let AccessPane: typeof import("./AccessPane").AccessPane;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () => {+ act(() => {+ root.unmount();+ });+ container.remove();+ },+ };+};++const setupDefaultMocks = () => {+ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });++ mocks.useProjectV1Store.mockReturnValue({+ getProjectByName: vi.fn(() => ({+ name: "projects/proj1",+ title: "Project 1",+ })),+ });++ mocks.useSQLEditorStore.mockReturnValue({ project: "projects/proj1" });+ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { connection: { database: "instances/inst1/databases/db1" } },+ });++ const uiStore = {+ asidePanelTab: "ACCESS",+ highlightAccessGrantName: undefined as string | undefined,+ };+ mocks.useSQLEditorUIStore.mockReturnValue(uiStore);++ mocks.useAccessGrantStore.mockReturnValue({+ searchMyAccessGrants: vi.fn().mockResolvedValue({+ accessGrants: [],+ nextPageToken: "",+ }),+ });++ mocks.useIssueV1Store.mockReturnValue({+ fetchIssueByName: vi.fn().mockResolvedValue({}),+ });++ mocks.useDatabaseV1Store.mockReturnValue({+ fetchDatabases: vi.fn().mockResolvedValue({ databases: [] }),+ getOrFetchDatabaseByName: vi.fn().mockResolvedValue({}),+ });++ mocks.hasFeature.mockReturnValue(true);+ mocks.getDefaultPagination.mockReturnValue(20);++ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+};++beforeEach(async () => {+ vi.clearAllMocks();+ setupDefaultMocks();++ ({ AccessPane } = await import("./AccessPane"));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("AccessPane", () => {+ test("empty state — shows no-access-requests text when no grants and not loading", async () => {+ const { container, render, unmount } = renderIntoContainer(<AccessPane />);+ render();++ // Wait for effects to settle+ await act(async () => {+ await new Promise((r) => setTimeout(r, 0));+ });++ expect(container.textContent).toContain("sql-editor.no-access-requests");+ unmount();+ });++ test("loading state — shows spinner while loading", async () => {+ let resolveSearch: (val: unknown) => void = () => {};+ mocks.useAccessGrantStore.mockReturnValue({+ searchMyAccessGrants: vi.fn(+ () =>+ new Promise((resolve) => {+ resolveSearch = resolve;+ })+ ),+ });++ const { container, render, unmount } = renderIntoContainer(<AccessPane />);+ render();++ // Should have spinner (Loader2 renders as svg with animate-spin)+ // Check loading indicator is present while fetch is pending+ const spinner = container.querySelector(".animate-spin");+ expect(spinner).not.toBeNull();++ // Resolve to avoid memory leaks+ await act(async () => {+ resolveSearch({ accessGrants: [], nextPageToken: "" });+ await new Promise((r) => setTimeout(r, 0));+ });++ unmount();+ });++ test("renders grants list when populated", async () => {+ const grants = [makeGrant("grant1"), makeGrant("grant2")];+ mocks.useAccessGrantStore.mockReturnValue({+ searchMyAccessGrants: vi.fn().mockResolvedValue({+ accessGrants: grants,+ nextPageToken: "",+ }),+ });+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ const { container, render, unmount } = renderIntoContainer(<AccessPane />);+ render();++ await act(async () => {+ await new Promise((r) => setTimeout(r, 0));+ });++ const items = container.querySelectorAll(+ "[data-testid='access-grant-item']"+ );+ expect(items.length).toBe(2);+ unmount();+ });++ test("click Request Access → drawer opens", async () => {+ const { container, render, unmount } = renderIntoContainer(<AccessPane />);+ render();++ await act(async () => {+ await new Promise((r) => setTimeout(r, 0));+ });++ // No drawer initially+ expect(+ container.querySelector("[data-testid='access-grant-request-drawer']")+ ).toBeNull();++ // Find and click the "request access" button+ const buttons = container.querySelectorAll("button");+ let requestBtn: HTMLButtonElement | null = null;+ for (const btn of Array.from(buttons)) {+ if (btn.textContent?.includes("sql-editor.request-access")) {+ requestBtn = btn;+ break;+ }+ }+ expect(requestBtn).not.toBeNull();++ await act(async () => {+ requestBtn!.click();+ });++ expect(+ container.querySelector("[data-testid='access-grant-request-drawer']")+ ).not.toBeNull();++ unmount();+ });++ test("click Run on a grant → emits execute-sql event", async () => {+ const grant = makeGrant("grant1");+ mocks.useAccessGrantStore.mockReturnValue({+ searchMyAccessGrants: vi.fn().mockResolvedValue({+ accessGrants: [grant],+ nextPageToken: "",+ }),+ });+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ const { container, render, unmount } = renderIntoContainer(<AccessPane />);+ render();++ await act(async () => {+ await new Promise((r) => setTimeout(r, 0));+ });++ const runBtn = container.querySelector(+ "[data-run-btn]"+ ) as HTMLButtonElement;+ expect(runBtn).not.toBeNull();++ await act(async () => {+ runBtn.click();+ });++ expect(mocks.sqlEditorEventsEmit).toHaveBeenCalledWith(+ "execute-sql",+ expect.objectContaining({+ statement: grant.query,+ })+ );+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/AccessPane.tsx b/frontend/src/react/components/sql-editor/AccessPane.tsxnew file mode 100644index 0000000000..d66e8e2cff--- /dev/null+++ b/frontend/src/react/components/sql-editor/AccessPane.tsx@@ -0,0 +1,369 @@+import { Loader2 } from "lucide-react";+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import type {+ ScopeOption,+ SearchParams,+} from "@/react/components/AdvancedSearch";+import { AdvancedSearch } from "@/react/components/AdvancedSearch";+import { FeatureBadge } from "@/react/components/FeatureBadge";+import { PermissionGuard } from "@/react/components/PermissionGuard";+import { Button } from "@/react/components/ui/button";+import { useVueState } from "@/react/hooks/useVueState";+import {+ hasFeature,+ useAccessGrantStore,+ useDatabaseV1Store,+ useIssueV1Store,+ useProjectV1Store,+ useSQLEditorStore,+ useSQLEditorUIStore,+} from "@/store";+import type { AccessFilter } from "@/store/modules/accessGrant";+import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";+import { AccessGrant_Status } from "@/types/proto-es/v1/access_grant_service_pb";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import type { AccessGrantFilterStatus } from "@/utils";+import { getDefaultPagination } from "@/utils";+import { sqlEditorEvents } from "@/views/sql-editor/events";+import { AccessGrantItem } from "./AccessGrantItem";+import { AccessGrantRequestDrawer } from "./AccessGrantRequestDrawer";++const PAGE_SIZE = getDefaultPagination();++const DEFAULT_SCOPES = [+ { id: "status", value: AccessGrant_Status[AccessGrant_Status.ACTIVE] },+ { id: "status", value: AccessGrant_Status[AccessGrant_Status.PENDING] },+];++export function AccessPane() {+ const { t } = useTranslation();++ const projectStore = useProjectV1Store();+ const editorStore = useSQLEditorStore();+ const accessGrantStore = useAccessGrantStore();+ const issueStore = useIssueV1Store();+ const databaseStore = useDatabaseV1Store();+ const uiStore = useSQLEditorUIStore();++ const [showDrawer, setShowDrawer] = useState(false);+ const [loading, setLoading] = useState(false);+ const [pendingCreate, setPendingCreate] = useState<AccessGrant | undefined>(+ undefined+ );+ const [accessGrantList, setAccessGrantList] = useState<AccessGrant[]>([]);+ const [nextPageToken, setNextPageToken] = useState("");+ const nextPageTokenRef = useRef(nextPageToken);+ nextPageTokenRef.current = nextPageToken;+ const [issueByGrantName, setIssueByGrantName] = useState<Map<string, Issue>>(+ new Map()+ );+ const [useSmallLayout, setUseSmallLayout] = useState(false);++ const containerRef = useRef<HTMLDivElement>(null);++ const [searchParams, setSearchParams] = useState<SearchParams>({+ query: "",+ scopes: DEFAULT_SCOPES,+ });++ const projectName = useVueState(() => editorStore.project);+ const highlightAccessGrantName = useVueState(+ () => uiStore.highlightAccessGrantName+ );++ const project = useMemo(() => {+ if (!projectName) return undefined;+ return projectStore.getProjectByName(projectName as string);+ }, [projectStore, projectName]);++ const hasJITFeature = useMemo(+ () => hasFeature(PlanFeature.FEATURE_JIT),+ // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list+ []+ );++ // Build scope options for AdvancedSearch (React-compatible, no Vue renderers)+ const scopeOptions = useMemo((): ScopeOption[] => {+ return [+ {+ id: "status",+ title: t("common.status"),+ description: t("sql-editor.access-search.scope.status.description"),+ allowMultiple: true,+ options: [+ {+ value: AccessGrant_Status[AccessGrant_Status.ACTIVE],+ keywords: ["active"],+ render: () => t("common.active"),+ },+ {+ value: AccessGrant_Status[AccessGrant_Status.PENDING],+ keywords: ["pending"],+ render: () => t("common.pending"),+ },+ {+ value: "EXPIRED",+ keywords: ["expired"],+ render: () => t("sql-editor.expired"),+ },+ {+ value: AccessGrant_Status[AccessGrant_Status.REVOKED],+ keywords: ["revoked"],+ render: () => t("common.revoked"),+ },+ ],+ },+ {+ id: "database",+ title: t("common.database"),+ description: t("sql-editor.access-search.scope.database.description"),+ onSearch: async (keyword: string) => {+ const parent = projectName as string | undefined;+ if (!parent) return [];+ const result = await databaseStore.fetchDatabases({+ parent,+ filter: { query: keyword },+ pageSize: getDefaultPagination(),+ silent: true,+ });+ return result.databases.map((db) => ({+ value: db.name,+ keywords: [db.name],+ }));+ },+ },+ ];+ }, [t, projectName, databaseStore]);++ // Build AccessFilter from React SearchParams+ const filter = useMemo((): AccessFilter => {+ const selectedStatuses = searchParams.scopes+ .filter((s) => s.id === "status")+ .map((s) => s.value) as AccessGrantFilterStatus[];++ const databaseScope = searchParams.scopes.find((s) => s.id === "database");++ const f: AccessFilter = {+ status: selectedStatuses,+ };+ if (databaseScope?.value) {+ f.target = databaseScope.value;+ }+ const queryText = searchParams.query.trim();+ if (queryText) {+ f.statement = queryText;+ }+ return f;+ }, [searchParams]);++ const fetchIssuesForPendingGrants = useCallback(+ async (grants: AccessGrant[]) => {+ const pendingWithIssue = grants.filter(+ (g) => g.status === AccessGrant_Status.PENDING && g.issue+ );+ const results = await Promise.all(+ pendingWithIssue.map(async (g) => {+ try {+ const issue = await issueStore.fetchIssueByName(g.issue, true);+ return { grantName: g.name, issue };+ } catch {+ return undefined;+ }+ })+ );+ setIssueByGrantName((prev) => {+ const next = new Map(prev);+ for (const r of results) {+ if (r) {+ next.set(r.grantName, r.issue);+ }+ }+ return next;+ });+ },+ [issueStore]+ );++ const fetchAccessGrants = useCallback(+ async (resetList = true) => {+ const parent = projectName as string | undefined;+ if (!parent) return;++ setLoading(true);+ try {+ const response = await accessGrantStore.searchMyAccessGrants({+ parent,+ filter,+ pageSize: PAGE_SIZE,+ pageToken: resetList ? undefined : nextPageTokenRef.current,+ });+ if (resetList) {+ setAccessGrantList(response.accessGrants);+ setIssueByGrantName(new Map());+ } else {+ setAccessGrantList((prev) => [...prev, ...response.accessGrants]);+ }+ setNextPageToken(response.nextPageToken);+ await fetchIssuesForPendingGrants(response.accessGrants);+ } finally {+ setLoading(false);+ }+ },+ // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list+ [projectName, filter, accessGrantStore, fetchIssuesForPendingGrants]+ );++ // Re-fetch when project or filter changes+ useEffect(() => {+ void fetchAccessGrants(true);+ // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list+ }, [projectName, filter]);++ // Re-fetch + clear highlight when highlightAccessGrantName changes+ useEffect(() => {+ const name = highlightAccessGrantName;+ if (!name) return;+ void fetchAccessGrants(true);+ const timer = setTimeout(() => {+ if (uiStore.highlightAccessGrantName === name) {+ uiStore.highlightAccessGrantName = undefined;+ }+ }, 3000);+ return () => clearTimeout(timer);+ // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list+ }, [highlightAccessGrantName]);++ // Responsive small layout detection+ useLayoutEffect(() => {+ const el = containerRef.current;+ if (!el) return;+ const observer = new ResizeObserver((entries) => {+ const width = entries[0]?.contentRect.width ?? 0;+ setUseSmallLayout(width > 0 && width < 250);+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ const handleDrawerClose = useCallback(() => {+ setShowDrawer(false);+ setPendingCreate(undefined);+ void fetchAccessGrants(true);+ }, [fetchAccessGrants]);++ const handleRequest = useCallback((grant: AccessGrant) => {+ setPendingCreate(grant);+ setShowDrawer(true);+ }, []);++ const handleRun = useCallback(+ async (grant: AccessGrant) => {+ const database = grant.targets[0] ?? "";+ const instanceName = database.replace(/\/databases\/.*$/, "");+ await databaseStore.getOrFetchDatabaseByName(database);+ await sqlEditorEvents.emit("execute-sql", {+ connection: { instance: instanceName, database },+ statement: grant.query,+ batchQueryContext: { databases: grant.targets },+ });+ },+ [databaseStore]+ );++ return (+ <div className="relative w-full h-full flex flex-col justify-start items-start gap-y-1">+ <div+ ref={containerRef}+ className="w-full px-1 flex flex-wrap items-center gap-x-2 gap-y-2"+ >+ <AdvancedSearch+ params={searchParams}+ scopeOptions={scopeOptions}+ placeholder={t("issue.advanced-search.filter")}+ onParamsChange={setSearchParams}+ />+ <PermissionGuard+ permissions={["bb.accessGrants.create"]}+ project={project}+ >+ {({ disabled }) => (+ <Button+ variant="outline"+ size="sm"+ style={{ width: useSmallLayout ? "100%" : "auto" }}+ disabled={!hasJITFeature || disabled}+ onClick={() => setShowDrawer(true)}+ className="ml-auto"+ >+ {!hasJITFeature && (+ <FeatureBadge+ clickable={false}+ feature={PlanFeature.FEATURE_JIT}+ className="mr-1"+ />+ )}+ {t("sql-editor.request-access")}+ </Button>+ )}+ </PermissionGuard>+ </div>++ <div className="w-full border-t" />++ <div className="w-full flex flex-col justify-start items-start overflow-y-auto">+ {accessGrantList.map((grant) => (+ <AccessGrantItem+ key={grant.name}+ grant={grant}+ highlight={grant.name === highlightAccessGrantName}+ issue={issueByGrantName.get(grant.name)}+ onRun={(g) => void handleRun(g)}+ onRequest={handleRequest}+ />+ ))}+ {nextPageToken && (+ <div className="w-full flex flex-col items-center my-2">+ <Button+ variant="ghost"+ size="sm"+ disabled={loading}+ onClick={() => void fetchAccessGrants(false)}+ >+ {loading && <Loader2 className="size-4 mr-1 animate-spin" />}+ <span className="textinfolabel">{t("common.load-more")}</span>+ </Button>+ </div>+ )}+ </div>++ {accessGrantList.length === 0 &&+ (loading ? (+ <div className="absolute inset-0 flex items-center justify-center bg-background/75">+ <Loader2 className="size-6 animate-spin text-accent" />+ </div>+ ) : (+ <div className="w-full flex items-center justify-center py-8 textinfolabel">+ {t("sql-editor.no-access-requests")}+ </div>+ ))}++ {showDrawer && (+ <AccessGrantRequestDrawer+ query={pendingCreate?.query}+ unmask={pendingCreate?.unmask}+ targets={pendingCreate?.targets}+ onClose={handleDrawerClose}+ />+ )}+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/HistoryPane.test.tsx b/frontend/src/react/components/sql-editor/HistoryPane.test.tsxnew file mode 100644index 0000000000..b62c1df74c--- /dev/null+++ b/frontend/src/react/components/sql-editor/HistoryPane.test.tsx@@ -0,0 +1,318 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useSQLEditorTabStore: vi.fn(),+ useSQLEditorStore: vi.fn(),+ useSQLEditorQueryHistoryStore: vi.fn(),+ pushNotification: vi.fn(),+ sqlEditorEventsEmit: vi.fn().mockResolvedValue(undefined),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,+ useSQLEditorStore: mocks.useSQLEditorStore,+ useSQLEditorQueryHistoryStore: mocks.useSQLEditorQueryHistoryStore,+ pushNotification: mocks.pushNotification,+}));++vi.mock("@/views/sql-editor/events", () => ({+ sqlEditorEvents: {+ emit: mocks.sqlEditorEventsEmit,+ },+}));++vi.mock("@/react/components/ui/search-input", () => ({+ SearchInput: ({+ value,+ onChange,+ placeholder,+ }: {+ value: string;+ onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;+ placeholder?: string;+ }) => (+ <input+ data-testid="search-input"+ value={value}+ onChange={onChange}+ placeholder={placeholder}+ />+ ),+}));++vi.mock("@/types", () => ({+ DEBOUNCE_SEARCH_DELAY: 300,+ getDateForPbTimestampProtoEs: vi.fn((ts: unknown) =>+ ts ? new Date("2024-01-15T10:30:00Z") : new Date(0)+ ),+}));++vi.mock("@/utils", () => ({+ getHighlightHTMLByKeyWords: vi.fn((s: string, _k: string) =>+ s.replace(/</g, "<").replace(/>/g, ">")+ ),+}));++vi.mock("dayjs", () => {+ const mockDayjs = vi.fn(() => ({+ format: vi.fn(() => "2024-01-15 10:30:00"),+ }));+ return { default: mockDayjs };+});++let HistoryPane: typeof import("./HistoryPane").HistoryPane;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () => {+ act(() => {+ root.unmount();+ });+ container.remove();+ },+ };+};++const makeHistory = (+ name: string,+ statement: string+): {+ name: string;+ statement: string;+ createTime: { seconds: bigint; nanos: number } | undefined;+} => ({+ name,+ statement,+ createTime: { seconds: BigInt(1705312200), nanos: 0 },+});++beforeEach(async () => {+ vi.clearAllMocks();++ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });++ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { connection: { database: "db/test" } },+ addTab: vi.fn(),+ });++ mocks.useSQLEditorStore.mockReturnValue({+ project: "projects/proj1",+ });++ mocks.useSQLEditorQueryHistoryStore.mockReturnValue({+ getQueryHistoryList: vi.fn(() => ({+ queryHistories: [],+ nextPageToken: "",+ })),+ fetchQueryHistoryList: vi.fn().mockResolvedValue({ queryHistories: [] }),+ resetPageToken: vi.fn(),+ });++ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ Object.defineProperty(navigator, "clipboard", {+ value: { writeText: vi.fn().mockResolvedValue(undefined) },+ configurable: true,+ writable: true,+ });++ ({ HistoryPane } = await import("./HistoryPane"));+});++afterEach(() => {+ document.body.innerHTML = "";+ vi.useRealTimers();+});++describe("HistoryPane", () => {+ test("empty state — shows no-history-found when empty list and not loading", () => {+ const queryHistoryStore = {+ getQueryHistoryList: vi.fn(() => ({+ queryHistories: [],+ nextPageToken: "",+ })),+ fetchQueryHistoryList: vi.fn().mockResolvedValue({ queryHistories: [] }),+ resetPageToken: vi.fn(),+ };+ mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);+ render();++ expect(container.textContent).toContain("sql-editor.no-history-found");+ unmount();+ });++ test("rendered history list — both entries visible via statement text", () => {+ const histories = [+ makeHistory("histories/h1", "SELECT * FROM users"),+ makeHistory("histories/h2", "SELECT id FROM orders"),+ ];+ const queryHistoryStore = {+ getQueryHistoryList: vi.fn(() => ({+ queryHistories: histories,+ nextPageToken: "",+ })),+ fetchQueryHistoryList: vi+ .fn()+ .mockResolvedValue({ queryHistories: histories }),+ resetPageToken: vi.fn(),+ };+ mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);+ render();++ expect(container.textContent).toContain("SELECT * FROM users");+ expect(container.textContent).toContain("SELECT id FROM orders");+ unmount();+ });++ test("debounced search — fetchQueryHistoryList called with statement after timer", async () => {+ vi.useFakeTimers();++ const fetchQueryHistoryList = vi+ .fn()+ .mockResolvedValue({ queryHistories: [] });+ const queryHistoryStore = {+ getQueryHistoryList: vi.fn(() => ({+ queryHistories: [],+ nextPageToken: "",+ })),+ fetchQueryHistoryList,+ resetPageToken: vi.fn(),+ };+ mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);+ render();++ // Find the search input and type+ const searchInput = container.querySelector(+ "[data-testid='search-input']"+ ) as HTMLInputElement;+ expect(searchInput).not.toBeNull();++ // Type into the search input by directly setting value and firing input event+ act(() => {+ Object.defineProperty(searchInput, "value", {+ writable: true,+ value: "SELECT",+ });+ const inputEvent = new Event("change", { bubbles: true });+ Object.defineProperty(inputEvent, "target", {+ writable: false,+ value: searchInput,+ });+ searchInput.dispatchEvent(inputEvent);+ });++ // Advance timers to trigger debounce+ await act(async () => {+ vi.advanceTimersByTime(300);+ });++ // fetchQueryHistoryList should have been called (initial load + after search)+ expect(fetchQueryHistoryList).toHaveBeenCalled();+ unmount();+ });++ test("click history row → emits append-editor-content event", async () => {+ const histories = [makeHistory("histories/h1", "SELECT * FROM users")];+ const queryHistoryStore = {+ getQueryHistoryList: vi.fn(() => ({+ queryHistories: histories,+ nextPageToken: "",+ })),+ fetchQueryHistoryList: vi+ .fn()+ .mockResolvedValue({ queryHistories: histories }),+ resetPageToken: vi.fn(),+ };+ mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);+ render();++ // Find history row (first div in the history list)+ const historyRow = container.querySelector(+ "[data-history-row]"+ ) as HTMLElement;+ expect(historyRow).not.toBeNull();++ await act(async () => {+ historyRow.click();+ });++ expect(mocks.sqlEditorEventsEmit).toHaveBeenCalledWith(+ "append-editor-content",+ { content: "SELECT * FROM users", select: true }+ );+ unmount();+ });++ test("click copy button → clipboard writeText and pushNotification called", async () => {+ const histories = [makeHistory("histories/h1", "SELECT * FROM users")];+ const queryHistoryStore = {+ getQueryHistoryList: vi.fn(() => ({+ queryHistories: histories,+ nextPageToken: "",+ })),+ fetchQueryHistoryList: vi+ .fn()+ .mockResolvedValue({ queryHistories: histories }),+ resetPageToken: vi.fn(),+ };+ mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ const { container, render, unmount } = renderIntoContainer(<HistoryPane />);+ render();++ const copyBtn = container.querySelector(+ "[data-copy-btn]"+ ) as HTMLButtonElement;+ expect(copyBtn).not.toBeNull();++ await act(async () => {+ copyBtn.click();+ });++ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "SELECT * FROM users"+ );+ expect(mocks.pushNotification).toHaveBeenCalledTimes(1);+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/HistoryPane.tsx b/frontend/src/react/components/sql-editor/HistoryPane.tsxnew file mode 100644index 0000000000..4a8191aca9--- /dev/null+++ b/frontend/src/react/components/sql-editor/HistoryPane.tsx@@ -0,0 +1,200 @@+import dayjs from "dayjs";+import { Copy, Loader2 } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { SearchInput } from "@/react/components/ui/search-input";+import { useVueState } from "@/react/hooks/useVueState";+import type { QueryHistoryFilter } from "@/store";+import {+ pushNotification,+ useSQLEditorQueryHistoryStore,+ useSQLEditorStore,+ useSQLEditorTabStore,+} from "@/store";+import { DEBOUNCE_SEARCH_DELAY, getDateForPbTimestampProtoEs } from "@/types";+import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";+import { getHighlightHTMLByKeyWords } from "@/utils";+import { sqlEditorEvents } from "@/views/sql-editor/events";++/**+ * React migration of frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue.+ * Displays the query history list with search, copy, and click-to-append features.+ */+export function HistoryPane() {+ const { t } = useTranslation();++ const tabStore = useSQLEditorTabStore();+ const editorStore = useSQLEditorStore();+ const queryHistoryStore = useSQLEditorQueryHistoryStore();++ const [searchText, setSearchText] = useState("");+ const [loading, setLoading] = useState(false);+ const searchTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);++ const currentTabDatabase = useVueState(+ () => tabStore.currentTab?.connection.database+ );+ const project = useVueState(() => editorStore.project);++ const historyQuery = useMemo<QueryHistoryFilter>(+ () => ({+ database: currentTabDatabase,+ project: project,+ statement: searchText,+ }),+ [currentTabDatabase, project, searchText]+ );++ const historyData = useVueState(() =>+ queryHistoryStore.getQueryHistoryList(historyQuery)+ );++ const fetchHistory = useCallback(async () => {+ setLoading(true);+ try {+ await queryHistoryStore.fetchQueryHistoryList(historyQuery);+ } finally {+ setLoading(false);+ }+ }, [queryHistoryStore, historyQuery]);++ // Debounced fetch on query change — only when list is empty (initial load / filter change)+ useEffect(() => {+ if (historyData.queryHistories.length === 0) {+ if (searchTimerRef.current) clearTimeout(searchTimerRef.current);+ searchTimerRef.current = setTimeout(fetchHistory, DEBOUNCE_SEARCH_DELAY);+ }+ return () => {+ if (searchTimerRef.current) clearTimeout(searchTimerRef.current);+ };+ // Intentionally only historyQuery in deps — fetchHistory is stable for the current query+ // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list+ }, [historyQuery]);++ const onSearchUpdate = useCallback(+ (next: string) => {+ queryHistoryStore.resetPageToken({ ...historyQuery, statement: next });+ setSearchText(next);+ },+ [queryHistoryStore, historyQuery]+ );++ const titleOfQueryHistory = (h: QueryHistory) =>+ dayjs(getDateForPbTimestampProtoEs(h.createTime)).format(+ "YYYY-MM-DD HH:mm:ss"+ );++ const handleHistoryClick = async (history: QueryHistory) => {+ const { statement } = history;+ if (tabStore.currentTab) {+ await sqlEditorEvents.emit("append-editor-content", {+ content: statement,+ select: true,+ });+ } else {+ tabStore.addTab(+ {+ title: `Query history at ${titleOfQueryHistory(history)}`,+ statement,+ },+ /* beside */ true+ );+ }+ };++ const handleCopy = async (statement: string) => {+ try {+ await navigator.clipboard.writeText(statement);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("sql-editor.url-copied-to-clipboard"),+ });+ } catch {+ // clipboard not available+ }+ };++ return (+ <div className="relative w-full h-full flex flex-col justify-start items-start">+ <div className="w-full px-1">+ <SearchInput+ value={searchText}+ onChange={(e) => onSearchUpdate(e.target.value)}+ placeholder={t("sql-editor.search-history-by-statement")}+ className="h-8"+ />+ </div>++ <div className="w-full flex flex-col justify-start items-start overflow-y-auto">+ {historyData.queryHistories.map((history) => (+ <div+ key={history.name}+ data-history-row+ className="w-full p-2 gap-y-1 border-b flex flex-col justify-start items-start cursor-pointer hover:bg-control-bg"+ onClick={() => {+ void handleHistoryClick(history);+ }}+ >+ <div className="w-full flex flex-row justify-between items-center">+ <div className="flex items-start gap-x-1">+ <span className="text-xs text-control-placeholder">+ {titleOfQueryHistory(history)}+ </span>+ </div>+ <Button+ variant="ghost"+ size="sm"+ className="h-6 w-6 p-0"+ data-copy-btn+ onClick={(e) => {+ e.stopPropagation();+ void handleCopy(history.statement);+ }}+ aria-label={t("common.copy")}+ >+ <Copy className="size-3.5" />+ </Button>+ </div>+ <p+ className="max-w-full text-xs wrap-break-word font-mono line-clamp-3"+ // biome-ignore lint/security/noDangerouslySetInnerHtml: utility returns pre-escaped HTML with highlight markup+ dangerouslySetInnerHTML={{+ __html: getHighlightHTMLByKeyWords(+ history.statement,+ searchText+ ),+ }}+ />+ </div>+ ))}++ {historyData.nextPageToken && (+ <div className="w-full flex flex-col items-center my-2">+ <Button+ variant="ghost"+ size="sm"+ disabled={loading}+ onClick={() => void fetchHistory()}+ >+ {loading && <Loader2 className="size-4 mr-1 animate-spin" />}+ <span className="textinfolabel">{t("common.load-more")}</span>+ </Button>+ </div>+ )}+ </div>++ {historyData.queryHistories.length === 0 &&+ (loading ? (+ <div className="absolute inset-0 flex items-center justify-center bg-background/75">+ <Loader2 className="size-6 animate-spin text-accent" />+ </div>+ ) : (+ <div className="w-full flex items-center justify-center py-8 textinfolabel">+ {t("sql-editor.no-history-found")}+ </div>+ ))}+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsxnew file mode 100644index 0000000000..1df3d1b26c--- /dev/null+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx@@ -0,0 +1,258 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useActuatorV1Store: vi.fn(),+ useCurrentUserV1: vi.fn(),+ useWorkSheetStore: vi.fn(),+ useSQLEditorTabStore: vi.fn(),+ pushNotification: vi.fn(),+ extractProjectResourceName: vi.fn(+ (name: string) => name.split("/")[1] ?? name+ ),+ extractWorksheetID: vi.fn((name: string) => name.split("/")[3] ?? name),+ routerResolve: vi.fn(() => ({ href: "/sql-editor/projects/proj1/sheets/1" })),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useActuatorV1Store: mocks.useActuatorV1Store,+ useCurrentUserV1: mocks.useCurrentUserV1,+ useWorkSheetStore: mocks.useWorkSheetStore,+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,+ pushNotification: mocks.pushNotification,+}));++vi.mock("@/utils", () => ({+ extractProjectResourceName: mocks.extractProjectResourceName,+ extractWorksheetID: mocks.extractWorksheetID,+}));++vi.mock("@/router", () => ({+ router: {+ resolve: mocks.routerResolve,+ },+}));++vi.mock("@/router/sqlEditor", () => ({+ SQL_EDITOR_WORKSHEET_MODULE: "sql-editor.worksheet",+}));++vi.mock("@/react/components/ui/popover", () => ({+ Popover: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="popover">{children}</div>+ ),+ PopoverTrigger: ({+ children,+ render: renderEl,+ }: {+ children?: React.ReactNode;+ render?: React.ReactElement;+ }) => (+ <div data-testid="popover-trigger">+ {renderEl ? renderEl : null}+ {children}+ </div>+ ),+ PopoverContent: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="popover-content">{children}</div>+ ),+}));++vi.mock("@/react/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++let SharePopoverBody: typeof import("./SharePopoverBody").SharePopoverBody;++const mockWorksheet = {+ name: "projects/proj1/worksheets/1",+ project: "projects/proj1",+ creator: "users/[email protected]",+ visibility: 3 /* PRIVATE */,+ title: "test sheet",+};++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () => {+ act(() => {+ root.unmount();+ });+ container.remove();+ },+ };+};++beforeEach(async () => {+ vi.clearAllMocks();++ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });++ mocks.useActuatorV1Store.mockReturnValue({+ serverInfo: { externalUrl: "https://example.com" },+ });+ mocks.useCurrentUserV1.mockReturnValue({+ value: { email: "[email protected]", name: "users/[email protected]" },+ });+ mocks.useWorkSheetStore.mockReturnValue({+ patchWorksheet: vi.fn().mockResolvedValue({}),+ });+ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { status: "CLEAN" },+ });++ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ // Mock clipboard+ Object.defineProperty(navigator, "clipboard", {+ value: { writeText: vi.fn().mockResolvedValue(undefined) },+ configurable: true,+ writable: true,+ });++ ({ SharePopoverBody } = await import("./SharePopoverBody"));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("SharePopoverBody", () => {+ test("renders Share title and link input", () => {+ const { container, render, unmount } = renderIntoContainer(+ <SharePopoverBody worksheet={mockWorksheet as never} />+ );+ render();+ expect(container.textContent).toContain("common.share");+ // Should show an input with the link+ expect(container.querySelector("input")).not.toBeNull();+ unmount();+ });++ test("shows 3 visibility options when selector is opened", () => {+ const { container, render, unmount } = renderIntoContainer(+ <SharePopoverBody worksheet={mockWorksheet as never} />+ );+ render();+ // The popover-content should contain 3 options+ const popoverContent = container.querySelector(+ "[data-testid='popover-content']"+ );+ expect(popoverContent).not.toBeNull();+ // 3 option rows each with cursor-pointer class+ const optionRows =+ popoverContent?.querySelectorAll("[data-option-row]") ?? [];+ expect(optionRows.length).toBe(3);+ unmount();+ });++ test("visibility selector disabled when user is not creator", () => {+ mocks.useCurrentUserV1.mockReturnValue({+ value: { email: "[email protected]", name: "users/[email protected]" },+ });+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ const { container, render, unmount } = renderIntoContainer(+ <SharePopoverBody worksheet={mockWorksheet as never} />+ );+ render();+ // Trigger should have disabled styling+ const trigger = container.querySelector("[data-access-trigger]");+ expect(trigger?.getAttribute("data-disabled")).toBe("true");+ unmount();+ });++ test("handleChangeAccess calls patchWorksheet and pushNotification and onUpdated", async () => {+ const onUpdated = vi.fn();+ const patchWorksheet = vi.fn().mockResolvedValue({});+ mocks.useWorkSheetStore.mockReturnValue({ patchWorksheet });++ const { container, render, unmount } = renderIntoContainer(+ <SharePopoverBody+ worksheet={mockWorksheet as never}+ onUpdated={onUpdated}+ />+ );+ render();++ const popoverContent = container.querySelector(+ "[data-testid='popover-content']"+ );+ const optionRows = popoverContent?.querySelectorAll("[data-option-row]");+ expect(optionRows?.length).toBeGreaterThanOrEqual(1);++ // Click second option (Project Read)+ await act(async () => {+ (optionRows?.[1] as HTMLElement)?.click();+ });++ expect(patchWorksheet).toHaveBeenCalledTimes(1);+ expect(mocks.pushNotification).toHaveBeenCalledTimes(1);+ expect(onUpdated).toHaveBeenCalledTimes(1);+ unmount();+ });++ test("copy button writes to clipboard and pushes notification", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <SharePopoverBody worksheet={mockWorksheet as never} />+ );+ render();++ const copyBtn = container.querySelector(+ "[data-copy-btn]"+ ) as HTMLButtonElement;+ expect(copyBtn).not.toBeNull();++ await act(async () => {+ copyBtn.click();+ });++ expect(navigator.clipboard.writeText).toHaveBeenCalled();+ expect(mocks.pushNotification).toHaveBeenCalledTimes(1);+ unmount();+ });++ test("copy button disabled when currentTab status is not CLEAN", () => {+ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { status: "DIRTY" },+ });+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ const { container, render, unmount } = renderIntoContainer(+ <SharePopoverBody worksheet={mockWorksheet as never} />+ );+ render();++ const copyBtn = container.querySelector(+ "[data-copy-btn]"+ ) as HTMLButtonElement;+ expect(copyBtn).not.toBeNull();+ expect(copyBtn.disabled).toBe(true);+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.tsxnew file mode 100644index 0000000000..8f5a3b33bc--- /dev/null+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.tsx@@ -0,0 +1,253 @@+import {+ Check,+ ChevronDown,+ Copy,+ Link2,+ LockKeyhole,+ Users,+} from "lucide-react";+import { useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/react/components/ui/popover";+import { useVueState } from "@/react/hooks/useVueState";+import { cn } from "@/react/lib/utils";+import { router } from "@/router";+import { SQL_EDITOR_WORKSHEET_MODULE } from "@/router/sqlEditor";+import {+ pushNotification,+ useActuatorV1Store,+ useCurrentUserV1,+ useSQLEditorTabStore,+ useWorkSheetStore,+} from "@/store";+import type { Worksheet } from "@/types/proto-es/v1/worksheet_service_pb";+import { Worksheet_Visibility } from "@/types/proto-es/v1/worksheet_service_pb";+import { extractProjectResourceName, extractWorksheetID } from "@/utils";++type AccessOption = {+ label: string;+ description: string;+ value: Worksheet_Visibility;+ icon: React.ReactNode;+};++type Props = {+ readonly worksheet?: Worksheet;+ readonly onUpdated?: () => void;+};++/**+ * Replaces frontend/src/views/sql-editor/EditorCommon/SharePopover.vue.+ * Renders the share popover body content: visibility selector + shareable link.+ */+export function SharePopoverBody({ worksheet, onUpdated }: Props) {+ const { t } = useTranslation();+ const actuatorStore = useActuatorV1Store();+ const currentUserStore = useCurrentUserV1();+ const worksheetStore = useWorkSheetStore();+ const tabStore = useSQLEditorTabStore();++ const workspaceExternalURL = useVueState(+ () => actuatorStore.serverInfo?.externalUrl+ );+ const currentUser = useVueState(() => currentUserStore.value);+ const tabStatus = useVueState(() => tabStore.currentTab?.status);++ const accessOptions = useMemo<AccessOption[]>(+ () => [+ {+ label: t("sql-editor.private"),+ description: t("sql-editor.private-desc"),+ value: Worksheet_Visibility.PRIVATE,+ icon: <LockKeyhole className="size-5" />,+ },+ {+ label: t("sql-editor.project-read"),+ description: t("sql-editor.project-read-desc"),+ value: Worksheet_Visibility.PROJECT_READ,+ icon: <Users className="size-5" />,+ },+ {+ label: t("sql-editor.project-write"),+ description: t("sql-editor.project-write-desc"),+ value: Worksheet_Visibility.PROJECT_WRITE,+ icon: <Users className="size-5" />,+ },+ ],+ [t]+ );++ const allowChangeAccess = useMemo(() => {+ if (!worksheet || !currentUser) return false;+ return worksheet.creator === `users/${currentUser.email}`;+ }, [worksheet, currentUser]);++ const [currentAccess, setCurrentAccess] = useState<AccessOption>(+ () => accessOptions[0]+ );++ const [selectorOpen, setSelectorOpen] = useState(false);++ // Sync currentAccess from worksheet.visibility when worksheet changes+ useEffect(() => {+ if (!worksheet) return;+ const idx = accessOptions.findIndex(+ (opt) => opt.value === worksheet.visibility+ );+ setCurrentAccess(idx !== -1 ? accessOptions[idx] : accessOptions[0]);+ }, [worksheet, accessOptions]);++ const sharedTabLink = useMemo(() => {+ if (!worksheet) return "";+ const route = router.resolve({+ name: SQL_EDITOR_WORKSHEET_MODULE,+ params: {+ project: extractProjectResourceName(worksheet.project),+ sheet: extractWorksheetID(worksheet.name),+ },+ });+ return new URL(route.href, workspaceExternalURL || window.location.origin)+ .href;+ }, [worksheet, workspaceExternalURL]);++ const handleChangeAccess = async (option: AccessOption) => {+ if (!allowChangeAccess || !worksheet) {+ setSelectorOpen(false);+ return;+ }+ setCurrentAccess(option);+ await worksheetStore.patchWorksheet(+ { ...worksheet, visibility: option.value },+ ["visibility"]+ );++ try {+ await navigator.clipboard.writeText(sharedTabLink);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("sql-editor.url-copied-to-clipboard"),+ });+ } catch {+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ }++ onUpdated?.();+ setSelectorOpen(false);+ };++ const handleCopyLink = async () => {+ try {+ await navigator.clipboard.writeText(sharedTabLink);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("sql-editor.url-copied-to-clipboard"),+ });+ } catch {+ // clipboard not available+ }+ };++ return (+ <div className="w-96 p-2 flex flex-col gap-y-4">+ {/* Header: Share title + visibility selector */}+ <section className="w-full flex flex-row justify-between items-center">+ <div className="pr-4">+ <h2 className="text-lg font-semibold">{t("common.share")}</h2>+ </div>+ <Popover open={selectorOpen} onOpenChange={setSelectorOpen}>+ <PopoverTrigger+ render={+ <div+ data-access-trigger+ data-disabled={!allowChangeAccess ? "true" : "false"}+ className={cn(+ "flex items-center",+ allowChangeAccess ? "cursor-pointer" : "cursor-not-allowed"+ )}+ />+ }+ >+ <span className="pr-2">{t("sql-editor.link-access")}:</span>+ <div+ className={cn(+ "border flex flex-row justify-start items-center px-2 py-1 rounded-sm",+ allowChangeAccess+ ? "hover:border-accent"+ : "border-gray-200 text-gray-400"+ )}+ >+ <strong>{currentAccess.label}</strong>+ <ChevronDown className="size-4 ml-1" />+ </div>+ </PopoverTrigger>+ <PopoverContent side="bottom" align="end" className="w-80 p-2">+ <div className="flex flex-col gap-y-2">+ {accessOptions.map((option) => (+ <div+ key={option.value}+ data-option-row+ className={cn(+ "p-2 rounded-xs flex justify-between",+ allowChangeAccess && "cursor-pointer hover:bg-gray-200",+ option.value === currentAccess.value && "bg-gray-200"+ )}+ onClick={() => handleChangeAccess(option)}+ >+ <div>+ <div className="flex gap-x-2 items-center">+ {option.icon}+ <h2 className="text-md flex">{option.label}</h2>+ </div>+ <span className="text-xs textinfolabel">+ {option.description}+ </span>+ </div>+ {option.value === currentAccess.value && (+ <div className="flex items-center">+ <Check className="size-5" />+ </div>+ )}+ </div>+ ))}+ </div>+ </PopoverContent>+ </Popover>+ </section>++ {/* Link input + copy button */}+ <div className="flex items-center gap-x-0">+ {/* Link icon prefix */}+ <div className="flex items-center justify-center px-2 py-1 border border-r-0 border-control-border bg-control-bg rounded-l-xs h-8">+ <Link2 className="size-5" />+ </div>+ {/* URL input */}+ <input+ type="text"+ readOnly+ value={sharedTabLink}+ className="flex-1 min-w-0 px-2 py-1 border border-control-border bg-control-bg text-control text-sm h-8 focus:outline-none"+ />+ {/* Copy button */}+ <button+ type="button"+ data-copy-btn+ disabled={tabStatus !== "CLEAN"}+ onClick={handleCopyLink}+ className="flex items-center justify-center px-2 py-1 border border-l-0 border-control-border bg-control-bg rounded-r-xs h-8 text-control-light hover:text-main disabled:opacity-50 disabled:cursor-not-allowed"+ >+ <Copy className="size-4" />+ </button>+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/ui/layer.ts b/frontend/src/react/components/ui/layer.tsindex 2633da04da..0bf6cceb31 100644--- a/frontend/src/react/components/ui/layer.ts+++ b/frontend/src/react/components/ui/layer.ts@@ -7,10 +7,14 @@ export const LAYER_ROOT_ID = {} as const;export const LAYER_Z_INDEX = {- overlay: 50,- agent: 60,- // Legacy Naive overlays start at 2000 and notifications/messages go higher,- // so forced re-auth must sit above that during the Vue->React migration.+ // Legacy naive-ui popovers sit at ~2000 during the Vue->React migration.+ // React overlays mounted inside Vue popovers (e.g. a nested React Popover+ // inside a naive-ui share popover) must sit above their Vue ancestor.+ // 2500 keeps React overlays above naive-ui popovers but below naive-ui+ // modals (3000) and notifications (5000).+ overlay: 2500,+ agent: 2600,+ // Forced re-auth must sit above naive-ui notifications/messages.critical: 7000,} as const;diff --git a/frontend/src/react/hooks/useSQLEditorEvent.test.tsx b/frontend/src/react/hooks/useSQLEditorEvent.test.tsxnew file mode 100644index 0000000000..dcd0761625--- /dev/null+++ b/frontend/src/react/hooks/useSQLEditorEvent.test.tsx@@ -0,0 +1,99 @@+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, test, vi } from "vitest";+import { sqlEditorEvents } from "@/views/sql-editor/events";+import { useSQLEditorEvent } from "./useSQLEditorEvent";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++describe("useSQLEditorEvent", () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ root = undefined;+ container = undefined;+ document.body.innerHTML = "";+ });++ test("handler called when event emitted after subscribe", async () => {+ const handler = vi.fn();+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);++ function Harness() {+ useSQLEditorEvent("format-content", handler);+ return null;+ }++ await act(async () => {+ root!.render(<Harness />);+ });++ await act(async () => {+ await sqlEditorEvents.emit("format-content", undefined);+ });++ expect(handler).toHaveBeenCalledTimes(1);+ });++ test("handler NOT called after component unmounts (unsubscribe works)", async () => {+ const handler = vi.fn();+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);++ function Harness() {+ useSQLEditorEvent("format-content", handler);+ return null;+ }++ await act(async () => {+ root!.render(<Harness />);+ });++ await act(async () => {+ root!.unmount();+ });+ root = undefined;++ await sqlEditorEvents.emit("format-content", undefined);++ expect(handler).not.toHaveBeenCalled();+ });++ test("handler ref updates: rerender with new handler, emit, latest handler fires", async () => {+ const handler1 = vi.fn();+ const handler2 = vi.fn();+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);++ function Harness({ onEvent }: { onEvent: () => void }) {+ useSQLEditorEvent("format-content", onEvent);+ return null;+ }++ await act(async () => {+ root!.render(<Harness onEvent={handler1} />);+ });++ // Rerender with new handler+ await act(async () => {+ root!.render(<Harness onEvent={handler2} />);+ });++ await act(async () => {+ await sqlEditorEvents.emit("format-content", undefined);+ });++ expect(handler1).not.toHaveBeenCalled();+ expect(handler2).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/react/hooks/useSQLEditorEvent.ts b/frontend/src/react/hooks/useSQLEditorEvent.tsnew file mode 100644index 0000000000..d759794a0e--- /dev/null+++ b/frontend/src/react/hooks/useSQLEditorEvent.ts@@ -0,0 +1,20 @@+import { useEffect, useRef } from "react";+import {+ type SQLEditorEvents,+ sqlEditorEvents,+} from "@/views/sql-editor/events";++export function useSQLEditorEvent<E extends keyof SQLEditorEvents>(+ event: E,+ handler: (data: SQLEditorEvents[E]) => void+): void {+ const handlerRef = useRef(handler);+ handlerRef.current = handler;++ useEffect(() => {+ const unsubscribe = sqlEditorEvents.on(event, (data) => {+ handlerRef.current(data as SQLEditorEvents[E]);+ });+ return unsubscribe;+ }, [event]);+}diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex edfa089594..0da46ee41a 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -360,6 +360,7 @@"sensitive-placeholder": "Sensitive - write only","setting": "Setting","settings": "Settings",+ "share": "Share","sign-in": "Sign in","sign-in-as-admin": "Sign in as administrator","sign-up": "Sign up",@@ -2305,6 +2306,16 @@},"sql-editor": {"access-grants": "Access Grants",+ "access-search": {+ "scope": {+ "database": {+ "description": "Filter by database"+ },+ "status": {+ "description": "Search by the access grant status"+ }+ }+ },"access-type-unmask": "See unmasked sensitive data","activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?",@@ -2312,31 +2323,52 @@"admin-mode": {"self": "Admin mode"},+ "and-n-more-databases": "and {{n}} more databases","batch-query": {"batch": "Batch"},"connect-to-a-database": "Connect to database",+ "duration-day": "{{days}} day",+ "duration-days": "{{days}} days",+ "duration-hours": "{{hours}} hour | {{hours}} hours",+ "expire-at": "Expire at {{time}}",+ "expire-in": "Expire in {{time}}","expired": "Expired","format-sql": "Format SQL","grant-type-unmask": "Unmask","jit": "Just-In-Time Access",+ "link-access": "Link access",+ "no-access-requests": "No access requests",+ "no-history-found": "No history found",+ "only-select-allowed": "Only read-only statements are allowed to execute.",+ "private": "Private",+ "private-desc": "Only you can access this sheet",+ "project-read": "Project read",+ "project-read-desc": "Both sheet owner and users with \"bb.worksheets.manage\" permission can read/write, other project users with \"bb.worksheets.get\" permission can read",+ "project-write": "Project write",+ "project-write-desc": "Both sheet owner and project users with \"bb.worksheets.get\" permission can read/write","query-context": {"admin-data-source-is-disallowed-to-query": "Admin data source is disallowed to query."},+ "re-request": "Re-request","redis-command": {"all-nodes": "All nodes","only-for-cluster": "Only available for cluster connection","self": "Run redis command on","single-node": "Single node"},+ "request-access": "Request Access",+ "request-data-access": "Request Data Access","result-limit": {"self": "Result limit"},"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "search-history-by-statement": "Search by statement","select-a-database-to-start": "Select a database to start","self": "SQL Editor","unmask-warning": "The query result may include unmasked sensitive data.",+ "url-copied-to-clipboard": "The URL is copied to your clipboard","view-issue": "View Issue","web-socket": {"errors": {diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex c9b184875d..feebbb0555 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -266,7 +266,7 @@"environment-name": "Nombre del entorno","environments": "Entornos","error": "Error",- "expiration": "Expiration",+ "expiration": "Expiración","export": "Exportar","failed": "Error","file-selector": {@@ -322,7 +322,7 @@"project": "Proyecto","projects": "Proyectos","read-only": "Solo lectura",- "reason": "Reason",+ "reason": "Razón","regenerate": "Regenerar","reject": "Reject","rejected": "Rechazado",@@ -360,6 +360,7 @@"sensitive-placeholder": "Sensible - solo escritura","setting": "Configuración","settings": "Configuraciones",+ "share": "Compartir","sign-in": "Iniciar sesión","sign-in-as-admin": "Iniciar sesión como administrador","sign-up": "Registrarse",@@ -2305,6 +2306,16 @@},"sql-editor": {"access-grants": "Access Grants",+ "access-search": {+ "scope": {+ "database": {+ "description": "Filtrar por base de datos"+ },+ "status": {+ "description": "Buscar por el estado de la concesión de acceso"+ }+ }+ },"access-type-unmask": "See unmasked sensitive data","activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?",@@ -2312,31 +2323,52 @@"admin-mode": {"self": "Modo administrador"},+ "and-n-more-databases": "and {{n}} more databases","batch-query": {"batch": "Lote"},"connect-to-a-database": "Conectar a base de datos",+ "duration-day": "{{days}} day",+ "duration-days": "{{days}} days",+ "duration-hours": "{{hours}} hour | {{hours}} hours",+ "expire-at": "Expire at {{time}}",+ "expire-in": "Expire in {{time}}","expired": "Expired","format-sql": "Format SQL","grant-type-unmask": "Unmask","jit": "Just-In-Time Access",+ "link-access": "Acceso al enlace",+ "no-access-requests": "No access requests",+ "no-history-found": "No se encontró historial",+ "only-select-allowed": "Solo se permiten ejecutar declaraciones de solo lectura.",+ "private": "Privado",+ "private-desc": "Solo tú puedes acceder a esta hoja",+ "project-read": "Lectura del proyecto",+ "project-read-desc": "Tanto el propietario de la hoja como los usuarios con permiso \"bb.worksheets.manage\" pueden leer/escribir, otros usuarios del proyecto con permiso \"bb.worksheets.get\" pueden leer",+ "project-write": "Escritura del proyecto",+ "project-write-desc": "Tanto el propietario de la hoja como los usuarios del proyecto con permiso \"bb.worksheets.get\" pueden leer/escribir","query-context": {"admin-data-source-is-disallowed-to-query": "No se permite realizar consultas a la fuente de datos del administrador."},+ "re-request": "Volver a solicitar","redis-command": {"all-nodes": "Todos los nodos","only-for-cluster": "Sólo disponible para conexión de clúster","self": "Ejecute el comando redis en","single-node": "Nodo único"},+ "request-access": "Request Access",+ "request-data-access": "Request Data Access","result-limit": {"self": "Límite de resultados"},"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "search-history-by-statement": "Búsqueda por enunciado","select-a-database-to-start": "Seleccione una base de datos para comenzar","self": "Editor de SQL","unmask-warning": "The query result may include unmasked sensitive data.",+ "url-copied-to-clipboard": "La URL se copia al portapapeles.","view-issue": "View Issue","web-socket": {"errors": {diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 54d1069b3e..f80fb93371 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -266,7 +266,7 @@"environment-name": "環境名","environments": "環境","error": "間違い",- "expiration": "Expiration",+ "expiration": "有効期限","export": "エクスポート","failed": "失敗","file-selector": {@@ -322,7 +322,7 @@"project": "プロジェクト","projects": "プロジェクト","read-only": "読み取り専用",- "reason": "Reason",+ "reason": "理由","regenerate": "再生する","reject": "Reject","rejected": "却下",@@ -360,6 +360,7 @@"sensitive-placeholder": "機密データ - 書き込みのみ","setting": "設定","settings": "設定",+ "share": "共有","sign-in": "ログイン","sign-in-as-admin": "管理者としてサインイン","sign-up": "登録する",@@ -2305,6 +2306,16 @@},"sql-editor": {"access-grants": "Access Grants",+ "access-search": {+ "scope": {+ "database": {+ "description": "データベースでフィルター"+ },+ "status": {+ "description": "アクセス許可のステータスで検索"+ }+ }+ },"access-type-unmask": "See unmasked sensitive data","activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?",@@ -2312,31 +2323,52 @@"admin-mode": {"self": "管理者モード"},+ "and-n-more-databases": "and {{n}} more databases","batch-query": {"batch": "バッチ"},"connect-to-a-database": "データベースに接続",+ "duration-day": "{{days}} day",+ "duration-days": "{{days}} days",+ "duration-hours": "{{hours}} hour | {{hours}} hours",+ "expire-at": "Expire at {{time}}",+ "expire-in": "Expire in {{time}}","expired": "Expired","format-sql": "Format SQL","grant-type-unmask": "Unmask","jit": "Just-In-Time Access",+ "link-access": "リンクアクセス",+ "no-access-requests": "No access requests",+ "no-history-found": "まだ履歴がありません",+ "only-select-allowed": "読み取り専用ステートメントのみが実行を許可されます",+ "private": "プライベート",+ "private-desc": "このシートにアクセスできるのはあなただけです",+ "project-read": "プロジェクト内で読み取り可能",+ "project-read-desc": "シートの所有者と「bb.worksheets.manage」権限を持つユーザーは読み取り/書き込みが可能で、「bb.worksheets.get」権限を持つ他のプロジェクトユーザーは読み取りが可能です。",+ "project-write": "プロジェクト内での読み取りと書き込み",+ "project-write-desc": "シート所有者と「bb.worksheets.get」権限を持つプロジェクトユーザーの両方が読み取り/書き込みできます。","query-context": {"admin-data-source-is-disallowed-to-query": "管理者データ ソースはクエリできません。"},+ "re-request": "再申請","redis-command": {"all-nodes": "すべてのノード","only-for-cluster": "クラスタ接続のみ使用可能","self": "redisコマンドを実行する","single-node": "単一ノード"},+ "request-access": "Request Access",+ "request-data-access": "Request Data Access","result-limit": {"self": "結果の制限"},"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "search-history-by-statement": "ステートメントで検索","select-a-database-to-start": "開始するにはデータベースを選択してください","self": "SQLエディタ","unmask-warning": "The query result may include unmasked sensitive data.",+ "url-copied-to-clipboard": "URLがクリップボードにコピーされました","view-issue": "View Issue","web-socket": {"errors": {diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex a8ea7bcebb..7826db9ab1 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -266,7 +266,7 @@"environment-name": "Tên môi trường","environments": "Môi trường","error": "Lỗi",- "expiration": "Expiration",+ "expiration": "Hết hạn","export": "Xuất","failed": "Thất bại","file-selector": {@@ -322,7 +322,7 @@"project": "Dự án","projects": "Dự án","read-only": "Chỉ đọc",- "reason": "Reason",+ "reason": "Lý do","regenerate": "Tạo lại","reject": "Reject","rejected": "Đã từ chối",@@ -360,6 +360,7 @@"sensitive-placeholder": "Nhạy cảm - Chỉ ghi","setting": "Cài đặt","settings": "Cài đặt",+ "share": "Chia sẻ","sign-in": "Đăng nhập","sign-in-as-admin": "Đăng nhập với tư cách quản trị viên","sign-up": "Đăng ký",@@ -2305,6 +2306,16 @@},"sql-editor": {"access-grants": "Access Grants",+ "access-search": {+ "scope": {+ "database": {+ "description": "Lọc theo cơ sở dữ liệu"+ },+ "status": {+ "description": "Tìm kiếm theo trạng thái cấp quyền truy cập"+ }+ }+ },"access-type-unmask": "See unmasked sensitive data","activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?",@@ -2312,31 +2323,52 @@"admin-mode": {"self": "Chế độ quản trị"},+ "and-n-more-databases": "and {{n}} more databases","batch-query": {"batch": "Hàng loạt"},"connect-to-a-database": "Kết nối cơ sở dữ liệu",+ "duration-day": "{{days}} day",+ "duration-days": "{{days}} days",+ "duration-hours": "{{hours}} hour | {{hours}} hours",+ "expire-at": "Expire at {{time}}",+ "expire-in": "Expire in {{time}}","expired": "Expired","format-sql": "Format SQL","grant-type-unmask": "Unmask","jit": "Just-In-Time Access",+ "link-access": "Truy cập liên kết",+ "no-access-requests": "No access requests",+ "no-history-found": "Không tìm thấy lịch sử",+ "only-select-allowed": "Chỉ cho phép thực thi câu lệnh chỉ đọc.",+ "private": "Riêng tư",+ "private-desc": "Chỉ bạn mới có thể truy cập trang tính này",+ "project-read": "Đọc dự án",+ "project-read-desc": "Cả chủ sở hữu trang tính và người dùng có quyền \"bb.worksheets.manage\" đều có thể đọc/ghi, những người dùng dự án khác có quyền \"bb.worksheets.get\" có thể đọc",+ "project-write": "Ghi dự án",+ "project-write-desc": "Cả chủ sở hữu trang tính và người dùng dự án có quyền \"bb.worksheets.get\" đều có thể đọc/ghi","query-context": {"admin-data-source-is-disallowed-to-query": "Nguồn dữ liệu quản trị không được phép truy vấn."},+ "re-request": "Yêu cầu lại","redis-command": {"all-nodes": "Tất cả các nút","only-for-cluster": "Chỉ khả dụng cho kết nối cụm","self": "Chạy lệnh redis trên","single-node": "Nút đơn"},+ "request-access": "Request Access",+ "request-data-access": "Request Data Access","result-limit": {"self": "Giới hạn kết quả"},"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "search-history-by-statement": "Tìm kiếm theo câu lệnh","select-a-database-to-start": "Chọn một cơ sở dữ liệu để bắt đầu","self": "Trình soạn thảo SQL","unmask-warning": "The query result may include unmasked sensitive data.",+ "url-copied-to-clipboard": "URL đã được sao chép vào bảng nhớ tạm của bạn","view-issue": "View Issue","web-socket": {"errors": {diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 98df725dd1..fb51be2356 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -266,7 +266,7 @@"environment-name": "环境名","environments": "环境","error": "错误",- "expiration": "Expiration",+ "expiration": "过期时间","export": "导出","failed": "失败","file-selector": {@@ -322,7 +322,7 @@"project": "项目","projects": "项目","read-only": "只读",- "reason": "Reason",+ "reason": "理由","regenerate": "重新生成","reject": "驳回","rejected": "已拒绝",@@ -360,6 +360,7 @@"sensitive-placeholder": "敏感数据 - 仅写入","setting": "设置","settings": "设置",+ "share": "分享","sign-in": "登录","sign-in-as-admin": "以管理员身份登录","sign-up": "注册",@@ -2305,6 +2306,16 @@},"sql-editor": {"access-grants": "访问授权",+ "access-search": {+ "scope": {+ "database": {+ "description": "按数据库筛选"+ },+ "status": {+ "description": "按访问授权状态搜索"+ }+ }+ },"access-type-unmask": "See unmasked sensitive data","activate-access": "激活","activate-confirm": "确定要激活此访问授权吗?",@@ -2312,31 +2323,52 @@"admin-mode": {"self": "管理员模式"},+ "and-n-more-databases": "及其他 {{n}} 个数据库","batch-query": {"batch": "批量"},"connect-to-a-database": "连接数据库",+ "duration-day": "{{days}} 天",+ "duration-days": "{{days}} 天",+ "duration-hours": "{{hours}} 小时",+ "expire-at": "{{time}} 过期",+ "expire-in": "{{time}} 后过期","expired": "已过期","format-sql": "格式化 SQL","grant-type-unmask": "脱敏豁免","jit": "即时访问",+ "link-access": "链接访问权限",+ "no-access-requests": "暂无访问请求",+ "no-history-found": "暂无历史记录",+ "only-select-allowed": "只允许执行只读语句",+ "private": "私有",+ "private-desc": "只有您自己可以访问此工作表",+ "project-read": "项目内可读",+ "project-read-desc": "工作表所有者和具有\"bb.worksheets.manage\"权限的用户都可以读/写,具有\"bb.worksheets.get\"权限的其他项目用户可以读取",+ "project-write": "项目内读写",+ "project-write-desc": "工作表所有者和具有\"bb.worksheets.get\"权限的项目用户都可以读/写","query-context": {"admin-data-source-is-disallowed-to-query": "禁止查询主数据源。"},+ "re-request": "重新申请","redis-command": {"all-nodes": "所有节点","only-for-cluster": "仅适用于集群连接","self": "运行 redis 命令","single-node": "单节点"},+ "request-access": "申请访问",+ "request-data-access": "申请数据访问","result-limit": {"self": "结果限制"},"revoke-access": "撤销","revoke-confirm": "确定要撤销此访问授权吗?",+ "search-history-by-statement": "搜索 SQL 语句","select-a-database-to-start": "选择数据库以开始","self": "SQL 编辑器","unmask-warning": "The query result may include unmasked sensitive data.",+ "url-copied-to-clipboard": "URL 已复制到剪贴板","view-issue": "查看工单","web-socket": {"errors": {diff --git a/frontend/src/store/modules/sqlEditor/index.ts b/frontend/src/store/modules/sqlEditor/index.tsindex d3bb1d239a..33d94e23e2 100644--- a/frontend/src/store/modules/sqlEditor/index.ts+++ b/frontend/src/store/modules/sqlEditor/index.ts@@ -4,3 +4,4 @@ export * from "./tree";export * from "./queryHistory";export * from "./uiState";export * from "./webTerminal";+export * from "./worksheet";diff --git a/frontend/src/store/modules/sqlEditor/queryHistory.ts b/frontend/src/store/modules/sqlEditor/queryHistory.tsindex 7a12891eb6..90885e4bea 100644--- a/frontend/src/store/modules/sqlEditor/queryHistory.ts+++ b/frontend/src/store/modules/sqlEditor/queryHistory.ts@@ -82,10 +82,7 @@ export const useSQLEditorQueryHistoryStore = defineStore(const resetPageToken = (filter: QueryHistoryFilter) => {const key = getCacheKey(filter);- if (!queryHistoryMap.has(key)) {- queryHistoryMap.set(key, { queryHistories: [] });- }- queryHistoryMap.get(key)!.nextPageToken = "";+ queryHistoryMap.set(key, { queryHistories: [] });};return {diff --git a/frontend/src/store/modules/sqlEditor/worksheet.test.ts b/frontend/src/store/modules/sqlEditor/worksheet.test.tsnew file mode 100644index 0000000000..e7c07971c9--- /dev/null+++ b/frontend/src/store/modules/sqlEditor/worksheet.test.ts@@ -0,0 +1,122 @@+import { createPinia, setActivePinia } from "pinia";+import { beforeEach, describe, expect, test, vi } from "vitest";++// Mock @/store to stub sub-stores (mirrors uiState.test.ts pattern)+vi.mock("@/store", async () => {+ const { ref } = await import("vue");+ return {+ pushNotification: vi.fn(),+ useProjectIamPolicyStore: vi.fn(() => ({+ getOrFetchProjectIamPolicy: vi.fn(),+ })),+ useProjectV1Store: vi.fn(() => ({+ getOrFetchProjectByName: vi.fn(),+ })),+ useSQLEditorStore: vi.fn(() => ({+ project: "projects/default",+ projectContextReady: true,+ setProject: vi.fn(),+ })),+ useSQLEditorTabStore: vi.fn(() => ({+ updateTab: vi.fn(),+ getTabById: vi.fn(),+ })),+ useSQLEditorUIStore: vi.fn(() => ({+ showConnectionPanel: ref(false),+ })),+ useWorkSheetStore: vi.fn(() => ({+ getWorksheetByName: vi.fn(),+ patchWorksheet: vi.fn(),+ upsertWorksheetOrganizer: vi.fn(),+ createWorksheet: vi.fn(),+ })),+ };+});++// Mock @/utils completely to avoid native binary dependencies+vi.mock("@/utils", () => ({+ extractWorksheetConnection: vi.fn(+ async ({ database }: { database: string }) => ({+ database,+ instance: "",+ })+ ),+ isSimilarDefaultSQLEditorTabTitle: vi.fn(() => false),+ isWorksheetWritableV1: vi.fn(() => true),+ NEW_WORKSHEET_TITLE: "Untitled",+ suggestedTabTitleForSQLEditorConnection: vi.fn(() => "Untitled"),+ isValidDatabaseName: vi.fn(() => false),+ isValidProjectName: vi.fn((name: string) => name.startsWith("projects/")),+}));++// Mock @/types to avoid importing native modules transitively+vi.mock("@/types", () => ({+ isValidDatabaseName: vi.fn(() => false),+ isValidProjectName: vi.fn((name: string) => name.startsWith("projects/")),+}));++// Mock @/views/sql-editor/Sheet+vi.mock("@/views/sql-editor/Sheet", () => ({+ openWorksheetByName: vi.fn(),+}));++// Mock @/views/sql-editor/events+vi.mock("@/views/sql-editor/events", () => ({+ sqlEditorEvents: {+ emit: vi.fn(),+ },+}));++// Mock protobuf and worksheet_service_pb+vi.mock("@bufbuild/protobuf", () => ({+ create: vi.fn(),+}));++vi.mock("@/types/proto-es/v1/worksheet_service_pb", () => ({+ Worksheet_Visibility: { PRIVATE: 0 },+ WorksheetSchema: {},+}));++let useSQLEditorWorksheetStore: typeof import("./worksheet").useSQLEditorWorksheetStore;++beforeEach(async () => {+ vi.clearAllMocks();+ setActivePinia(createPinia());+ ({ useSQLEditorWorksheetStore } = await import("./worksheet"));+});++describe("useSQLEditorWorksheetStore", () => {+ test("store initializes with autoSaveController === null", () => {+ const store = useSQLEditorWorksheetStore();+ expect(store.autoSaveController).toBeNull();+ });++ test("abortAutoSave() with no controller is a no-op (doesn't throw)", () => {+ const store = useSQLEditorWorksheetStore();+ expect(() => store.abortAutoSave()).not.toThrow();+ expect(store.autoSaveController).toBeNull();+ });++ test("abortAutoSave() with a controller calls abort and clears it", () => {+ const store = useSQLEditorWorksheetStore();+ const controller = new AbortController();+ const abortSpy = vi.spyOn(controller, "abort");+ store.autoSaveController = controller;++ store.abortAutoSave();++ expect(abortSpy).toHaveBeenCalledTimes(1);+ expect(store.autoSaveController).toBeNull();+ });++ test("maybeSwitchProject with an invalid project name returns undefined without setting project", async () => {+ const store = useSQLEditorWorksheetStore();+ const { useSQLEditorStore } = await import("@/store");+ const editorStore = useSQLEditorStore();++ const result = await store.maybeSwitchProject("not-a-valid-project-name");++ expect(result).toBeUndefined();+ expect(editorStore.setProject).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/store/modules/sqlEditor/worksheet.ts b/frontend/src/store/modules/sqlEditor/worksheet.tsnew file mode 100644index 0000000000..73ada59ce0--- /dev/null+++ b/frontend/src/store/modules/sqlEditor/worksheet.ts@@ -0,0 +1,203 @@+import { create } from "@bufbuild/protobuf";+import { isUndefined } from "lodash-es";+import { defineStore } from "pinia";+import { nextTick, ref } from "vue";+import {+ useProjectIamPolicyStore,+ useProjectV1Store,+ useSQLEditorStore,+ useSQLEditorTabStore,+ useSQLEditorUIStore,+ useWorkSheetStore,+} from "@/store";+import type { SQLEditorTab } from "@/types";+import { isValidDatabaseName, isValidProjectName } from "@/types";+import {+ Worksheet_Visibility,+ WorksheetSchema,+} from "@/types/proto-es/v1/worksheet_service_pb";+import {+ extractWorksheetConnection,+ isSimilarDefaultSQLEditorTabTitle,+ NEW_WORKSHEET_TITLE,+ suggestedTabTitleForSQLEditorConnection,+} from "@/utils";+import { sqlEditorEvents } from "@/views/sql-editor/events";+import { openWorksheetByName } from "@/views/sql-editor/Sheet";++export const useSQLEditorWorksheetStore = defineStore(+ "sqlEditorWorksheet",+ () => {+ const editorStore = useSQLEditorStore();+ const tabStore = useSQLEditorTabStore();+ const projectStore = useProjectV1Store();+ const projectIamPolicyStore = useProjectIamPolicyStore();+ const worksheetStore = useWorkSheetStore();+ const uiStore = useSQLEditorUIStore();++ const autoSaveController = ref<AbortController | null>(null);++ const abortAutoSave = () => {+ if (autoSaveController.value) {+ autoSaveController.value.abort();+ autoSaveController.value = null;+ }+ };++ const maybeSwitchProject = async (+ projectName: string+ ): Promise<string | undefined> => {+ editorStore.projectContextReady = false;+ try {+ if (!isValidProjectName(projectName)) {+ return;+ }+ const project = await projectStore.getOrFetchProjectByName(projectName);+ // Fetch IAM policy to ensure permission checks work correctly+ await projectIamPolicyStore.getOrFetchProjectIamPolicy(project.name);+ editorStore.setProject(project.name);+ await sqlEditorEvents.emit("project-context-ready", {+ project: project.name,+ });+ return project.name;+ } catch {+ // Nothing+ } finally {+ editorStore.projectContextReady = true;+ }+ };++ const maybeUpdateWorksheet = async ({+ tabId,+ worksheet,+ title,+ database,+ statement,+ folders,+ signal,+ }: {+ tabId: string;+ worksheet?: string;+ title?: string;+ database: string;+ statement: string;+ folders?: string[];+ signal?: AbortSignal;+ }): Promise<SQLEditorTab | undefined> => {+ const connection = await extractWorksheetConnection({ database });+ let worksheetTitle = title ?? "";+ if (isSimilarDefaultSQLEditorTabTitle(worksheetTitle)) {+ worksheetTitle = suggestedTabTitleForSQLEditorConnection(connection);+ }++ if (worksheet) {+ const currentSheet = worksheetStore.getWorksheetByName(worksheet);+ if (!currentSheet) {+ return;+ }+ if (!isSimilarDefaultSQLEditorTabTitle(currentSheet.title)) {+ worksheetTitle = currentSheet.title;+ }++ const updated = await worksheetStore.patchWorksheet(+ {+ ...currentSheet,+ title: worksheetTitle,+ database,+ content: new TextEncoder().encode(statement),+ },+ ["title", "database", "content"],+ signal+ );+ if (!updated) {+ return;+ }+ if (!isUndefined(folders)) {+ await worksheetStore.upsertWorksheetOrganizer(+ {+ worksheet: updated.name,+ folders: folders,+ },+ ["folders"]+ );+ }+ }++ return tabStore.updateTab(tabId, {+ status: "CLEAN",+ connection,+ title: worksheetTitle,+ worksheet,+ });+ };++ const createWorksheet = async ({+ tabId,+ title,+ statement = "",+ folders = [],+ database = "",+ }: {+ tabId?: string;+ title?: string;+ statement?: string;+ folders?: string[];+ database?: string;+ }): Promise<SQLEditorTab | undefined> => {+ let worksheetTitle = title || NEW_WORKSHEET_TITLE;+ const connection = await extractWorksheetConnection({ database });+ if (!title && isValidDatabaseName(database)) {+ worksheetTitle = suggestedTabTitleForSQLEditorConnection(connection);+ }++ const newWorksheet = await worksheetStore.createWorksheet(+ create(WorksheetSchema, {+ title: worksheetTitle,+ database,+ content: new TextEncoder().encode(statement),+ project: editorStore.project,+ visibility: Worksheet_Visibility.PRIVATE,+ })+ );++ if (folders.length > 0) {+ await worksheetStore.upsertWorksheetOrganizer(+ {+ worksheet: newWorksheet.name,+ folders: folders,+ },+ ["folders"]+ );+ }++ if (tabId) {+ return tabStore.updateTab(tabId, {+ status: "CLEAN",+ title: worksheetTitle,+ statement,+ connection,+ worksheet: newWorksheet.name,+ });+ } else {+ const tab = await openWorksheetByName({+ worksheet: newWorksheet.name,+ forceNewTab: true,+ });+ nextTick(() => {+ if (tab && !tab.connection?.database) {+ uiStore.showConnectionPanel = true;+ }+ });+ return tab;+ }+ };++ return {+ autoSaveController,+ abortAutoSave,+ maybeSwitchProject,+ maybeUpdateWorksheet,+ createWorksheet,+ };+ }+);diff --git a/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantItem.vue b/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantItem.vuedeleted file mode 100644index 0db878bef2..0000000000--- a/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantItem.vue+++ /dev/null@@ -1,207 +0,0 @@-<template>- <div- class="w-full p-2 gap-y-2 border-b flex flex-col justify-start items-start hover:bg-gray-50"- :class="highlight ? 'highlight-pulse' : 'transition-colors duration-1000'"- >- <div class="w-full flex flex-row justify-between items-center gap-x-2">- <div class="flex items-center gap-x-1">- <NTag :type="statusTagType" size="tiny" :bordered="false" round>- {{ statusLabel }}- </NTag>- <NTag v-if="grant.unmask" size="tiny" :bordered="false" round>- {{ $t("sql-editor.grant-type-unmask") }}- </NTag>- </div>- <NEllipsis- v-if="expirationText"- :line-clamp="1"- :tooltip="true"- >- <span class="text-xs text-gray-500 shrink-0">- {{ expirationText }}- </span>- </NEllipsis>- </div>-- <NTooltip placement="right">- <template #trigger>- <p- class="max-w-full text-xs wrap-break-word whitespace-pre-wrap font-mono line-clamp-2"- :class="{ 'line-through text-gray-400': isExpired || isRejectedOrCanceled }"- >- {{ grant.query }}- </p>- </template>- <pre class="max-w-lg whitespace-pre-wrap text-xs">{{ grant.query }}</pre>- </NTooltip>-- <div class="w-full flex flex-col gap-y-2">- <NTooltip :disabled="allDatabaseNames.length <= 2" placement="right">- <template #trigger>- <span class="text-xs text-gray-400 truncate">- {{ databaseNamesDisplay }}- </span>- </template>- <div class="flex flex-col">- <span v-for="name in allDatabaseNames" :key="name">{{ name }}</span>- </div>- </NTooltip>- <div class="flex items-center justify-between gap-x-1">- <div>- <NButton- v-if="isActive"- size="tiny"- secondary- type="primary"- @click.stop="$emit('run', grant)"- >- {{ $t("common.run") }}- </NButton>- </div>- <div class="flex items-center gap-x-1">- <NButton- v-if="isRejectedOrCanceled"- tertiary- size="tiny"- @click.stop="$emit('request', grant)"- >- {{ $t("sql-editor.re-request") }}- </NButton>- <NButton- v-if="grant.issue"- tertiary- size="tiny"- tag="a"- :href="issueLink"- target="_blank"- @click.stop- >- {{ $t("sql-editor.view-issue") }}- </NButton>- </div>- </div>- </div>- </div>-</template>--<script setup lang="ts">-import { NButton, NEllipsis, NTag, NTooltip } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { type AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";-import {- getAccessGrantDisplayStatus,- getAccessGrantDisplayStatusText,- getAccessGrantExpirationText,- getAccessGrantExpireTimeMs,- getAccessGrantStatusTagType,-} from "@/utils/accessGrant";--const props = defineProps<{- grant: AccessGrant;- highlight?: boolean;- issue?: Issue;-}>();--defineEmits<{- (e: "run", grant: AccessGrant): void;- (e: "request", grant: AccessGrant): void;-}>();--const { t } = useI18n();--const expireTimeMs = computed(() => getAccessGrantExpireTimeMs(props.grant));--const displayStatus = computed(() =>- getAccessGrantDisplayStatus(props.grant, props.issue)-);--const isActive = computed(() => displayStatus.value === "ACTIVE");--const isExpired = computed(() => {- return displayStatus.value === "EXPIRED";-});--const statusTagType = computed(() =>- getAccessGrantStatusTagType(displayStatus.value)-);--const isRejectedOrCanceled = computed(- () => displayStatus.value !== "ACTIVE" && displayStatus.value !== "PENDING"-);--const statusLabel = computed(() => {- return getAccessGrantDisplayStatusText(props.grant, props.issue);-});--const expirationInfo = computed(() =>- getAccessGrantExpirationText(props.grant)-);--const expirationText = computed(() => {- // Only show the expiration for ACTIVE/EXPIRED- if (displayStatus.value !== "ACTIVE" && displayStatus.value !== "EXPIRED") {- return;- }-- const info = expirationInfo.value;- if (info.type === "never" || info.type === "duration") {- return;- }-- if (!isExpired.value && expireTimeMs.value !== undefined) {- const diff = expireTimeMs.value - Date.now();- const hours = Math.floor(diff / (1000 * 60 * 60));- if (hours >= 24) {- return t("sql-editor.expire-at", { time: info.value });- }- const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));- const dur = hours > 0 ? `${hours}h${minutes}m` : `${minutes}m`;- return t("sql-editor.expire-in", { time: dur });- }- return `${t("issue.access-grant.expired-at")} ${info.value}`;-});--const allDatabaseNames = computed(() => {- return props.grant.targets.map((t) => {- const match = t.match(/databases\/(.+)$/);- return match ? match[1] : t;- });-});--const databaseNamesDisplay = computed(() => {- const names = allDatabaseNames.value;- if (names.length <= 2) {- return names.join(", ");- }- return `${names.slice(0, 2).join(", ")} ${t("sql-editor.and-n-more-databases", { n: names.length - 2 })}`;-});--const issueLink = computed(() => {- if (!props.grant.issue) return "";- let path = props.grant.issue;- if (!path.startsWith("/")) {- path = `/${path}`;- }- return path;-});-</script>--<style scoped>-.highlight-pulse {- animation: highlight-fade 3s ease-in-out;-}--@keyframes highlight-fade {- 0% {- background-color: rgb(219 234 254); /* bg-blue-100 */- }- 60% {- background-color: rgb(219 234 254);- }- 100% {- background-color: transparent;- }-}-</style>diff --git a/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessPane.vue b/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessPane.vuedeleted file mode 100644index 143ada927c..0000000000--- a/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessPane.vue+++ /dev/null@@ -1,328 +0,0 @@-<template>- <div class="relative w-full h-full flex flex-col justify-start items-start gap-y-1">- <div- ref="containerRef"- class="w-full px-1 flex flex-wrap items-center gap-x-2 gap-y-2"- >- <AdvancedSearch- class="flex-1"- :class="useSmallLayout ? 'min-w-full' : ''"- :size="'small'"- :params="searchParams"- :scope-options="scopeOptions"- :placeholder="$t('issue.advanced-search.filter')"- :autofocus="false"- :cache-query="false"- @update:params="searchParams = $event"- />- <PermissionGuardWrapper- v-slot="slotProps"- :project="project"- :permissions="[- 'bb.accessGrants.create'- ]"- class="ml-auto"- >- <NButton- ghost- size="small"- type="primary"- :style="{- width: useSmallLayout ? '100%' : 'auto'- }"- :disabled="!hasJITFeature || slotProps.disabled"- @click="showDrawer = true"- >- <template v-if="!hasJITFeature" #icon>- <FeatureBadge :clickable="false" :feature="PlanFeature.FEATURE_JIT" />- </template>- {{ $t("sql-editor.request-access") }}- </NButton>- </PermissionGuardWrapper>- </div>- <NDivider class="mt-2! mb-0!" />- <div class="w-full flex flex-col justify-start items-start overflow-y-auto">- <AccessGrantItem- v-for="grant in accessGrantList"- :key="grant.name"- :grant="grant"- :highlight="grant.name === highlightAccessGrantName"- :issue="issueByGrantName.get(grant.name)"- @run="handleRun"- @request="handleRequest"- />- <div- v-if="nextPageToken"- class="w-full flex flex-col items-center my-2"- >- <NButton- quaternary- size="small"- :loading="loading"- @click="fetchAccessGrants(false)"- >- <span class="textinfolabel">- {{ $t("common.load-more") }}- </span>- </NButton>- </div>- </div>-- <template v-if="accessGrantList.length === 0">- <MaskSpinner v-if="loading" class="bg-white/75!" />- <div- v-else- class="w-full flex items-center justify-center py-8 textinfolabel"- >- {{ $t("sql-editor.no-access-requests") }}- </div>- </template>-- <AccessGrantRequestDrawer- v-if="showDrawer"- :query="pendingCreate?.query"- :unmask="pendingCreate?.unmask"- :targets="pendingCreate?.targets"- @close="handleDrawerClose"- />- </div>-</template>--<script lang="ts" setup>-import { useElementSize } from "@vueuse/core";-import { NButton, NDivider } from "naive-ui";-import { computed, nextTick, ref, watch } from "vue";-import AdvancedSearch from "@/components/AdvancedSearch";-import { FeatureBadge } from "@/components/FeatureGuard";-import MaskSpinner from "@/components/misc/MaskSpinner.vue";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import { useExecuteSQL } from "@/composables/useExecuteSQL";-import {- type AccessFilter,- hasFeature,- useAccessGrantStore,- useConnectionOfCurrentSQLEditorTab,- useDatabaseV1Store,- useIssueV1Store,- useProjectV1Store,- useSQLEditorStore,- useSQLEditorTabStore,-} from "@/store";-import {- type AccessGrant,- AccessGrant_Status,-} from "@/types/proto-es/v1/access_grant_service_pb";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import {- type AccessGrantFilterStatus,- getAccessSearchOptions,- getDefaultPagination,- type SearchParams,-} from "@/utils";-import {- getValueFromSearchParams,- getValuesFromSearchParams,-} from "@/utils/v1/advanced-search/common";-import { useSQLEditorContext } from "../../context";-import AccessGrantItem from "./AccessGrantItem.vue";-import AccessGrantRequestDrawer from "./AccessGrantRequestDrawer.vue";--const PAGE_SIZE = getDefaultPagination();--const projectStore = useProjectV1Store();-const editorStore = useSQLEditorStore();-const tabStore = useSQLEditorTabStore();-const accessGrantStore = useAccessGrantStore();-const issueStore = useIssueV1Store();-const { instance: currentInstance } = useConnectionOfCurrentSQLEditorTab();-const { execute } = useExecuteSQL();-const { highlightAccessGrantName } = useSQLEditorContext();--const showDrawer = ref(false);-const loading = ref(false);-const pendingCreate = ref<AccessGrant>();-const accessGrantList = ref<AccessGrant[]>([]);-const nextPageToken = ref("");-// Maps access grant name → Issue for PENDING grants with an associated issue.-const issueByGrantName = ref<Map<string, Issue>>(new Map());-const containerRef = ref<HTMLDivElement>();-const { width: containerWidth } = useElementSize(containerRef);-const useSmallLayout = computed(- () => containerWidth.value > 0 && containerWidth.value < 250-);--watch(- () => showDrawer.value,- (showDrawer) => {- if (!showDrawer) {- pendingCreate.value = undefined;- }- }-);--const hasJITFeature = computed(() => hasFeature(PlanFeature.FEATURE_JIT));--const project = computed(() =>- projectStore.getProjectByName(editorStore.project)-);--const searchParams = ref<SearchParams>({- query: "",- scopes: [- {- id: "status",- value: AccessGrant_Status[AccessGrant_Status.ACTIVE],- },- {- id: "status",- value: AccessGrant_Status[AccessGrant_Status.PENDING],- },- ],-});--const scopeOptions = computed(() => {- return getAccessSearchOptions({- project: editorStore.project,- showCreator: false,- });-});--const selectedStatuses = computed(- () =>- getValuesFromSearchParams(- searchParams.value,- "status"- ) as AccessGrantFilterStatus[]-);--// Build AccessFilter from search params.-const filter = computed((): AccessFilter => {- const f: AccessFilter = {- status: selectedStatuses.value,- };-- const database = getValueFromSearchParams(- searchParams.value,- "database",- undefined- );- if (database) {- f.target = database;- }-- const queryText = searchParams.value.query.trim();- if (queryText) {- f.statement = queryText;- }-- return f;-});--const fetchIssuesForPendingGrants = async (grants: AccessGrant[]) => {- const pendingWithIssue = grants.filter(- (g) => g.status === AccessGrant_Status.PENDING && g.issue- );- const results = await Promise.all(- pendingWithIssue.map(async (g) => {- try {- const issue = await issueStore.fetchIssueByName(g.issue, true);- return { grantName: g.name, issue };- } catch {- return undefined;- }- })- );- for (const r of results) {- if (r) {- issueByGrantName.value.set(r.grantName, r.issue);- }- }-};--const fetchAccessGrants = async (resetList = true) => {- const project = editorStore.project;- if (!project) return;-- loading.value = true;- try {- const response = await accessGrantStore.searchMyAccessGrants({- parent: project,- filter: filter.value,- pageSize: PAGE_SIZE,- pageToken: resetList ? undefined : nextPageToken.value,- });- if (resetList) {- accessGrantList.value = response.accessGrants;- issueByGrantName.value = new Map();- } else {- accessGrantList.value.push(...response.accessGrants);- }- nextPageToken.value = response.nextPageToken;- await fetchIssuesForPendingGrants(response.accessGrants);- } finally {- loading.value = false;- }-};--// Re-fetch when project or filter changes.-watch([() => editorStore.project, filter], () => fetchAccessGrants(), {- immediate: true,- deep: true,-});--// When a new grant is highlighted (e.g. created from the drawer in other panels),-// refresh the list so it appears, then auto-clear the highlight after 3 seconds.-watch(- highlightAccessGrantName,- async (name) => {- if (name) {- await fetchAccessGrants();- setTimeout(() => {- if (highlightAccessGrantName.value === name) {- highlightAccessGrantName.value = undefined;- }- }, 3000);- }- },- { immediate: true }-);--const handleDrawerClose = () => {- showDrawer.value = false;- fetchAccessGrants();-};--const handleRequest = async (grant: AccessGrant) => {- pendingCreate.value = grant;- showDrawer.value = true;-};--const handleRun = async (grant: AccessGrant) => {- const database = grant.targets[0] ?? "";- const instanceName = database.replace(/\/databases\/.*$/, "");- // Pre-fetch the database so the connection is fully resolved- // before the tab is created and the query is executed.- await useDatabaseV1Store().getOrFetchDatabaseByName(database);- const tab = tabStore.addTab(- {- connection: { instance: instanceName, database },- statement: grant.query,- batchQueryContext: {- databases: grant.targets,- },- },- /* beside */ true- );- nextTick(() => {- execute({- connection: { ...tab.connection },- statement: grant.query,- engine: currentInstance.value.engine,- explain: false,- selection: null,- limit: 0, // no limit- });- });-};-</script>diff --git a/frontend/src/views/sql-editor/AsidePanel/AccessPane/index.ts b/frontend/src/views/sql-editor/AsidePanel/AccessPane/index.tsdeleted file mode 100644index 59368ea352..0000000000--- a/frontend/src/views/sql-editor/AsidePanel/AccessPane/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import AccessPane from "./AccessPane.vue";--export default AccessPane;diff --git a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vueindex 7a4d7a7dc6..b67818ea49 100644--- a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue+++ b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue@@ -54,8 +54,14 @@<div class="h-full flex-1 flex flex-col pt-1 overflow-hidden"><WorksheetPane v-if="asidePanelTab === 'WORKSHEET'" /><SchemaPane v-if="asidePanelTab === 'SCHEMA'" />- <HistoryPane v-if="asidePanelTab === 'HISTORY'" />- <AccessPane v-if="asidePanelTab === 'ACCESS'" />+ <ReactPageMount+ v-if="asidePanelTab === 'HISTORY'"+ page="HistoryPane"+ />+ <ReactPageMount+ v-if="asidePanelTab === 'ACCESS'"+ page="AccessPane"+ /></div></div></div>@@ -77,9 +83,7 @@ import {import { defaultProject, isValidProjectName } from "@/types";import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";import { useSQLEditorContext } from "../context";-import AccessPane from "./AccessPane";import ActionBar from "./ActionBar";-import HistoryPane from "./HistoryPane";import SchemaPane from "./SchemaPane";import WorksheetPane from "./WorksheetPane";diff --git a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryConnectionIcon.vue b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryConnectionIcon.vuedeleted file mode 100644index d4cfa74837..0000000000--- a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryConnectionIcon.vue+++ /dev/null@@ -1,27 +0,0 @@-<template>- <InstanceV1EngineIcon- v-if="isValidInstanceName(instance.name)"- :instance="instance"- :tooltip="false"- class="h-3.5 w-auto"- />-</template>--<script setup lang="ts">-import { computedAsync } from "@vueuse/core";-import { InstanceV1EngineIcon } from "@/components/v2";-import { useDatabaseV1Store } from "@/store";-import { isValidInstanceName, unknownInstanceResource } from "@/types";-import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";-import { extractDatabaseResourceName, getInstanceResource } from "@/utils";--const props = defineProps<{- queryHistory: QueryHistory;-}>();--const instance = computedAsync(async () => {- const { database } = extractDatabaseResourceName(props.queryHistory.database);- const d = await useDatabaseV1Store().getOrFetchDatabaseByName(database);- return getInstanceResource(d);-}, unknownInstanceResource());-</script>diff --git a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vuedeleted file mode 100644index 3a30f8afc0..0000000000--- a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue+++ /dev/null@@ -1,169 +0,0 @@-<!-- eslint-disable vue/no-v-html -->-<template>- <div class="relative w-full h-full flex flex-col justify-start items-start">- <div class="w-full px-1">- <SearchBox- :value="state.search"- size="small"- :placeholder="$t('sql-editor.search-history-by-statement')"- style="max-width: 100%"- @update:value="onSearchUpdate"- />- </div>- <div class="w-full flex flex-col justify-start items-start overflow-y-auto">- <div- v-for="history in queryHistoryData.queryHistories"- :key="history.name"- class="w-full p-2 gap-y-1 border-b flex flex-col justify-start items-start cursor-pointer hover:bg-gray-50"- @click="handleQueryHistoryClick(history)"- >- <div class="w-full flex flex-row justify-between items-center">- <div class="flex items-start gap-x-1">- <span class="text-xs text-gray-500">- {{ titleOfQueryHistory(history) }}- </span>- </div>- <CopyButton- quaternary- :text="false"- :content="history.statement"- @click.stop- />- </div>- <p- class="max-w-full text-xs wrap-break-word font-mono line-clamp-3"- v-html="getFormattedStatement(history.statement)"- ></p>- </div>- <div- v-if="queryHistoryData.nextPageToken"- class="w-full flex flex-col items-center my-2"- >- <NButton- quaternary- :size="'small'"- :loading="state.loading"- @click="fetchQueryHistoryListList"- >- <span class="textinfolabel">- {{ $t("common.load-more") }}- </span>- </NButton>- </div>- </div>-- <template v-if="queryHistoryData.queryHistories.length === 0">- <MaskSpinner v-if="state.loading" class="bg-white/75!" />- <div- v-else- class="w-full flex items-center justify-center py-8 textinfolabel"- >- {{ $t("sql-editor.no-history-found") }}- </div>- </template>- </div>-</template>--<script lang="ts" setup>-import { useDebounceFn } from "@vueuse/core";-import dayjs from "dayjs";-import { NButton } from "naive-ui";-import { computed, reactive, watch } from "vue";-import MaskSpinner from "@/components/misc/MaskSpinner.vue";-import { CopyButton, SearchBox } from "@/components/v2";-import {- type QueryHistoryFilter,- useSQLEditorQueryHistoryStore,- useSQLEditorStore,- useSQLEditorTabStore,-} from "@/store";-import { DEBOUNCE_SEARCH_DELAY, getDateForPbTimestampProtoEs } from "@/types";-import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";-import { getHighlightHTMLByKeyWords } from "@/utils";-import { useSQLEditorContext } from "@/views/sql-editor/context";--interface State {- search: string;- loading: boolean;-}--const tabStore = useSQLEditorTabStore();-const editorStore = useSQLEditorStore();-const queryHistoryStore = useSQLEditorQueryHistoryStore();-const { events: editorEvents } = useSQLEditorContext();--const state = reactive<State>({- search: "",- loading: false,-});--const historyQuery = computed((): QueryHistoryFilter => {- const tab = tabStore.currentTab;- return {- database: tab?.connection.database,- project: editorStore.project,- statement: state.search,- };-});--const onSearchUpdate = async (search: string) => {- queryHistoryStore.resetPageToken(historyQuery.value);- state.search = search;- await fetchQueryHistoryListList();-};--const queryHistoryData = computed(() =>- queryHistoryStore.getQueryHistoryList(historyQuery.value)-);--const fetchQueryHistoryListList = useDebounceFn(async () => {- state.loading = true;- try {- await queryHistoryStore.fetchQueryHistoryList(historyQuery.value);- } finally {- state.loading = false;- }-}, DEBOUNCE_SEARCH_DELAY);--watch(- () => historyQuery.value,- async () => {- if (queryHistoryData.value.queryHistories.length === 0) {- await fetchQueryHistoryListList();- }- },- {- immediate: true,- deep: true,- }-);--const getFormattedStatement = (statement: string) => {- return getHighlightHTMLByKeyWords(statement, state.search);-};--const titleOfQueryHistory = (history: QueryHistory) => {- return dayjs(getDateForPbTimestampProtoEs(history.createTime)).format(- "YYYY-MM-DD HH:mm:ss"- );-};--const handleQueryHistoryClick = (queryHistory: QueryHistory) => {- const { statement } = queryHistory;- if (tabStore.currentTab) {- editorEvents.emit("append-editor-content", {- content: statement,- select: true,- });- } else {- // Open a new tab with the connection and statement.- tabStore.addTab(- {- title: `Query history at ${titleOfQueryHistory(queryHistory)}`,- statement,- },- /* beside */ true- );- }-};-</script>diff --git a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/index.ts b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/index.tsdeleted file mode 100644index 5414a30964..0000000000--- a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import HistoryPane from "./HistoryPane.vue";--export default HistoryPane;diff --git a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vueindex 6801e3e0dd..d0b43b262e 100644--- a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue+++ b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue@@ -53,10 +53,9 @@:y="contextMenuContext.position.y"@clickoutside="handleContextMenuClickOutside">- <SharePopover+ <ReactPageMount page="SharePopoverBody":worksheet="worksheetEntity"- @on-updated="handleContextMenuClickOutside"- />+ :onUpdated="handleContextMenuClickOutside" /></NPopover></div></template>@@ -78,6 +77,7 @@ import { BBSpin } from "@/bbkit";import { HighlightLabelText } from "@/components/v2";import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";import { t } from "@/plugins/i18n";+import ReactPageMount from "@/react/ReactPageMount.vue";import {pushNotification,useSQLEditorStore,@@ -87,7 +87,6 @@ import {import { DEBOUNCE_SEARCH_DELAY } from "@/types";import { defer, isDescendantOf } from "@/utils";import { useSQLEditorContext } from "@/views/sql-editor/context";-import SharePopover from "@/views/sql-editor/EditorCommon/SharePopover.vue";import {openWorksheetByName,revealNodes,diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vueindex eae8cb5b9a..79cc5d4ab0 100644--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue@@ -104,7 +104,8 @@</NPopover></template><template #default>- <SharePopover :worksheet="sheetAndTabStore.currentSheet" />+ <ReactPageMount page="SharePopoverBody"+ :worksheet="sheetAndTabStore.currentSheet" /></template></NPopover></template>@@ -158,7 +159,6 @@ import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import { isWorksheetWritableV1, keyboardShortcutStr } from "@/utils";import { useSQLEditorContext } from "../context";import OpenAIButton from "./OpenAIButton";-import SharePopover from "./SharePopover.vue";interface LocalState {requiredFeatureName?: PlanFeature;diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/AdviceItem.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/AdviceItem.vuedeleted file mode 100644index ee2df550e2..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/AdviceItem.vue+++ /dev/null@@ -1,92 +0,0 @@-<template>- <div- class="grid items-start gap-2 text-sm p-1"- style="grid-template-columns: auto 1fr"- >- <div class="shrink-0 flex items-center h-5">- <CircleAlertIcon- v-if="advice.status === Advice_Level.ERROR"- class="w-5 h-5 text-error"- />- <CircleAlertIcon- v-if="advice.status === Advice_Level.WARNING"- class="w-5 h-5 text-warning"- />- </div>- <div class="flex items-center gap-1">- <span>{{ title }}</span>- <NButton- v-if="hasValidPosition"- size="tiny"- quaternary- type="primary"- @click="doScroll"- >- L{{ position.startLine }}:C{{ position.startColumn }}- </NButton>- </div>- <div v-if="advice.content" class="col-start-2">- {{ advice.content }}- </div>- </div>-</template>--<script setup lang="ts">-import { CircleAlertIcon } from "lucide-vue-next";-import { Selection } from "monaco-editor";-import { NButton } from "naive-ui";-import { computed } from "vue";-import { positionWithOffset } from "@/components/MonacoEditor/utils";-import type { SQLEditorQueryParams } from "@/types";-import { type Advice, Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { useSQLEditorContext } from "@/views/sql-editor/context";--const props = defineProps<{- advice: Advice;- executeParams?: SQLEditorQueryParams;-}>();-const { events: editorEvents } = useSQLEditorContext();--const title = computed(() => {- const { code, title } = props.advice;- const parts = [title];- if (code) {- parts.unshift(`(${code})`);- }- return parts.join(" ");-});--const hasValidPosition = computed(() => {- const { advice } = props;- // Position with line 0 means unknown position- return (advice.startPosition?.line ?? 0) > 0;-});--const position = computed(() => {- const { advice, executeParams } = props;- const [startLine, startColumn] = positionWithOffset(- advice.startPosition?.line ?? 1,- advice.startPosition?.column || 1,- executeParams?.selection- );- const [endLine, endColumn] = positionWithOffset(- advice.endPosition?.line ?? startLine,- advice.endPosition?.column || startColumn,- executeParams?.selection- );- return {- startLine,- startColumn,- endLine,- endColumn,- };-});--const doScroll = () => {- const { startLine, startColumn, endLine, endColumn } = position.value;- editorEvents.emit(- "set-editor-selection",- new Selection(startLine, startColumn, endLine, endColumn)- );-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/SharePopover.vue b/frontend/src/views/sql-editor/EditorCommon/SharePopover.vuedeleted file mode 100644index c36d2d083e..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/SharePopover.vue+++ /dev/null@@ -1,228 +0,0 @@-<template>- <div class="share-popover w-96 p-2 flex flex-col gap-y-4">- <section class="w-full flex flex-row justify-between items-center">- <div class="pr-4">- <h2 class="text-lg font-semibold">{{ $t("common.share") }}</h2>- </div>- <NPopover- trigger="click"- :show="isShowAccessPopover"- :disabled="!allowChangeAccess"- >- <template #trigger>- <div- class="flex items-center"- :class="allowChangeAccess ? 'cursor-pointer' : 'cursor-not-allowed'"- @click="isShowAccessPopover = !isShowAccessPopover"- >- <span class="pr-2">{{ $t("sql-editor.link-access") }}:</span>- <div- class="border flex flex-row justify-start items-center px-2 py-1 rounded-sm"- :class="- allowChangeAccess- ? 'hover:border-accent'- : 'border-gray-200 text-gray-400'- "- >- <strong>{{ currentAccess.label }}</strong>- <heroicons-solid:chevron-down />- </div>- </div>- </template>- <div class="access-content flex flex-col gap-y-2 w-80">- <div- v-for="option in accessOptions"- :key="option.label"- class="p-2 rounded-xs flex justify-between"- :class="[- allowChangeAccess && 'cursor-pointer hover:bg-gray-200',- option.value === currentAccess.value && 'bg-gray-200',- ]"- @click="handleChangeAccess(option)"- >- <div class="access-content--prefix">- <div class="flex gap-x-2 items-center">- <component :is="option.icon" class="h-5 w-5" />- <h2 class="text-md flex">- {{ option.label }}- </h2>- </div>- <span class="text-xs textinfolabel">- {{ option.description }}- </span>- </div>- <div- v-show="option.value === currentAccess.value"- class="access-content--suffix flex items-center"- >- <heroicons-solid:check class="h-5 w-5" />- </div>- </div>- </div>- </NPopover>- </section>- <NInputGroup class="flex items-center justify-center">- <NInputGroupLabel>- <div- class="w-full h-full flex flex-row items-center justify-center m-auto"- >- <heroicons-solid:link class="w-5 h-auto" />- </div>- </NInputGroupLabel>- <NInput :value="sharedTabLink" disabled />- <div class="pl-2">- <CopyButton- quaternary- :text="false"- :size="'medium'"- :content="sharedTabLink"- :disabled="tabStore.currentTab?.status !== 'CLEAN'"- />- </div>- </NInputGroup>- </div>-</template>--<script lang="ts" setup>-import { useClipboard } from "@vueuse/core";-import { LockKeyholeIcon, UsersIcon } from "lucide-vue-next";-import { NInput, NInputGroup, NInputGroupLabel, NPopover } from "naive-ui";-import { computed, h, onMounted, ref, type VNode } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import { CopyButton } from "@/components/v2";-import { SQL_EDITOR_WORKSHEET_MODULE } from "@/router/sqlEditor";-import {- pushNotification,- useActuatorV1Store,- useCurrentUserV1,- useSQLEditorTabStore,- useWorkSheetStore,-} from "@/store";-import {- type Worksheet,- Worksheet_Visibility,-} from "@/types/proto-es/v1/worksheet_service_pb";-import { extractProjectResourceName, extractWorksheetID } from "@/utils";--type AccessOption = {- label: string;- description: string;- value: Worksheet_Visibility;- icon: VNode;-};--const props = defineProps<{- worksheet?: Worksheet;-}>();--const emit = defineEmits<{- (event: "on-updated"): void;-}>();--const { t } = useI18n();--const router = useRouter();-const tabStore = useSQLEditorTabStore();-const worksheetV1Store = useWorkSheetStore();-const me = useCurrentUserV1();--const { copy: copyTextToClipboard, isSupported } = useClipboard({- legacy: true,-});--const workspaceExternalURL = computed(- () => useActuatorV1Store().serverInfo?.externalUrl-);--const accessOptions = computed<AccessOption[]>(() => {- return [- {- label: t("sql-editor.private"),- value: Worksheet_Visibility.PRIVATE,- description: t("sql-editor.private-desc"),- icon: h(LockKeyholeIcon),- },- {- label: t("sql-editor.project-read"),- value: Worksheet_Visibility.PROJECT_READ,- description: t("sql-editor.project-read-desc"),- icon: h(UsersIcon),- },- {- label: t("sql-editor.project-write"),- value: Worksheet_Visibility.PROJECT_WRITE,- description: t("sql-editor.project-write-desc"),- icon: h(UsersIcon),- },- ];-});--const allowChangeAccess = computed(() => {- return props.worksheet?.creator === `users/${me.value.email}`;-});--const currentAccess = ref<AccessOption>(accessOptions.value[0]);-const isShowAccessPopover = ref(false);--const handleChangeAccess = async (option: AccessOption) => {- // only creator can change access- if (allowChangeAccess.value && props.worksheet) {- currentAccess.value = option;- await worksheetV1Store.patchWorksheet(- {- ...props.worksheet,- visibility: currentAccess.value.value,- },- ["visibility"]- );-- if (sharedTabLink.value && isSupported.value) {- await copyTextToClipboard(sharedTabLink.value);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("sql-editor.url-copied-to-clipboard"),- });- } else {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- }-- emit("on-updated");- }- isShowAccessPopover.value = false;-};--const sharedTabLink = computed(() => {- if (!props.worksheet) {- return "";- }-- const route = router.resolve({- name: SQL_EDITOR_WORKSHEET_MODULE,- params: {- project: extractProjectResourceName(props.worksheet.project),- sheet: extractWorksheetID(props.worksheet.name),- },- });- return new URL(- route.href,- workspaceExternalURL.value || window.location.origin- ).href;-});--onMounted(() => {- if (props.worksheet) {- const { visibility } = props.worksheet;- const idx = accessOptions.value.findIndex(- (item) => item.value === visibility- );- currentAccess.value =- idx !== -1 ? accessOptions.value[idx] : accessOptions.value[0];- }-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/index.ts b/frontend/src/views/sql-editor/EditorCommon/index.tsindex b382da7b0d..fe6a3c2bab 100644--- a/frontend/src/views/sql-editor/EditorCommon/index.ts+++ b/frontend/src/views/sql-editor/EditorCommon/index.ts@@ -3,14 +3,12 @@ import ExecutingHintModal from "./ExecutingHintModal.vue";import OpenAIButton from "./OpenAIButton/OpenAIButton.vue";import { ResultViewV1 } from "./ResultView";import SaveSheetModal from "./SaveSheetModal.vue";-import SharePopover from "./SharePopover.vue";import SheetConnectionIcon from "./SheetConnectionIcon.vue";export {EditorAction,ExecutingHintModal,SaveSheetModal,- SharePopover,ResultViewV1,SheetConnectionIcon,OpenAIButton,diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vueindex 527bb9aa28..35b5463848 100644--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue@@ -84,21 +84,24 @@ import { NSplit } from "naive-ui";import { storeToRefs } from "pinia";import { computed, defineAsyncComponent, nextTick, ref } from "vue";import { BBSpin } from "@/bbkit";+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";import { useExecuteSQL } from "@/composables/useExecuteSQL";import { AIChatToSQL } from "@/plugins/ai";import ReactPageMount from "@/react/ReactPageMount.vue";import {useConnectionOfCurrentSQLEditorTab,+ useDatabaseV1Store,useSQLEditorTabStore,} from "@/store";import type { SQLEditorQueryParams } from "@/types";-import { instanceV1HasReadonlyMode } from "@/utils";+import { getInstanceResource, instanceV1HasReadonlyMode } from "@/utils";import { useSQLEditorContext } from "../../context";import {EditorAction,ExecutingHintModal,SaveSheetModal,} from "../../EditorCommon";+import { sqlEditorEvents } from "../../events";import ReadonlyModeNotSupported from "../ReadonlyModeNotSupported.vue";import ResultPanel from "../ResultPanel";@@ -129,6 +132,29 @@ const allowReadonlyMode = computed(() => {const { execute } = useExecuteSQL();+useEmitteryEventListener(+ sqlEditorEvents,+ "execute-sql",+ async ({ connection, statement, batchQueryContext }) => {+ const database = await useDatabaseV1Store().getOrFetchDatabaseByName(+ connection.database+ );+ const newTab = tabStore.addTab(+ { connection, statement, batchQueryContext },+ /* beside */ true+ );+ nextTick(() => {+ execute({+ connection: { ...newTab.connection },+ statement,+ engine: getInstanceResource(database).engine,+ explain: false,+ selection: null,+ });+ });+ }+);+const handleExecuteFromActionBar = (params: SQLEditorQueryParams) => {if (!tab.value || !sqlEditorRef.value) {return;diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.tsindex d4e44c3824..5d342b016f 100644--- a/frontend/src/views/sql-editor/context.ts+++ b/frontend/src/views/sql-editor/context.ts@@ -1,35 +1,24 @@-import { create } from "@bufbuild/protobuf";import { watchDebounced } from "@vueuse/core";import Emittery from "emittery";-import { isUndefined } from "lodash-es";-import { type IRange } from "monaco-editor";import { storeToRefs } from "pinia";import type { ComputedRef, InjectionKey, Ref } from "vue";-import { inject, nextTick, provide } from "vue";+import { inject, provide } from "vue";import {pushNotification,- useProjectIamPolicyStore,- useProjectV1Store,- useSQLEditorStore,useSQLEditorTabStore,useSQLEditorUIStore,+ useSQLEditorWorksheetStore,useWorkSheetStore,} from "@/store";import type { SQLEditorTab } from "@/types";-import { isValidDatabaseName, isValidProjectName } from "@/types";import type { GetSchemaStringRequest_ObjectType } from "@/types/proto-es/v1/database_service_pb";-import {- Worksheet_Visibility,- WorksheetSchema,-} from "@/types/proto-es/v1/worksheet_service_pb";-import {- extractWorksheetConnection,- isSimilarDefaultSQLEditorTabTitle,- isWorksheetWritableV1,- NEW_WORKSHEET_TITLE,- suggestedTabTitleForSQLEditorConnection,-} from "@/utils";-import { openWorksheetByName } from "@/views/sql-editor/Sheet";+import { isWorksheetWritableV1 } from "@/utils";+import type { SQLEditorEvents as SQLEditorEventsMap } from "./events";+import { sqlEditorEvents } from "./events";++// Backward-compat alias: consumers typed the events field as Emittery<{...}>.+// Re-export Emittery<SQLEditorEventsMap> under the old name so that no callers need changing.+export type SQLEditorEvents = Emittery<SQLEditorEventsMap>;export const ASIDE_PANEL_TABS = ["SCHEMA",@@ -39,29 +28,6 @@ export const ASIDE_PANEL_TABS = [] as const;export type AsidePanelTab = (typeof ASIDE_PANEL_TABS)[number];-export type SQLEditorEvents = Emittery<{- "save-sheet": {- tab: SQLEditorTab;- editTitle?: boolean;- };- "alter-schema": {- // Format: instances/{instance}/databases/{database}- databaseName: string;- schema: string;- table: string;- };- "format-content": undefined;- "tree-ready": undefined;- "project-context-ready": {- project: string;- };- "set-editor-selection": IRange;- "append-editor-content": { content: string; select: boolean };- "insert-at-caret": {- content: string;- };-}>;-export type SQLEditorContext = {asidePanelTab: Ref<AsidePanelTab>;showConnectionPanel: Ref<boolean>;@@ -118,12 +84,10 @@ export const useSQLEditorContext = () => {};export const provideSQLEditorContext = () => {- const editorStore = useSQLEditorStore();const tabStore = useSQLEditorTabStore();- const projectStore = useProjectV1Store();- const projectIamPolicyStore = useProjectIamPolicyStore();const worksheetStore = useWorkSheetStore();const uiStore = useSQLEditorUIStore();+ const sqlEditorWorksheetStore = useSQLEditorWorksheetStore();const {asidePanelTab,showConnectionPanel,@@ -134,160 +98,6 @@ export const provideSQLEditorContext = () => {editorPanelSize,} = storeToRefs(uiStore);- const maybeUpdateWorksheet = async ({- tabId,- worksheet,- title,- database,- statement,- folders,- signal,- }: {- tabId: string;- worksheet?: string;- title?: string;- database: string;- statement: string;- folders?: string[];- signal?: AbortSignal;- }) => {- const connection = await extractWorksheetConnection({ database });- let worksheetTitle = title ?? "";- if (isSimilarDefaultSQLEditorTabTitle(worksheetTitle)) {- worksheetTitle = suggestedTabTitleForSQLEditorConnection(connection);- }-- if (worksheet) {- const currentSheet = worksheetStore.getWorksheetByName(worksheet);- if (!currentSheet) {- return;- }- if (!isSimilarDefaultSQLEditorTabTitle(currentSheet.title)) {- worksheetTitle = currentSheet.title;- }-- const updated = await worksheetStore.patchWorksheet(- {- ...currentSheet,- title: worksheetTitle,- database,- content: new TextEncoder().encode(statement),- },- ["title", "database", "content"],- signal- );- if (!updated) {- return;- }- if (!isUndefined(folders)) {- await worksheetStore.upsertWorksheetOrganizer(- {- worksheet: updated.name,- folders: folders,- },- ["folders"]- );- }- }-- return tabStore.updateTab(tabId, {- status: "CLEAN",- connection,- title: worksheetTitle,- worksheet,- });- };-- const createWorksheet = async ({- tabId,- title,- statement = "",- folders = [],- database = "",- }: {- tabId?: string;- title?: string;- statement?: string;- folders?: string[];- database?: string;- }) => {- let worksheetTitle = title || NEW_WORKSHEET_TITLE;- const connection = await extractWorksheetConnection({ database });- if (!title && isValidDatabaseName(database)) {- worksheetTitle = suggestedTabTitleForSQLEditorConnection(connection);- }-- const newWorksheet = await worksheetStore.createWorksheet(- create(WorksheetSchema, {- title: worksheetTitle,- database,- content: new TextEncoder().encode(statement),- project: editorStore.project,- visibility: Worksheet_Visibility.PRIVATE,- })- );-- if (folders.length > 0) {- await worksheetStore.upsertWorksheetOrganizer(- {- worksheet: newWorksheet.name,- folders: folders,- },- ["folders"]- );- }-- if (tabId) {- return tabStore.updateTab(tabId, {- status: "CLEAN",- title: worksheetTitle,- statement,- connection,- worksheet: newWorksheet.name,- });- } else {- const tab = await openWorksheetByName({- worksheet: newWorksheet.name,- forceNewTab: true,- });- nextTick(() => {- if (tab && !tab.connection?.database) {- showConnectionPanel.value = true;- }- });- return tab;- }- };-- const maybeSwitchProject = async (projectName: string) => {- editorStore.projectContextReady = false;- try {- if (!isValidProjectName(projectName)) {- return;- }- const project = await projectStore.getOrFetchProjectByName(projectName);- // Fetch IAM policy to ensure permission checks work correctly- await projectIamPolicyStore.getOrFetchProjectIamPolicy(project.name);- editorStore.setProject(project.name);- context.events.emit("project-context-ready", { project: project.name });- return project.name;- } catch {- // Nothing- } finally {- editorStore.projectContextReady = true;- }- };-- // Auto-save abort controller - allows manual save to cancel in-progress auto-save- let autoSaveController: AbortController | null = null;-- const abortAutoSave = () => {- if (autoSaveController) {- autoSaveController.abort();- autoSaveController = null;- }- };-const context: SQLEditorContext = {asidePanelTab,showConnectionPanel,@@ -296,13 +106,13 @@ export const provideSQLEditorContext = () => {schemaViewer,pendingInsertAtCaret,highlightAccessGrantName,- events: new Emittery(),+ events: sqlEditorEvents,- maybeSwitchProject,+ maybeSwitchProject: sqlEditorWorksheetStore.maybeSwitchProject,handleEditorPanelResize: uiStore.handleEditorPanelResize,- createWorksheet,- maybeUpdateWorksheet,- abortAutoSave,+ createWorksheet: sqlEditorWorksheetStore.createWorksheet,+ maybeUpdateWorksheet: sqlEditorWorksheetStore.maybeUpdateWorksheet,+ abortAutoSave: sqlEditorWorksheetStore.abortAutoSave,};// Auto-saving for current tab.@@ -374,14 +184,15 @@ export const provideSQLEditorContext = () => {}// Abort any in-progress auto-save before starting a new one- abortAutoSave();+ sqlEditorWorksheetStore.abortAutoSave();// Capture the statement and tab id before async operationconst statementToSave = tab.statement;const tabId = tab.id;// Create new abort controller for this auto-save- autoSaveController = new AbortController();+ const controller = new AbortController();+ sqlEditorWorksheetStore.autoSaveController = controller;// Set status to SAVINGtabStore.updateTab(tabId, { status: "SAVING" });@@ -390,12 +201,12 @@ export const provideSQLEditorContext = () => {try {// the maybeUpdateWorksheet will set status to CLEAN- await maybeUpdateWorksheet({+ await sqlEditorWorksheetStore.maybeUpdateWorksheet({tabId,worksheet: tab.worksheet,database: tab.connection.database,statement: statementToSave,- signal: autoSaveController.signal,+ signal: controller.signal,});} catch (error) {// Don't handle aborted requests - a newer save or manual save took priority@@ -415,7 +226,7 @@ export const provideSQLEditorContext = () => {description: error instanceof Error ? error.message : "Unknown error",});} finally {- autoSaveController = null;+ sqlEditorWorksheetStore.autoSaveController = null;// Skip for aborted requests - manual save or newer auto-save took priorityif (wasAborted) {diff --git a/frontend/src/views/sql-editor/events.test.ts b/frontend/src/views/sql-editor/events.test.tsnew file mode 100644index 0000000000..91aca11ce2--- /dev/null+++ b/frontend/src/views/sql-editor/events.test.ts@@ -0,0 +1,19 @@+import Emittery from "emittery";+import { describe, expect, test, vi } from "vitest";+import { sqlEditorEvents } from "./events";++describe("sqlEditorEvents", () => {+ test("singleton exists and is an Emittery instance", () => {+ expect(sqlEditorEvents).toBeInstanceOf(Emittery);+ });++ test("emit + on roundtrip works", async () => {+ const handler = vi.fn();+ const unsubscribe = sqlEditorEvents.on("format-content", handler);++ await sqlEditorEvents.emit("format-content", undefined);++ expect(handler).toHaveBeenCalledTimes(1);+ unsubscribe();+ });+});diff --git a/frontend/src/views/sql-editor/events.ts b/frontend/src/views/sql-editor/events.tsnew file mode 100644index 0000000000..6f12f21c03--- /dev/null+++ b/frontend/src/views/sql-editor/events.ts@@ -0,0 +1,26 @@+import Emittery from "emittery";+import type { IRange } from "monaco-editor";+import type {+ BatchQueryContext,+ SQLEditorConnection,+ SQLEditorTab,+} from "@/types";++export type SQLEditorEvents = {+ "save-sheet": { tab: SQLEditorTab; editTitle?: boolean };+ "alter-schema": { databaseName: string; schema: string; table: string };+ "execute-sql": {+ connection: SQLEditorConnection;+ statement: string;+ batchQueryContext?: BatchQueryContext;+ };+ "format-content": undefined;+ "tree-ready": undefined;+ "project-context-ready": { project: string };+ "set-editor-selection": IRange;+ "append-editor-content": { content: string; select: boolean };+ "insert-at-caret": { content: string };+};++export const sqlEditorEvents: Emittery<SQLEditorEvents> =+ new Emittery<SQLEditorEvents>();