SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(query-builder): fieldContext prefixed key suggestions (#12200)
Aditya Singh7ac6df6fb0e9
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsxindex 599d976e98..776fe4de35 100644--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx@@ -52,6 +52,8 @@ import type { SignalType } from 'types/api/v5/queryRange';import { queryExamples, SUGGESTIONS_SECTION } from './constants';import {combineInitialAndUserExpression,+ dedupeOptionsByLabel,+ getFieldContextPrefix,getRecentOptions,renderRecentDeleteButton,} from './utils';@@ -222,6 +224,12 @@ function QuerySearch({QueryKeyDataSuggestionsProps[] | null>(null);+ // dedupe keySuggestions by label/name+ const dedupedKeySuggestions = useMemo(+ () => dedupeOptionsByLabel(keySuggestions || []),+ [keySuggestions],+ );+const [showExamples] = useState(false);const [cursorPos, setCursorPos] = useState({ line: 0, ch: 0 });@@ -246,9 +254,11 @@ function QuerySearch({[key: string]: QueryKeyDataSuggestionsProps[];}): any[] =>Object.values(keys).flatMap((items: QueryKeyDataSuggestionsProps[]) =>- items.map(({ name, fieldDataType }) => ({+ items.map(({ name, fieldDataType, fieldContext }) => ({label: name,type: fieldDataType === 'string' ? 'keyword' : fieldDataType,+ fieldContext,+ fieldDataType,info: '',details: '',})),@@ -307,13 +317,17 @@ function QuerySearch({if (response.data.data) {const { keys } = response.data.data;const options = generateOptions(keys);- // Use a Map to deduplicate by label and preserve order: new options take precedence+ // Deduplicate by full variant identity (name + context + data type), NOT by+ // label. deduping by label removes varient which is not expected. If we need+ // to dedupe by label use dedupedKeySuggestions not dedupe the source itself+ const variantId = (opt: QueryKeyDataSuggestionsProps): string =>+ `${opt.label}|${opt.fieldContext ?? ''}|${opt.fieldDataType ?? ''}`;const merged = new Map<string, QueryKeyDataSuggestionsProps>();- options.forEach((opt) => merged.set(opt.label, opt));+ options.forEach((opt) => merged.set(variantId(opt), opt));if (searchText && lastKeyRef.current !== searchText) {(keySuggestions || []).forEach((opt) => {- if (!merged.has(opt.label)) {- merged.set(opt.label, opt);+ if (!merged.has(variantId(opt))) {+ merged.set(variantId(opt), opt);}});}@@ -919,8 +933,55 @@ function QuerySearch({if (queryContext.isInKey) {const searchText = word?.text.toLowerCase().trim() ?? '';+ const fieldContextMatch = getFieldContextPrefix(searchText);++ if (fieldContextMatch) {+ const { context: fieldContext, remainder } = fieldContextMatch;++ // Fetch the context's page when the prefix is typed exactly eg.("attribute.")+ if (remainder === '' && lastFetchedKeyRef.current !== searchText) {+ debouncedFetchKeySuggestions(searchText);+ }++ //suggestions that actually do start with <fieldContext>.+ const nameMatches = (keySuggestions || [])+ .filter((option) => option.label.toLowerCase().includes(searchText))+ .map((option) => ({ ...option, boost: 100 }));++ //suggestions which do not start with the prefix but qualifies for suggestion+ const contextQualified = (keySuggestions || [])+ .filter(+ (option) =>+ option.fieldContext === fieldContext &&+ option.label.toLowerCase().includes(remainder),+ )+ .map((option) => ({+ ...option,+ label: `${fieldContext}.${option.label}`,+ boost: 0,+ }));++ const contextOptions = dedupeOptionsByLabel([+ ...nameMatches,+ ...contextQualified,+ ]);- options = (keySuggestions || []).filter((option) =>+ // If contextOptions is empty fetch again.+ if (+ contextOptions.length === 0 &&+ lastFetchedKeyRef.current !== searchText+ ) {+ debouncedFetchKeySuggestions(searchText);+ }++ return {+ from: word?.from ?? 0,+ to: word?.to ?? cursorPos.ch,+ options: addSpaceToOptions(contextOptions),+ };+ }++ options = dedupedKeySuggestions.filter((option) =>option.label.toLowerCase().includes(searchText),);@@ -969,9 +1030,26 @@ function QuerySearch({// If we have a key context, add that info to the operator suggestionsif (keyName) {- // Find the key details from suggestions- const keyDetails = (keySuggestions || []).find((k) => k.label === keyName);- const keyType = keyDetails?.type || '';+ const keyContextMatch = getFieldContextPrefix(keyName);+ // key-suggestion can contain multiple variants of a single key+ // In variants we capture ones that match the label to typed keyName exactly or,+ // if it has a prefix fieldContext remove it and then match.+ const variants = (keySuggestions || []).filter(+ (k) =>+ k.label === keyName ||+ (keyContextMatch !== null &&+ k.fieldContext === keyContextMatch.context &&+ k.label === keyContextMatch.remainder),+ );+ const variantTypes = new Set(+ variants+ .map((k) =>+ k.type === 'keyword' ? QUERY_BUILDER_KEY_TYPES.STRING : k.type,+ )+ .filter(Boolean),+ );+ //if there are multi-variant, show all suggestions else just the one+ const keyType = variantTypes.size === 1 ? [...variantTypes][0] : '';// Filter operators based on key typeif (keyType) {@@ -1214,7 +1292,7 @@ function QuerySearch({if (curChar === '(') {// In expression context, suggest keys, functions, or nested parenthesesoptions = [- ...(keySuggestions || []),+ ...dedupedKeySuggestions,{ label: '(', type: 'parenthesis', info: 'Open nested group' },{ label: 'NOT', type: 'operator', info: 'Negate expression' },...options.filter((opt) => opt.type === 'function'),diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/__tests__/utils.test.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/__tests__/utils.test.tsnew file mode 100644index 0000000000..82b91fd47b--- /dev/null+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/__tests__/utils.test.ts@@ -0,0 +1,120 @@+import {+ combineInitialAndUserExpression,+ dedupeOptionsByLabel,+ getFieldContextPrefix,+ getUserExpressionFromCombined,+} from '../utils';++describe('entityLogsExpression', () => {+ describe('combineInitialAndUserExpression', () => {+ it('returns user when initial is empty', () => {+ expect(combineInitialAndUserExpression('', 'body contains error')).toBe(+ 'body contains error',+ );+ });++ it('returns initial when user is empty', () => {+ expect(combineInitialAndUserExpression('k8s.pod.name = "x"', '')).toBe(+ 'k8s.pod.name = "x"',+ );+ });++ it('wraps user in parentheses with AND', () => {+ expect(+ combineInitialAndUserExpression('k8s.pod.name = "x"', 'body = "a"'),+ ).toBe('k8s.pod.name = "x" AND (body = "a")');+ });+ });++ describe('getUserExpressionFromCombined', () => {+ it('returns empty when combined equals initial', () => {+ expect(+ getUserExpressionFromCombined('k8s.pod.name = "x"', 'k8s.pod.name = "x"'),+ ).toBe('');+ });++ it('extracts user from wrapped form', () => {+ expect(+ getUserExpressionFromCombined(+ 'k8s.pod.name = "x"',+ 'k8s.pod.name = "x" AND (body = "a")',+ ),+ ).toBe('body = "a"');+ });++ it('extracts user from legacy AND without parens', () => {+ expect(+ getUserExpressionFromCombined(+ 'k8s.pod.name = "x"',+ 'k8s.pod.name = "x" AND body = "a"',+ ),+ ).toBe('body = "a"');+ });++ it('returns full combined when initial is empty', () => {+ expect(getUserExpressionFromCombined('', 'service.name = "a"')).toBe(+ 'service.name = "a"',+ );+ });+ });+});++describe('getFieldContextPrefix', () => {+ it('matches a complete context prefix with a remainder', () => {+ expect(getFieldContextPrefix('attribute.status')).toStrictEqual({+ context: 'attribute',+ remainder: 'status',+ });+ });++ it('matches a bare context prefix with empty remainder', () => {+ expect(getFieldContextPrefix('resource.')).toStrictEqual({+ context: 'resource',+ remainder: '',+ });+ });++ it('matches every backend field context', () => {+ ['attribute', 'resource', 'span', 'body', 'log', 'metric'].forEach((ctx) => {+ expect(getFieldContextPrefix(`${ctx}.x`)).toStrictEqual({+ context: ctx,+ remainder: 'x',+ });+ });+ });++ it('does not match a partial context name', () => {+ expect(getFieldContextPrefix('attr')).toBeNull();+ expect(getFieldContextPrefix('attribute')).toBeNull();+ });++ it('does not match a non-context key with dots', () => {+ expect(getFieldContextPrefix('status.code')).toBeNull();+ });++ it('matches context case-insensitively but keeps remainder casing', () => {+ expect(getFieldContextPrefix('Attribute.Status')).toStrictEqual({+ context: 'attribute',+ remainder: 'Status',+ });+ });+});++describe('dedupeOptionsByLabel', () => {+ it('keeps the first occurrence per label, preserving order', () => {+ expect(+ dedupeOptionsByLabel([+ { label: 'status.code', type: 'keyword' },+ { label: 'status.code', type: 'number' },+ { label: 'duration', type: 'number' },+ ]),+ ).toStrictEqual([+ { label: 'status.code', type: 'keyword' },+ { label: 'duration', type: 'number' },+ ]);+ });++ it('returns an empty array for empty input', () => {+ expect(dedupeOptionsByLabel([])).toStrictEqual([]);+ });+});diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/__tests__/utils.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/__tests__/utils.tsdeleted file mode 100644index 482194b5b6..0000000000--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/__tests__/utils.ts+++ /dev/null@@ -1,58 +0,0 @@-import {- combineInitialAndUserExpression,- getUserExpressionFromCombined,-} from '../utils';--describe('entityLogsExpression', () => {- describe('combineInitialAndUserExpression', () => {- it('returns user when initial is empty', () => {- expect(combineInitialAndUserExpression('', 'body contains error')).toBe(- 'body contains error',- );- });-- it('returns initial when user is empty', () => {- expect(combineInitialAndUserExpression('k8s.pod.name = "x"', '')).toBe(- 'k8s.pod.name = "x"',- );- });-- it('wraps user in parentheses with AND', () => {- expect(- combineInitialAndUserExpression('k8s.pod.name = "x"', 'body = "a"'),- ).toBe('k8s.pod.name = "x" AND (body = "a")');- });- });-- describe('getUserExpressionFromCombined', () => {- it('returns empty when combined equals initial', () => {- expect(- getUserExpressionFromCombined('k8s.pod.name = "x"', 'k8s.pod.name = "x"'),- ).toBe('');- });-- it('extracts user from wrapped form', () => {- expect(- getUserExpressionFromCombined(- 'k8s.pod.name = "x"',- 'k8s.pod.name = "x" AND (body = "a")',- ),- ).toBe('body = "a"');- });-- it('extracts user from legacy AND without parens', () => {- expect(- getUserExpressionFromCombined(- 'k8s.pod.name = "x"',- 'k8s.pod.name = "x" AND body = "a"',- ),- ).toBe('body = "a"');- });-- it('returns full combined when initial is empty', () => {- expect(getUserExpressionFromCombined('', 'service.name = "a"')).toBe(- 'service.name = "a"',- );- });- });-});diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/constants.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/constants.tsindex 251ffdceea..a07da15eb2 100644--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/constants.ts+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/constants.ts@@ -1,6 +1,16 @@export const RECENTS_SECTION = { name: 'Recent searches', rank: 1 } as const;export const SUGGESTIONS_SECTION = { name: 'Suggestions', rank: 2 } as const;+// TODO: move to using TelemetrytypesFieldContextDTO when we migrate getKeySuggestions API (Part of https://github.com/SigNoz/engineering-pod/issues/5289)+export const FIELD_CONTEXTS = [+ 'attribute',+ 'resource',+ 'span',+ 'body',+ 'log',+ 'metric',+] as const;+// Custom CodeMirror Completion.type for recent-query entries. Used to discriminate// recents from regular autocomplete completions in renderers and event handlers.export const RECENT_COMPLETION_TYPE = 'recent';diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.tsindex 8705fd3eb1..676e66e0e6 100644--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts@@ -9,11 +9,45 @@ import type { SignalType } from 'types/api/v5/queryRange';import 'utils/timeUtils';import {+ FIELD_CONTEXTS,RECENT_COMPLETION_TYPE,RECENTS_DISPLAY_CAP,RECENTS_SECTION,} from './constants';+export interface FieldContextPrefixMatch {+ context: string;+ remainder: string;+}++// This function checks if the text(query key) starts with a fieldContext+// This util strictly checks that and returns context and remainder back.+// This helps differentiate if the typed key was prefixed with a context or+// was it an actual queryKey like (attribute.abc)+export function getFieldContextPrefix(+ text: string,+): FieldContextPrefixMatch | null {+ const lower = text.toLowerCase();+ const context = FIELD_CONTEXTS.find((ctx) => lower.startsWith(`${ctx}.`));+ return context ? { context, remainder: text.slice(context.length + 1) } : null;+}++// Keeps the first occurrence per label, preserving order. Key suggestions hold+// one entry per (name, fieldContext, fieldDataType) variant; This means query builder+// could show multiple labels and this avoids that.+export function dedupeOptionsByLabel<T extends { label: string }>(+ options: T[],+): T[] {+ const seen = new Set<string>();+ return options.filter((option) => {+ if (seen.has(option.label)) {+ return false;+ }+ seen.add(option.label);+ return true;+ });+}+export function combineInitialAndUserExpression(initial: string,user: string,diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QuerySearch.contextSuggestions.test.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QuerySearch.contextSuggestions.test.tsxnew file mode 100644index 0000000000..f2452cb2d0--- /dev/null+++ b/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QuerySearch.contextSuggestions.test.tsx@@ -0,0 +1,217 @@+import { initialQueriesMap } from 'constants/queryBuilder';+import { rest, server } from 'mocks-server/server';+import { render, userEvent, waitFor } from 'tests/test-utils';+import { DataSource } from 'types/common/queryBuilder';++import QuerySearch from '../QuerySearch/QuerySearch';+import { mockCodeMirrorDomApis } from './codemirrorDomMocks';++const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';+const CM_OPTION_SELECTOR = '.cm-tooltip-autocomplete .cm-completionLabel';++beforeAll(() => {+ mockCodeMirrorDomApis();+});++jest.mock('hooks/useDarkMode', () => ({+ useIsDarkMode: (): boolean => false,+}));++jest.mock('providers/Dashboard/store/useDashboardStore', () => ({+ useDashboardStore: (): { dashboardData: undefined } => ({+ dashboardData: undefined,+ }),+}));++jest.mock('hooks/queryBuilder/useQueryBuilder', () => {+ const handleRunQuery = jest.fn();+ return {+ __esModule: true,+ useQueryBuilder: (): { handleRunQuery: () => void } => ({ handleRunQuery }),+ handleRunQuery,+ };+});++// Keys fixture: status.code exists as 3 variants (attribute string/number ++// resource string); attribute.a.b.c is a key literally named with the prefix.+const KEYS_FIXTURE = {+ 'status.code': [+ {+ name: 'status.code',+ fieldContext: 'attribute',+ fieldDataType: 'string',+ signal: 'logs',+ },+ {+ name: 'status.code',+ fieldContext: 'attribute',+ fieldDataType: 'number',+ signal: 'logs',+ },+ {+ name: 'status.code',+ fieldContext: 'resource',+ fieldDataType: 'string',+ signal: 'logs',+ },+ ],+ 'attribute.a.b.c': [+ {+ name: 'attribute.a.b.c',+ fieldContext: 'attribute',+ fieldDataType: 'string',+ signal: 'logs',+ },+ ],+ 'duration.nano': [+ {+ name: 'duration.nano',+ fieldContext: 'span',+ fieldDataType: 'number',+ signal: 'logs',+ },+ ],+};++const fetchedSearchTexts: string[] = [];++beforeEach(() => {+ fetchedSearchTexts.length = 0;+ server.use(+ rest.get('http://localhost/api/v1/fields/keys', (req, res, ctx) => {+ fetchedSearchTexts.push(req.url.searchParams.get('searchText') ?? '');+ return res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: { complete: true, keys: KEYS_FIXTURE },+ }),+ );+ }),+ rest.get('http://localhost/api/v1/fields/values', (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: { values: { stringValues: [], numberValues: [] } },+ }),+ ),+ ),+ );+});++async function renderAndType(text: string): Promise<HTMLElement> {+ render(+ <QuerySearch+ onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}+ queryData={initialQueriesMap.logs.builder.queryData[0]}+ dataSource={DataSource.LOGS}+ />,+ );++ await waitFor(() => {+ expect(document.querySelector(CM_EDITOR_SELECTOR)).toBeInTheDocument();+ });++ const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;+ await userEvent.click(editor);+ await userEvent.type(editor, text);+ return editor;+}++// Types a key, waits for its suggestion to render (proving the debounced key+// fetch resolved into state), then types a space to enter operator context.+async function typeKeyThenEnterOperatorContext(+ key: string,+ expectedKeyLabel: string,+): Promise<void> {+ const editor = await renderAndType(key);++ await waitFor(() => {+ expect(visibleOptionLabels()).toContain(expectedKeyLabel);+ });++ // skipClick: a click would reset the caret to position 0 under the mocked+ // DOM rects; we need the space appended at the end of the typed key.+ await userEvent.type(editor, ' ', { skipClick: true });++ await waitFor(() => {+ expect(visibleOptionLabels()).toContain('=');+ });+}++function visibleOptionLabels(): string[] {+ return Array.from(document.querySelectorAll(CM_OPTION_SELECTOR)).map(+ (el) => el.textContent ?? '',+ );+}++describe('QuerySearch context-prefixed key suggestions', () => {+ it('shows one deduped suggestion per key name in normal mode', async () => {+ await renderAndType('statu');++ await waitFor(() => {+ expect(visibleOptionLabels()).toContain('status.code');+ });++ const statusOptions = visibleOptionLabels().filter(+ (label) => label === 'status.code',+ );+ expect(statusOptions).toHaveLength(1);+ });++ it('shows context-scoped suggestions for a complete context prefix', async () => {+ await renderAndType('attribute.');++ await waitFor(() => {+ expect(visibleOptionLabels()).toContain('attribute.status.code');+ });++ const labels = visibleOptionLabels();+ // Literal key name match ranks first+ expect(labels[0]).toBe('attribute.a.b.c');+ // Context-qualified form of the literal key is also present+ expect(labels).toContain('attribute.attribute.a.b.c');+ // span-only key is not suggested under attribute.+ expect(labels).not.toContain('attribute.duration.nano');+ });++ it('fetches the context page when the prefix is typed exactly', async () => {+ await renderAndType('attribute.');++ await waitFor(() => {+ expect(fetchedSearchTexts).toContain('attribute.');+ });+ });+});++describe('QuerySearch operator suggestions by key type', () => {+ it('shows all operators for a key with ambiguous types', async () => {+ // status.code is string + number across variants → no type filtering+ await typeKeyThenEnterOperatorContext('status.code', 'status.code');++ const labels = visibleOptionLabels();+ expect(labels).toContain('>');+ expect(labels).toContain('LIKE');+ });++ it('shows numeric operators for a single-type number key', async () => {+ await typeKeyThenEnterOperatorContext('duration.nano', 'duration.nano');++ const labels = visibleOptionLabels();+ expect(labels).toContain('>');+ expect(labels).not.toContain('LIKE');+ });++ it('narrows operators when a context prefix disambiguates the type', async () => {+ // status.code is ambiguous globally, but resource.status.code is string-only+ await typeKeyThenEnterOperatorContext(+ 'resource.status.code',+ 'resource.status.code',+ );++ const labels = visibleOptionLabels();+ expect(labels).toContain('LIKE');+ expect(labels).not.toContain('>');+ });+});diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QuerySearch.test.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QuerySearch.test.tsxindex c08a7c969b..be3e4f72ab 100644--- a/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QuerySearch.test.tsx+++ b/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QuerySearch.test.tsx@@ -8,78 +8,13 @@ import type { QueryKeyDataSuggestionsProps } from 'types/api/querySuggestions/tyimport { DataSource } from 'types/common/queryBuilder';import QuerySearch from '../QuerySearch/QuerySearch';+import { mockCodeMirrorDomApis } from './codemirrorDomMocks';const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';// Mock DOM APIs that CodeMirror needsbeforeAll(() => {- // Mock getClientRects and getBoundingClientRect for Range objects- const mockRect: DOMRect = {- width: 100,- height: 20,- top: 0,- left: 0,- right: 100,- bottom: 20,- x: 0,- y: 0,- toJSON: (): DOMRect => mockRect,- } as DOMRect;-- // Create a minimal Range mock with only what CodeMirror actually uses- const createMockRange = (): Range => {- let startContainer: Node = document.createTextNode('');- let endContainer: Node = document.createTextNode('');- let startOffset = 0;- let endOffset = 0;-- const mockRange = {- // CodeMirror uses these for text measurement- getClientRects: (): DOMRectList =>- ({- length: 1,- item: (index: number): DOMRect | null => (index === 0 ? mockRect : null),- 0: mockRect,- *[Symbol.iterator](): Generator<DOMRect> {- yield mockRect;- },- }) as unknown as DOMRectList,- getBoundingClientRect: (): DOMRect => mockRect,- // CodeMirror calls these to set up text ranges- setStart: (node: Node, offset: number): void => {- startContainer = node;- startOffset = offset;- },- setEnd: (node: Node, offset: number): void => {- endContainer = node;- endOffset = offset;- },- // Minimal Range properties (TypeScript requires these)- get startContainer(): Node {- return startContainer;- },- get endContainer(): Node {- return endContainer;- },- get startOffset(): number {- return startOffset;- },- get endOffset(): number {- return endOffset;- },- get collapsed(): boolean {- return startContainer === endContainer && startOffset === endOffset;- },- commonAncestorContainer: document.body,- };- return mockRange as unknown as Range;- };-- // Mock document.createRange to return a new Range instance each time- document.createRange = (): Range => createMockRange();-- // Mock getBoundingClientRect for elements- Element.prototype.getBoundingClientRect = (): DOMRect => mockRect;+ mockCodeMirrorDomApis();});jest.mock('hooks/useDarkMode', () => ({diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/codemirrorDomMocks.ts b/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/codemirrorDomMocks.tsnew file mode 100644index 0000000000..04595b69fa--- /dev/null+++ b/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/codemirrorDomMocks.ts@@ -0,0 +1,71 @@+// Mocks the DOM measurement APIs CodeMirror needs to render in jsdom+// (Range client rects + element bounding rects). Call from a beforeAll in+// specs that render the real CodeMirror editor.+export function mockCodeMirrorDomApis(): void {+ const mockRect: DOMRect = {+ width: 100,+ height: 20,+ top: 0,+ left: 0,+ right: 100,+ bottom: 20,+ x: 0,+ y: 0,+ toJSON: (): DOMRect => mockRect,+ } as DOMRect;++ // Create a minimal Range mock with only what CodeMirror actually uses+ const createMockRange = (): Range => {+ let startContainer: Node = document.createTextNode('');+ let endContainer: Node = document.createTextNode('');+ let startOffset = 0;+ let endOffset = 0;++ const mockRange = {+ // CodeMirror uses these for text measurement+ getClientRects: (): DOMRectList =>+ ({+ length: 1,+ item: (index: number): DOMRect | null => (index === 0 ? mockRect : null),+ 0: mockRect,+ *[Symbol.iterator](): Generator<DOMRect> {+ yield mockRect;+ },+ }) as unknown as DOMRectList,+ getBoundingClientRect: (): DOMRect => mockRect,+ // CodeMirror calls these to set up text ranges+ setStart: (node: Node, offset: number): void => {+ startContainer = node;+ startOffset = offset;+ },+ setEnd: (node: Node, offset: number): void => {+ endContainer = node;+ endOffset = offset;+ },+ // Minimal Range properties (TypeScript requires these)+ get startContainer(): Node {+ return startContainer;+ },+ get endContainer(): Node {+ return endContainer;+ },+ get startOffset(): number {+ return startOffset;+ },+ get endOffset(): number {+ return endOffset;+ },+ get collapsed(): boolean {+ return startContainer === endContainer && startOffset === endOffset;+ },+ commonAncestorContainer: document.body,+ };+ return mockRange as unknown as Range;+ };++ // Mock document.createRange to return a new Range instance each time+ document.createRange = (): Range => createMockRange();++ // Mock getBoundingClientRect for elements+ Element.prototype.getBoundingClientRect = (): DOMRect => mockRect;+}