Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support search in sql editor result detail drawer (#20755)
ecmadao65629f71675d
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 84790e7294..2da856ba2d 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2878,6 +2878,11 @@"request-export": "Request export","request-jit": "Request just-in-time access","request-query": "Request query",+ "result-detail": {+ "next-match": "Next match",+ "previous-match": "Previous match",+ "search": "Search detail"+ },"result-limit": {"self": "Result limit"},diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 6caaa2eab7..7420cbd972 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2878,6 +2878,11 @@"request-export": "Solicitar exportación","request-jit": "Solicitar acceso just-in-time","request-query": "Solicitar consulta",+ "result-detail": {+ "next-match": "Siguiente coincidencia",+ "previous-match": "Coincidencia anterior",+ "search": "Buscar en detalles"+ },"result-limit": {"self": "Límite de resultados"},diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 3c42e84a88..5c56f3e29a 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2878,6 +2878,11 @@"request-export": "エクスポートをリクエスト","request-jit": "ジャストインタイムアクセスをリクエスト","request-query": "リクエストクエリ",+ "result-detail": {+ "next-match": "次の一致",+ "previous-match": "前の一致",+ "search": "詳細を検索"+ },"result-limit": {"self": "結果の制限"},diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 1542221407..be763cf978 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2878,6 +2878,11 @@"request-export": "Yêu cầu xuất dữ liệu","request-jit": "Yêu cầu truy cập just-in-time","request-query": "Yêu cầu truy vấn",+ "result-detail": {+ "next-match": "Kết quả tiếp theo",+ "previous-match": "Kết quả trước",+ "search": "Tìm trong chi tiết"+ },"result-limit": {"self": "Giới hạn kết quả"},diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 92644de5c1..76be41828f 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2878,6 +2878,11 @@"request-export": "申请导出","request-jit": "申请即时访问","request-query": "请求查询",+ "result-detail": {+ "next-match": "下一个匹配项",+ "previous-match": "上一个匹配项",+ "search": "搜索详情"+ },"result-limit": {"self": "结果限制"},diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsxindex 936d29c701..ce870e0c55 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx@@ -166,8 +166,13 @@ vi.mock("@/react/components/ui/sheet", () => ({{children}</div>),- SheetContent: ({ children }: { children: React.ReactNode }) => (- <div data-testid="sheet-content">{children}</div>+ SheetContent: ({+ children,+ ...props+ }: React.HTMLAttributes<HTMLDivElement> & { children: React.ReactNode }) => (+ <div data-testid="sheet-content" {...props}>+ {children}+ </div>),SheetHeader: ({ children }: { children: React.ReactNode }) => (<div data-testid="sheet-header">{children}</div>@@ -438,6 +443,33 @@ describe("AccessGrantRequestDrawer", () => {unmount();});+ test("clicking the drawer content does not bubble to the component that opened it", () => {+ const onOwnerClick = vi.fn();+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <div onClick={onOwnerClick}>+ <AccessGrantRequestDrawer+ targets={["instances/inst1/databases/mydb"]}+ query="SELECT id FROM orders"+ onClose={onClose}+ />+ </div>+ );+ render();++ const textarea = container.querySelector(+ "[data-testid='textarea']"+ ) as HTMLTextAreaElement;+ expect(textarea).not.toBeNull();++ act(() => {+ textarea.click();+ });++ expect(onOwnerClick).not.toHaveBeenCalled();+ unmount();+ });+test("Submit button disabled when required fields missing", () => {const onClose = vi.fn();const { container, render, unmount } = renderIntoContainer(diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsxindex 0eeeeb98d6..06b23b90a0 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx@@ -2,7 +2,13 @@ import { create } from "@bufbuild/protobuf";import { DurationSchema, TimestampSchema } from "@bufbuild/protobuf/wkt";import dayjs from "dayjs";import { Loader2 } from "lucide-react";-import { useEffect, useMemo, useRef, useState } from "react";+import {+ type SyntheticEvent,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import { useTranslation } from "react-i18next";import { accessGrantServiceClientConnect } from "@/connect";import { DatabaseSelect } from "@/react/components/DatabaseSelect";@@ -476,13 +482,22 @@ export function AccessGrantRequestDrawer({}),[active]);+ const stopDrawerEvent = (event: SyntheticEvent) => {+ event.stopPropagation();+ };return (<Sheet open={true} onOpenChange={(next) => !next && onClose()}>{/* text-main gives the drawer a themed default text color (it portalsoutside the SQL Editor wrapper that sets one), so un-classed text likecheckbox labels and selected values follow the theme. */}- <SheetContent width="standard" style={sheetStyle} className="text-main">+ <SheetContent+ width="standard"+ style={sheetStyle}+ className="text-main"+ onClick={stopDrawerEvent}+ onPointerDown={stopDrawerEvent}+ ><AccessGrantRequestDrawerInnerkey={`${targets?.join(",")}-${query}-${unmask}-${exportResult}`}stableProps={stableProps}diff --git a/frontend/src/react/components/sql-editor/ResultView/DetailPanel.test.tsx b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.test.tsxindex de60a06602..e305658359 100644--- a/frontend/src/react/components/sql-editor/ResultView/DetailPanel.test.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.test.tsx@@ -86,18 +86,22 @@ function SelectCellOnMount() {function TestDetailPanel({disallowCopyingData = false,+ panelRows = rows,+ panelColumns = columns,}: {disallowCopyingData?: boolean;+ panelRows?: ResultTableRow[];+ panelColumns?: ResultTableColumn[];}) {return (<SQLResultViewProviderengine={Engine.POSTGRES}- rows={rows}- columns={columns}+ rows={panelRows}+ columns={panelColumns}disallowCopyingData={disallowCopyingData}><OpenDetailOnMount />- <DetailPanel rows={rows} columns={columns} />+ <DetailPanel rows={panelRows} columns={panelColumns} /></SQLResultViewProvider>);}@@ -133,11 +137,40 @@ const renderIntoContainer = (element: ReactElement) => {};};-const getDetailContentRegion = () => {+const setInputValue = (input: HTMLInputElement, value: string) => {+ const valueSetter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+};++const flushAsyncRender = async () => {+ await act(async () => {+ await new Promise((resolve) => window.setTimeout(resolve, 0));+ });+};++const waitForAssertion = async (assertion: () => void) => {+ let lastError: unknown;+ for (let i = 0; i < 20; i++) {+ await flushAsyncRender();+ try {+ assertion();+ return;+ } catch (err) {+ lastError = err;+ }+ }+ throw lastError;+};++const getDetailContentRegion = (expectedText = "longbridge") => {const candidates = Array.from(document.body.querySelectorAll("div"));const contentRegion = candidates.find((element) =>- element.textContent?.includes("longbridge") &&+ element.textContent?.includes(expectedText) &&element.className.includes("overflow-auto") &&element.className.includes("font-mono"));@@ -228,4 +261,186 @@ describe("DetailPanel", () => {getSelectionSpy.mockRestore();unmount();});++ test("highlights plain text search matches and jumps between them", () => {+ const textRows: ResultTableRow[] = [+ {+ key: 0,+ item: create(QueryRowSchema, {+ values: [textValue("CREATE TABLE users;\nCREATE INDEX users_name;")],+ }),+ },+ ];+ const { render, unmount } = renderIntoContainer(+ <TestDetailPanel panelRows={textRows} />+ );+ render();++ const input = document.body.querySelector(+ "input[aria-label='sql-editor.result-detail.search']"+ ) as HTMLInputElement | null;+ expect(input).toBeInstanceOf(HTMLInputElement);++ act(() => {+ setInputValue(input!, "create");+ });++ const marks = Array.from(+ getDetailContentRegion("CREATE TABLE").querySelectorAll("mark")+ );+ expect(marks.map((mark) => mark.textContent)).toEqual(["CREATE", "CREATE"]);+ expect(document.body.textContent).toContain("1 / 2");+ expect(marks[0]?.className).toContain("bg-accent");+ const searchControl = input!.closest(+ "[data-testid='detail-search-control']"+ );+ expect(searchControl).toBeInstanceOf(HTMLDivElement);+ expect(searchControl?.textContent).toContain("1 / 2");+ expect(searchControl?.querySelectorAll("button")).toHaveLength(3);+ expect(searchControl?.className).toContain("rounded-xs");+ expect(searchControl?.className).toContain("bg-transparent");+ expect(searchControl?.className).not.toContain("rounded-md");+ expect(searchControl?.className).not.toContain("shadow");+ expect(searchControl?.parentElement?.className).not.toContain("flex-1");++ act(() => {+ input!.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "Enter",+ bubbles: true,+ cancelable: true,+ })+ );+ });++ const nextMarks = Array.from(+ getDetailContentRegion("CREATE TABLE").querySelectorAll("mark")+ );+ expect(nextMarks[1]?.className).toContain("bg-accent");++ unmount();+ });++ test("scrolls the active match when the search target changes but match count is unchanged", () => {+ const scrollIntoView = vi.fn();+ const originalScrollIntoView = HTMLElement.prototype.scrollIntoView;+ HTMLElement.prototype.scrollIntoView = scrollIntoView;+ const textRows: ResultTableRow[] = [+ {+ key: 0,+ item: create(QueryRowSchema, {+ values: [textValue("CREATE TABLE users;\nCREATE INDEX users_name;")],+ }),+ },+ ];+ const { render, unmount } = renderIntoContainer(+ <TestDetailPanel panelRows={textRows} />+ );+ render();++ const input = document.body.querySelector(+ "input[aria-label='sql-editor.result-detail.search']"+ ) as HTMLInputElement | null;+ expect(input).toBeInstanceOf(HTMLInputElement);++ act(() => {+ setInputValue(input!, "create");+ });+ expect(scrollIntoView).toHaveBeenCalled();+ scrollIntoView.mockClear();++ act(() => {+ setInputValue(input!, "users");+ });++ expect(document.body.textContent).toContain("1 / 2");+ expect(scrollIntoView).toHaveBeenCalled();++ HTMLElement.prototype.scrollIntoView = originalScrollIntoView;+ unmount();+ });++ test("scrolls formatted JSON matches after the async highlighted render", async () => {+ localStorage.setItem("bb.sql-editor.detail-panel.format", "true");+ const scrolledContent: string[] = [];+ const originalScrollIntoView = HTMLElement.prototype.scrollIntoView;+ HTMLElement.prototype.scrollIntoView = function () {+ scrolledContent.push(+ this.closest(".overflow-auto")?.textContent?.trim() ?? ""+ );+ };+ const jsonRows: ResultTableRow[] = [+ {+ key: 0,+ item: create(QueryRowSchema, {+ values: [+ textValue('{"name":"alpha","first":"needle","second":"needle"}'),+ ],+ }),+ },+ {+ key: 1,+ item: create(QueryRowSchema, {+ values: [+ textValue('{"name":"beta","first":"needle","second":"needle"}'),+ ],+ }),+ },+ ];+ const { render, unmount } = renderIntoContainer(+ <TestDetailPanel panelRows={jsonRows} />+ );+ render();++ const input = document.body.querySelector(+ "input[aria-label='sql-editor.result-detail.search']"+ ) as HTMLInputElement | null;+ expect(input).toBeInstanceOf(HTMLInputElement);++ act(() => {+ setInputValue(input!, "needle");+ });+ await waitForAssertion(() => {+ expect(document.body.textContent).toContain("1 / 2");+ });+ scrolledContent.length = 0;++ act(() => {+ document.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ bubbles: true,+ cancelable: true,+ })+ );+ });+ await waitForAssertion(() => {+ expect(scrolledContent.some((text) => text.includes("beta"))).toBe(true);+ });++ HTMLElement.prototype.scrollIntoView = originalScrollIntoView;+ unmount();+ });++ test("focuses detail search from the native find shortcut", () => {+ const { render, unmount } = renderIntoContainer(<TestDetailPanel />);+ render();++ const event = new KeyboardEvent("keydown", {+ key: "f",+ metaKey: true,+ bubbles: true,+ cancelable: true,+ });+ act(() => {+ document.dispatchEvent(event);+ });++ expect(event.defaultPrevented).toBe(true);+ expect(document.activeElement?.getAttribute("aria-label")).toBe(+ "sql-editor.result-detail.search"+ );++ unmount();+ });});diff --git a/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsxindex 75df5c960a..d832ea9d57 100644--- a/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx@@ -8,11 +8,14 @@ import {ChevronDownIcon,ChevronUpIcon,CopyIcon,+ SearchIcon,WrapTextIcon,+ XIcon,} from "lucide-react";-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";import {Sheet,SheetContent,@@ -29,6 +32,11 @@ import {import { BinaryFormatButton } from "./BinaryFormatButton";import { getPlainValue } from "./cell-value";import { useBinaryFormatContext, useSQLResultViewContext } from "./context";+import {+ DETAIL_SEARCH_ACTIVE_MATCH_SELECTOR,+ renderTextWithSearchMatches,+ searchMatchCountLabel,+} from "./detail-panel-search";import { PrettyJSON } from "./PrettyJSON";import type { ResultTableColumn, ResultTableRow } from "./types";@@ -65,11 +73,30 @@ function useLocalStorageBoolean(return [value, update];}+const isEditableTarget = (target: EventTarget | null) => {+ if (!(target instanceof HTMLElement)) {+ return false;+ }+ const tagName = target.tagName.toLowerCase();+ return (+ tagName === "input" ||+ tagName === "textarea" ||+ target.isContentEditable ||+ target.closest("[contenteditable='true']") !== null+ );+};+export function DetailPanel({ rows, columns }: DetailPanelProps) {const { t } = useTranslation();const { detail, disallowCopyingData, setDetail } = useSQLResultViewContext();const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();const [copied, setCopied] = useState(false);+ const [searchQuery, setSearchQuery] = useState("");+ const [activeMatchIndex, setActiveMatchIndex] = useState(0);+ const [matchCount, setMatchCount] = useState(0);+ const [highlightedContentVersion, setHighlightedContentVersion] = useState(0);+ const searchInputRef = useRef<HTMLInputElement>(null);+ const contentRef = useRef<HTMLDivElement>(null);const [format, setFormat] = useLocalStorageBoolean(STORAGE_KEY_SQL_EDITOR_DETAIL_FORMAT,@@ -119,11 +146,26 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {[detail, totalCount, setDetail]);+ const moveSearchMatch = useCallback(+ (offset: number) => {+ if (matchCount === 0) {+ return;+ }+ setActiveMatchIndex((current) => {+ return (current + offset + matchCount) % matchCount;+ });+ },+ [matchCount]+ );+// Replicates Vue's onKeyStroke("ArrowUp"/"ArrowDown") row navigation while// the panel is open.useEffect(() => {if (!detail) return;const handler = (e: KeyboardEvent) => {+ if (isEditableTarget(e.target)) {+ return;+ }if (e.key === "ArrowUp") {e.preventDefault();e.stopPropagation();@@ -138,6 +180,50 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {return () => document.removeEventListener("keydown", handler);}, [detail, move]);+ useEffect(() => {+ if (!detail) return;+ const handler = (e: KeyboardEvent) => {+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "f") {+ e.preventDefault();+ e.stopPropagation();+ searchInputRef.current?.focus();+ searchInputRef.current?.select();+ }+ };+ document.addEventListener("keydown", handler);+ return () => document.removeEventListener("keydown", handler);+ }, [detail]);++ useEffect(() => {+ setActiveMatchIndex(0);+ }, [content, format, searchQuery]);++ useEffect(() => {+ if (matchCount === 0) {+ setActiveMatchIndex(0);+ return;+ }+ if (activeMatchIndex >= matchCount) {+ setActiveMatchIndex(matchCount - 1);+ }+ }, [activeMatchIndex, content, format, matchCount, searchQuery]);++ useEffect(() => {+ const activeMatch = contentRef.current?.querySelector(+ DETAIL_SEARCH_ACTIVE_MATCH_SELECTOR+ );+ if (activeMatch instanceof HTMLElement) {+ activeMatch.scrollIntoView?.({ block: "center", inline: "nearest" });+ }+ }, [+ activeMatchIndex,+ content,+ format,+ highlightedContentVersion,+ matchCount,+ searchQuery,+ ]);+const copyContent = useMemo(() => {const raw = content ?? "";if (guessedIsJSON && format) {@@ -172,6 +258,37 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {}};+ const plainSearchResult = useMemo(+ () =>+ renderTextWithSearchMatches(content ?? "", searchQuery, activeMatchIndex),+ [activeMatchIndex, content, searchQuery]+ );++ const handleHighlightedContentChange = useCallback(() => {+ setHighlightedContentVersion((version) => version + 1);+ }, []);++ useEffect(() => {+ if (!(guessedIsJSON && format)) {+ setMatchCount(plainSearchResult.count);+ }+ }, [format, guessedIsJSON, plainSearchResult.count]);++ const handleSearchKeyDown = (+ event: React.KeyboardEvent<HTMLInputElement>+ ) => {+ if (event.key !== "Enter") {+ return;+ }+ event.preventDefault();+ moveSearchMatch(event.shiftKey ? -1 : 1);+ };++ const clearSearch = () => {+ setSearchQuery("");+ searchInputRef.current?.focus();+ };+return (<Sheet open={isOpen} onOpenChange={handleOpenChange}><SheetContent width="standard">@@ -227,53 +344,121 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {</div></div>- <div className="flex items-center gap-1">- {guessedIsJSON && (- <Tooltip content={t("sql-editor.format")}>- <Button- size="sm"- variant={format ? "default" : "outline"}- className="h-7 px-1.5"- onClick={() => setFormat(!format)}- >- <BracesIcon className="size-4" />- </Button>- </Tooltip>- )}-- {isBinaryData && (- <BinaryFormatButton- format={binaryFormat}- onFormatChange={(next) =>- setBinaryFormat({- rowIndex: detail.row,- colIndex: detail.col,- format: next,- })- }+ <div className="flex min-w-0 items-center gap-x-2">+ <div+ data-testid="detail-search-control"+ className={cn(+ "h-8 w-80 min-w-0 flex items-center overflow-hidden rounded-xs",+ "border border-control-border bg-transparent text-main transition-colors"+ )}+ >+ <SearchIcon className="ml-2.5 size-4 shrink-0 text-control-placeholder" />+ <Input+ ref={searchInputRef}+ size="sm"+ aria-label={t("sql-editor.result-detail.search")}+ className="h-7 min-w-0 flex-1 border-0 px-2 text-sm focus:ring-0"+ placeholder={t("sql-editor.result-detail.search")}+ value={searchQuery}+ onChange={(event) => setSearchQuery(event.target.value)}+ onKeyDown={handleSearchKeyDown}/>- )}-- {!disallowCopyingData && (- <Tooltip content={t("common.copy")}>- <Button- size="sm"- variant="ghost"- className="size-7 p-0"- onClick={handleCopy}- >- {copied ? (- <CheckIcon className="size-4" />- ) : (- <CopyIcon className="size-4" />- )}- </Button>- </Tooltip>- )}+ {searchQuery.trim() && (+ <span className="min-w-10 text-center text-xs text-control-light">+ {searchMatchCountLabel(activeMatchIndex, matchCount)}+ </span>+ )}+ {searchQuery.trim() && (+ <div className="ml-1 flex shrink-0 items-center">+ <Tooltip+ content={t("sql-editor.result-detail.previous-match")}+ >+ <Button+ size="sm"+ variant="ghost"+ className="size-7 p-0"+ disabled={matchCount === 0}+ onClick={() => moveSearchMatch(-1)}+ >+ <ChevronUpIcon className="size-4" />+ </Button>+ </Tooltip>+ <Tooltip+ content={t("sql-editor.result-detail.next-match")}+ >+ <Button+ size="sm"+ variant="ghost"+ className="size-7 p-0"+ disabled={matchCount === 0}+ onClick={() => moveSearchMatch(1)}+ >+ <ChevronDownIcon className="size-4" />+ </Button>+ </Tooltip>+ <Tooltip content={t("common.close")}>+ <Button+ size="sm"+ variant="ghost"+ className="size-7 border-l border-control-border p-0"+ onClick={clearSearch}+ >+ <XIcon className="size-4" />+ </Button>+ </Tooltip>+ </div>+ )}+ </div>++ <div className="flex shrink-0 items-center gap-1">+ {guessedIsJSON && (+ <Tooltip content={t("sql-editor.format")}>+ <Button+ size="sm"+ variant={format ? "default" : "outline"}+ className="h-7 px-1.5"+ onClick={() => setFormat(!format)}+ >+ <BracesIcon className="size-4" />+ </Button>+ </Tooltip>+ )}++ {isBinaryData && (+ <BinaryFormatButton+ format={binaryFormat}+ onFormatChange={(next) =>+ setBinaryFormat({+ rowIndex: detail.row,+ colIndex: detail.col,+ format: next,+ })+ }+ />+ )}++ {!disallowCopyingData && (+ <Tooltip content={t("common.copy")}>+ <Button+ size="sm"+ variant="ghost"+ className="size-7 p-0"+ onClick={handleCopy}+ >+ {copied ? (+ <CheckIcon className="size-4" />+ ) : (+ <CopyIcon className="size-4" />+ )}+ </Button>+ </Tooltip>+ )}+ </div></div></div><div+ ref={contentRef}className={cn("flex-1 overflow-auto text-sm font-mono border p-2 relative",disallowCopyingData ? "select-none" : "select-text",@@ -297,10 +482,16 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {</Button></Tooltip></div>- <PrettyJSON content={content ?? ""} />+ <PrettyJSON+ content={content ?? ""}+ searchQuery={searchQuery}+ activeMatchIndex={activeMatchIndex}+ onMatchCountChange={setMatchCount}+ onHighlightedContentChange={handleHighlightedContentChange}+ /></>) : content && content.length > 0 ? (- <>{content}</>+ <>{plainSearchResult.nodes}</>) : (<br style={{ minWidth: "1rem", display: "inline-flex" }} />)}diff --git a/frontend/src/react/components/sql-editor/ResultView/PrettyJSON.tsx b/frontend/src/react/components/sql-editor/ResultView/PrettyJSON.tsxindex b4f53ffde0..c050362a58 100644--- a/frontend/src/react/components/sql-editor/ResultView/PrettyJSON.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/PrettyJSON.tsx@@ -1,8 +1,13 @@import { escape } from "lodash-es";-import { useEffect, useState } from "react";+import { useEffect, useLayoutEffect, useState } from "react";+import { highlightHtmlText } from "./detail-panel-search";interface PrettyJSONProps {content: string;+ searchQuery?: string;+ activeMatchIndex?: number;+ onMatchCountChange?: (count: number) => void;+ onHighlightedContentChange?: () => void;}/**@@ -11,7 +16,13 @@ interface PrettyJSONProps {* for them eagerly. An AbortController per `content` prevents the* older pretty-print result from racing in after a quick switch.*/-export function PrettyJSON({ content }: PrettyJSONProps) {+export function PrettyJSON({+ content,+ searchQuery = "",+ activeMatchIndex = 0,+ onMatchCountChange,+ onHighlightedContentChange,+}: Readonly<PrettyJSONProps>) {const [html, setHtml] = useState<string>("");useEffect(() => {@@ -40,5 +51,15 @@ export function PrettyJSON({ content }: PrettyJSONProps) {return () => controller.abort();}, [content]);- return <div dangerouslySetInnerHTML={{ __html: html }} />;+ const highlighted = highlightHtmlText(html, searchQuery, activeMatchIndex);++ useEffect(() => {+ onMatchCountChange?.(highlighted.count);+ }, [highlighted.count, onMatchCountChange]);++ useLayoutEffect(() => {+ onHighlightedContentChange?.();+ }, [highlighted.html, onHighlightedContentChange]);++ return <div dangerouslySetInnerHTML={{ __html: highlighted.html }} />;}diff --git a/frontend/src/react/components/sql-editor/ResultView/detail-panel-search.test.tsx b/frontend/src/react/components/sql-editor/ResultView/detail-panel-search.test.tsxnew file mode 100644index 0000000000..fca8e7095c--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/detail-panel-search.test.tsx@@ -0,0 +1,18 @@+import { describe, expect, test } from "vitest";+import { highlightHtmlText } from "./detail-panel-search";++describe("detail panel search", () => {+ test("highlights matches inside generated HTML without removing token markup", () => {+ const result = highlightHtmlText(+ '<span class="json-key">"raw_dump"</span>: <span class="json-string">"CREATE TABLE users"</span>',+ "create",+ 0+ );++ expect(result.count).toBe(1);+ expect(result.html).toContain('class="json-key"');+ expect(result.html).toContain('class="json-string"');+ expect(result.html).toContain("<mark");+ expect(result.html).toContain("CREATE");+ });+});diff --git a/frontend/src/react/components/sql-editor/ResultView/detail-panel-search.tsx b/frontend/src/react/components/sql-editor/ResultView/detail-panel-search.tsxnew file mode 100644index 0000000000..ba79c56d82--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/detail-panel-search.tsx@@ -0,0 +1,142 @@+import type { ReactNode } from "react";+import { Fragment } from "react";++export const DETAIL_SEARCH_ACTIVE_MATCH_SELECTOR =+ "[data-detail-search-active-match='true']";++const matchClassName =+ "rounded-[2px] px-0.5 bg-warning-bg text-main data-[detail-search-active-match=true]:bg-accent data-[detail-search-active-match=true]:text-accent-text";++export const normalizeSearchQuery = (query: string) => query.trim();++export const findTextMatches = (content: string, query: string) => {+ const normalizedQuery = normalizeSearchQuery(query);+ if (!normalizedQuery) {+ return [];+ }++ const matches: Array<{ start: number; end: number }> = [];+ const lowerContent = content.toLocaleLowerCase();+ const lowerQuery = normalizedQuery.toLocaleLowerCase();+ let index = lowerContent.indexOf(lowerQuery);+ while (index >= 0) {+ matches.push({ start: index, end: index + normalizedQuery.length });+ index = lowerContent.indexOf(lowerQuery, index + normalizedQuery.length);+ }+ return matches;+};++export function renderTextWithSearchMatches(+ content: string,+ query: string,+ activeIndex: number+): { nodes: ReactNode; count: number } {+ const matches = findTextMatches(content, query);+ if (matches.length === 0) {+ return { nodes: content, count: 0 };+ }++ const nodes: ReactNode[] = [];+ let cursor = 0;+ for (const [index, match] of matches.entries()) {+ if (match.start > cursor) {+ nodes.push(+ <Fragment key={`text-${cursor}`}>+ {content.slice(cursor, match.start)}+ </Fragment>+ );+ }+ nodes.push(+ <mark+ key={`match-${match.start}`}+ data-detail-search-match+ data-detail-search-active-match={+ index === activeIndex ? "true" : "false"+ }+ className={matchClassName}+ >+ {content.slice(match.start, match.end)}+ </mark>+ );+ cursor = match.end;+ }+ if (cursor < content.length) {+ nodes.push(+ <Fragment key={`text-${cursor}`}>{content.slice(cursor)}</Fragment>+ );+ }++ return { nodes, count: matches.length };+}++const getTextNodes = (root: Node) => {+ const nodes: Text[] = [];+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ let current = walker.nextNode();+ while (current) {+ nodes.push(current as Text);+ current = walker.nextNode();+ }+ return nodes;+};++export function highlightHtmlText(+ html: string,+ query: string,+ activeIndex: number+): { html: string; count: number } {+ const normalizedQuery = normalizeSearchQuery(query);+ if (!normalizedQuery) {+ return { html, count: 0 };+ }++ const container = document.createElement("div");+ container.innerHTML = html;+ const textNodes = getTextNodes(container);+ const text = textNodes.map((node) => node.data).join("");+ const matches = findTextMatches(text, normalizedQuery);+ if (matches.length === 0) {+ return { html, count: 0 };+ }++ const textNodeRanges = [];+ let offset = 0;+ for (const node of textNodes) {+ textNodeRanges.push({+ node,+ start: offset,+ end: offset + node.data.length,+ });+ offset += node.data.length;+ }++ for (let matchIndex = matches.length - 1; matchIndex >= 0; matchIndex--) {+ const match = matches[matchIndex];+ const affectedRanges = textNodeRanges.filter(+ (range) => range.start < match.end && range.end > match.start+ );+ for (let index = affectedRanges.length - 1; index >= 0; index--) {+ const range = affectedRanges[index];+ const start = Math.max(match.start, range.start) - range.start;+ const end = Math.min(match.end, range.end) - range.start;+ const mark = document.createElement("mark");+ mark.dataset.detailSearchMatch = "";+ mark.dataset.detailSearchActiveMatch =+ matchIndex === activeIndex && index === 0 ? "true" : "false";+ mark.className = matchClassName;+ const highlighted = range.node.splitText(start);+ highlighted.splitText(end - start);+ mark.textContent = highlighted.data;+ highlighted.replaceWith(mark);+ }+ }++ return { html: container.innerHTML, count: matches.length };+}++export function searchMatchCountLabel(activeIndex: number, count: number) {+ if (count === 0) {+ return "0 / 0";+ }+ return `${activeIndex + 1} / ${count}`;+}