plugin-elastic-report 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/client-v2.d.ts +2 -2
  2. package/client-v2.js +1 -1
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/{ai → dist/ai}/skills/elastic-report/SKILLS.md +52 -34
  6. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  7. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +2 -1
  10. package/dist/locale/en-US.json +213 -198
  11. package/dist/locale/vi-VN.json +213 -198
  12. package/dist/locale/zh-CN.json +213 -198
  13. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  14. package/dist/server/mcp/ElasticReportToolCatalog.js +6 -4
  15. package/dist/server/plugin.js +4 -4
  16. package/dist/server/report-block-tools.js +340 -0
  17. package/dist/server/services/ElasticReportService.js +12 -6
  18. package/dist/shared/constants.js +9 -0
  19. package/package.json +2 -3
  20. package/server.d.ts +2 -2
  21. package/server.js +1 -1
  22. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  23. package/src/client/index.tsx +34 -34
  24. package/src/client/workflow-instructions.tsx +44 -44
  25. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -791
  26. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -178
  27. package/src/client-v2/api.ts +320 -320
  28. package/src/client-v2/bus/DashboardFilterBus.ts +212 -212
  29. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -652
  30. package/src/client-v2/components/ElasticFilterBar.tsx +372 -372
  31. package/src/client-v2/components/ElasticKqlInput.tsx +421 -421
  32. package/src/client-v2/components/ElasticReportBlock.tsx +306 -306
  33. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -1257
  34. package/src/client-v2/components/HighlightText.tsx +50 -50
  35. package/src/client-v2/components/ReportSelect.tsx +85 -85
  36. package/src/client-v2/index.tsx +14 -14
  37. package/src/client-v2/locale.ts +23 -23
  38. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -115
  39. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -118
  40. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1453
  41. package/src/client-v2/plugin.tsx +107 -72
  42. package/src/client-v2/report-destination.tsx +126 -0
  43. package/src/client-v2/utils/kqlAutocomplete.ts +861 -861
  44. package/src/client-v2/workflow/instructions.tsx +149 -149
  45. package/src/index.ts +11 -11
  46. package/src/locale/en-US.json +213 -198
  47. package/src/locale/vi-VN.json +213 -198
  48. package/src/locale/zh-CN.json +213 -198
  49. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  50. package/src/server/__tests__/query-compiler.test.ts +620 -620
  51. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -645
  52. package/src/server/acl-guard.ts +194 -194
  53. package/src/server/collections/es-report-data-views.ts +64 -64
  54. package/src/server/collections/es-reports.ts +80 -80
  55. package/src/server/index.ts +15 -15
  56. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  57. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -663
  58. package/src/server/plugin.ts +599 -599
  59. package/src/server/report-block-tools.ts +400 -0
  60. package/src/server/services/ElasticReportService.ts +494 -486
  61. package/src/server/services/ElasticsearchConnectionService.ts +728 -728
  62. package/src/server/services/ReportExportService.ts +282 -282
  63. package/src/server/services/ReportQueryCompiler.ts +1552 -1552
  64. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -124
  65. package/src/shared/constants.ts +39 -36
  66. package/src/shared/types.ts +272 -272
  67. package/dist/client-v2/851.142c93fc6d666b28.js +0 -10
  68. package/dist/client-v2/877.f4095a3dbcadf98f.js +0 -10
  69. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  70. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,1257 +1,1257 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import {
11
- ArrowDownOutlined,
12
- ArrowUpOutlined,
13
- ClockCircleOutlined,
14
- CodeOutlined,
15
- DatabaseOutlined,
16
- DownloadOutlined,
17
- FilterOutlined,
18
- LockOutlined,
19
- MinusCircleOutlined,
20
- PlusCircleOutlined,
21
- ReloadOutlined,
22
- RollbackOutlined,
23
- SearchOutlined,
24
- SettingOutlined,
25
- } from '@ant-design/icons';
26
- import {
27
- Alert,
28
- Button,
29
- Descriptions,
30
- Drawer,
31
- Dropdown,
32
- Empty,
33
- Form,
34
- Input,
35
- Modal,
36
- Popover,
37
- Progress,
38
- Select,
39
- Space,
40
- Spin,
41
- Table,
42
- Tabs,
43
- Tag,
44
- Tooltip,
45
- Typography,
46
- } from 'antd';
47
- import type { TableColumnsType } from 'antd';
48
- import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
49
- import type {
50
- AutoRefreshInterval,
51
- EsDataViewRecord,
52
- EsFieldCapability,
53
- ExportFormat,
54
- FieldFormatType,
55
- FieldTopValuesResult,
56
- FilterOperator,
57
- ReportExecutionResult,
58
- ReportFilterItem,
59
- ReportRowHit,
60
- ReportRuntimeOverrides,
61
- ReportSortItem,
62
- ReportSpec,
63
- ReportTimeRange,
64
- ScalarFilterValue,
65
- TimeRangePreset,
66
- } from '../../shared/types';
67
- import { useT } from '../locale';
68
- import { ElasticBasicChart, ReportHistogramStrip } from './ElasticBasicCharts';
69
- import { ElasticKqlInput } from './ElasticKqlInput';
70
- import { HighlightText } from './HighlightText';
71
-
72
- const { Text } = Typography;
73
-
74
- const VISUALLY_HIDDEN_STYLE: React.CSSProperties = {
75
- position: 'absolute',
76
- clipPath: 'inset(50%)',
77
- overflow: 'hidden',
78
- width: 1,
79
- height: 1,
80
- margin: -1,
81
- padding: 0,
82
- border: 0,
83
- whiteSpace: 'nowrap',
84
- };
85
-
86
- const OPERATOR_OPTIONS: Array<{ label: string; value: FilterOperator; needsValue: boolean; needsRange?: boolean }> = [
87
- { label: 'is (=)', value: 'eq', needsValue: true },
88
- { label: 'is not (!=)', value: 'ne', needsValue: true },
89
- { label: 'contains', value: 'contains', needsValue: true },
90
- { label: 'is one of (in)', value: 'in', needsValue: true },
91
- { label: 'is not one of', value: 'not_in', needsValue: true },
92
- { label: '>', value: 'gt', needsValue: true },
93
- { label: '>=', value: 'gte', needsValue: true },
94
- { label: '<', value: 'lt', needsValue: true },
95
- { label: '<=', value: 'lte', needsValue: true },
96
- { label: 'between', value: 'between', needsValue: true, needsRange: true },
97
- { label: 'exists', value: 'exists', needsValue: false },
98
- { label: 'does not exist', value: 'not_exists', needsValue: false },
99
- ];
100
-
101
- function getNestedValue(source: Record<string, unknown>, path: string): unknown {
102
- if (path in source) return source[path];
103
- const parts = path.split('.');
104
- let current: unknown = source;
105
- for (const part of parts) {
106
- if (
107
- current &&
108
- typeof current === 'object' &&
109
- !Array.isArray(current) &&
110
- part in (current as Record<string, unknown>)
111
- ) {
112
- current = (current as Record<string, unknown>)[part];
113
- } else {
114
- return undefined;
115
- }
116
- }
117
- return current;
118
- }
119
-
120
- function toScalarCandidate(value: unknown): ScalarFilterValue | undefined {
121
- if (typeof value === 'string' && value.length <= 256) return value;
122
- if (typeof value === 'number' && Number.isFinite(value)) return value;
123
- if (typeof value === 'boolean') return value;
124
- return undefined;
125
- }
126
-
127
- function formatCellValue(value: unknown): string {
128
- if (value === null || value === undefined) return '—';
129
- if (typeof value === 'string') return value;
130
- if (typeof value === 'number' || typeof value === 'boolean') return String(value);
131
- try {
132
- return JSON.stringify(value);
133
- } catch {
134
- return String(value);
135
- }
136
- }
137
-
138
- function formatHumanBytes(bytes: number): string {
139
- if (!Number.isFinite(bytes)) return '0 B';
140
- const abs = Math.abs(bytes);
141
- if (abs >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
142
- if (abs >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
143
- if (abs >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
144
- return `${bytes} B`;
145
- }
146
-
147
- function renderFormattedCell(rawVal: unknown, formatType?: FieldFormatType): React.ReactNode {
148
- if (rawVal === null || rawVal === undefined) return '—';
149
- if (!formatType || formatType === 'auto') {
150
- return formatCellValue(rawVal);
151
- }
152
- if (formatType === 'duration_ms') {
153
- const num = Number(rawVal);
154
- if (!Number.isFinite(num)) return formatCellValue(rawVal);
155
- return num >= 1000 ? `${(num / 1000).toFixed(2)} s` : `${num} ms`;
156
- }
157
- if (formatType === 'bytes') {
158
- const num = Number(rawVal);
159
- return Number.isFinite(num) ? formatHumanBytes(num) : formatCellValue(rawVal);
160
- }
161
- if (formatType === 'percent') {
162
- const num = Number(rawVal);
163
- return Number.isFinite(num) ? `${num.toFixed(2)}%` : formatCellValue(rawVal);
164
- }
165
- if (formatType === 'number') {
166
- const num = Number(rawVal);
167
- return Number.isFinite(num) ? num.toLocaleString() : formatCellValue(rawVal);
168
- }
169
- if (formatType === 'status_badge') {
170
- const num = Number(rawVal);
171
- if (Number.isFinite(num)) {
172
- const color = num >= 500 ? 'error' : num >= 400 ? 'warning' : num >= 200 && num < 300 ? 'success' : 'default';
173
- return <Tag color={color}>{num}</Tag>;
174
- }
175
- const text = String(rawVal);
176
- const lower = text.toLowerCase();
177
- const color =
178
- lower.includes('err') || lower.includes('fatal') || lower.includes('crit')
179
- ? 'error'
180
- : lower.includes('warn')
181
- ? 'warning'
182
- : lower.includes('ok') || lower.includes('info')
183
- ? 'processing'
184
- : 'default';
185
- return <Tag color={color}>{text}</Tag>;
186
- }
187
- if (formatType === 'url') {
188
- const text = String(rawVal).trim();
189
- if (/^https?:\/\//i.test(text)) {
190
- return (
191
- <a href={text} target="_blank" rel="noopener noreferrer" onClick={(e) => e.stopPropagation()}>
192
- {text}
193
- </a>
194
- );
195
- }
196
- return text;
197
- }
198
- return formatCellValue(rawVal);
199
- }
200
-
201
- export interface ElasticReportRendererProps {
202
- title: string;
203
- spec: ReportSpec;
204
- dataView?: EsDataViewRecord | null;
205
- fields?: EsFieldCapability[];
206
- result?: ReportExecutionResult | null;
207
- loading?: boolean;
208
- error?: string | null;
209
- showToolbar?: boolean;
210
- compact?: boolean;
211
- onExecute: (overrides: ReportRuntimeOverrides) => void;
212
- onCrossFilter?: (filterItem: ReportFilterItem) => void;
213
- onInspectTopValues?: (field: string, overrides?: ReportRuntimeOverrides) => Promise<FieldTopValuesResult>;
214
- onExport?: (format: ExportFormat, columns?: string[], overrides?: ReportRuntimeOverrides) => Promise<void>;
215
- }
216
-
217
- export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
218
- title,
219
- spec,
220
- dataView,
221
- fields = [],
222
- result,
223
- loading = false,
224
- error = null,
225
- showToolbar = true,
226
- compact = false,
227
- onExecute,
228
- onCrossFilter,
229
- onInspectTopValues,
230
- onExport,
231
- }) => {
232
- const t = useT();
233
- const regionLabelId = useId();
234
-
235
- const [queryText, setQueryText] = useState<string>(spec.query ?? '');
236
- const [filters, setFilters] = useState<ReportFilterItem[]>(spec.filters ?? []);
237
- const [sort, setSort] = useState<ReportSortItem[]>(spec.sort ?? []);
238
- const [timeRange, setTimeRange] = useState<ReportTimeRange>(spec.timeRange ?? { preset: 'last_24h' });
239
- const [customColumns, setCustomColumns] = useState<string[] | null>(null);
240
- const [autoRefreshSec, setAutoRefreshSec] = useState<AutoRefreshInterval>(0);
241
- const [page, setPage] = useState<number>(1);
242
- const [cursorHistory, setCursorHistory] = useState<Array<Array<string | number | boolean | null>>>([]);
243
-
244
- const [filterPopoverOpen, setFilterPopoverOpen] = useState(false);
245
- const [editingFilterIdx, setEditingFilterIdx] = useState<number | null>(null);
246
- const [draftFilterField, setDraftFilterField] = useState<string>('');
247
- const [draftFilterOp, setDraftFilterOp] = useState<FilterOperator>('eq');
248
- const [draftFilterValue, setDraftFilterValue] = useState<string>('');
249
- const [draftFilterValueTo, setDraftFilterValueTo] = useState<string>('');
250
-
251
- const [columnsPopoverOpen, setColumnsPopoverOpen] = useState(false);
252
- const [fieldsExplorerOpen, setFieldsExplorerOpen] = useState(false);
253
- const [selectedExploreField, setSelectedExploreField] = useState<string>('');
254
- const [topValuesData, setTopValuesData] = useState<FieldTopValuesResult | null>(null);
255
- const [topValuesLoading, setTopValuesLoading] = useState(false);
256
- const [exporting, setExporting] = useState(false);
257
-
258
- const [inspectDslOpen, setInspectDslOpen] = useState(false);
259
- const [selectedDoc, setSelectedDoc] = useState<ReportRowHit | null>(null);
260
-
261
- const serializedSpec = useMemo(() => JSON.stringify(spec), [spec]);
262
- const appliedSpecRef = useRef<string>(serializedSpec);
263
-
264
- useEffect(() => {
265
- if (appliedSpecRef.current === serializedSpec) {
266
- return;
267
- }
268
- appliedSpecRef.current = serializedSpec;
269
- setQueryText(spec.query ?? '');
270
- setFilters(spec.filters ?? []);
271
- setSort(spec.sort ?? []);
272
- setTimeRange(spec.timeRange ?? { preset: 'last_24h' });
273
- setCustomColumns(null);
274
- setPage(1);
275
- setCursorHistory([]);
276
- }, [serializedSpec, spec]);
277
-
278
- const buildCurrentOverrides = (nextOverrides?: Partial<ReportRuntimeOverrides>): ReportRuntimeOverrides => ({
279
- query: nextOverrides?.query !== undefined ? nextOverrides.query : queryText,
280
- filters: nextOverrides?.filters !== undefined ? nextOverrides.filters : filters,
281
- sort: nextOverrides?.sort !== undefined ? nextOverrides.sort : sort,
282
- timeRange: nextOverrides?.timeRange !== undefined ? nextOverrides.timeRange : timeRange,
283
- page: nextOverrides?.page ?? page,
284
- pageSize: spec.pageSize ?? 20,
285
- ...(nextOverrides?.searchAfter ? { searchAfter: nextOverrides.searchAfter } : {}),
286
- ...(nextOverrides?.pitId ?? result?.pitId ? { pitId: nextOverrides?.pitId ?? result?.pitId } : {}),
287
- });
288
-
289
- const triggerQuery = (nextOverrides?: Partial<ReportRuntimeOverrides>) => {
290
- const merged = buildCurrentOverrides({
291
- ...nextOverrides,
292
- page: nextOverrides?.page ?? 1,
293
- });
294
- onExecute(merged);
295
- };
296
-
297
- // Per-block Auto-Refresh timer (pauses automatically when browser tab is hidden)
298
- const triggerRef = useRef(triggerQuery);
299
- triggerRef.current = triggerQuery;
300
- useEffect(() => {
301
- if (!autoRefreshSec || autoRefreshSec <= 0) {
302
- return;
303
- }
304
- const timer = setInterval(() => {
305
- if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
306
- return;
307
- }
308
- triggerRef.current({ page });
309
- }, autoRefreshSec * 1000);
310
- return () => {
311
- clearInterval(timer);
312
- };
313
- }, [autoRefreshSec, page]);
314
-
315
- const aggregatableFields = useMemo(
316
- () => fields.filter((f) => f.aggregatable || Boolean(f.keywordSubfield)),
317
- [fields],
318
- );
319
-
320
- const selectableColumnFields = useMemo(() => fields.filter((f) => !f.isSubfield), [fields]);
321
-
322
- const timeRangeOptions: Array<{ label: string; value: TimeRangePreset }> = useMemo(
323
- () => [
324
- { label: t('Last 15 minutes'), value: 'last_15m' },
325
- { label: t('Last 1 hour'), value: 'last_1h' },
326
- { label: t('Last 24 hours'), value: 'last_24h' },
327
- { label: t('Last 7 days'), value: 'last_7d' },
328
- { label: t('Last 30 days'), value: 'last_30d' },
329
- { label: t('Last 90 days'), value: 'last_90d' },
330
- { label: t('All time'), value: 'all' },
331
- { label: t('Custom range'), value: 'custom' },
332
- ],
333
- [t],
334
- );
335
-
336
- const autoRefreshOptions: Array<{ label: string; value: AutoRefreshInterval }> = useMemo(
337
- () => [
338
- { label: t('Off'), value: 0 },
339
- { label: '10s', value: 10 },
340
- { label: '30s', value: 30 },
341
- { label: '1m', value: 60 },
342
- { label: '5m', value: 300 },
343
- ],
344
- [t],
345
- );
346
-
347
- const openAddFilterPopover = () => {
348
- setEditingFilterIdx(null);
349
- setDraftFilterOp('eq');
350
- setDraftFilterValue('');
351
- setDraftFilterValueTo('');
352
- setFilterPopoverOpen(true);
353
- };
354
-
355
- const openEditFilterPopover = (idx: number) => {
356
- const item = filters[idx];
357
- if (!item) return;
358
- setEditingFilterIdx(idx);
359
- setDraftFilterField(item.field);
360
- setDraftFilterOp(item.operator);
361
- setDraftFilterValue(
362
- Array.isArray(item.value) ? item.value.join(', ') : item.value !== undefined ? String(item.value) : '',
363
- );
364
- setDraftFilterValueTo(item.valueTo !== undefined ? String(item.valueTo) : '');
365
- setFilterPopoverOpen(true);
366
- };
367
-
368
- const handleSaveFilterPill = () => {
369
- if (!draftFilterField) return;
370
- const opMeta = OPERATOR_OPTIONS.find((o) => o.value === draftFilterOp);
371
- const parsedValue =
372
- draftFilterOp === 'in' || draftFilterOp === 'not_in'
373
- ? draftFilterValue
374
- .split(',')
375
- .map((part) => part.trim())
376
- .filter(Boolean)
377
- : draftFilterValue;
378
- const nextItem: ReportFilterItem = {
379
- id: editingFilterIdx !== null ? filters[editingFilterIdx]?.id ?? `${Date.now()}` : `${Date.now()}`,
380
- field: draftFilterField,
381
- operator: draftFilterOp,
382
- ...(opMeta?.needsValue ? { value: parsedValue } : {}),
383
- ...(opMeta?.needsRange && draftFilterValueTo ? { valueTo: draftFilterValueTo } : {}),
384
- enabled: true,
385
- };
386
- const updated =
387
- editingFilterIdx !== null
388
- ? filters.map((item, i) => (i === editingFilterIdx ? nextItem : item))
389
- : [...filters, nextItem];
390
- setFilters(updated);
391
- setPage(1);
392
- setCursorHistory([]);
393
- setFilterPopoverOpen(false);
394
- setEditingFilterIdx(null);
395
- setDraftFilterValue('');
396
- setDraftFilterValueTo('');
397
- triggerQuery({ filters: updated, page: 1 });
398
- };
399
-
400
- const applyQuickFieldFilter = useCallback(
401
- (field: string, operator: 'eq' | 'ne', value: ScalarFilterValue) => {
402
- const nextItem: ReportFilterItem = {
403
- id: `${Date.now()}-${field}`,
404
- field,
405
- operator,
406
- value,
407
- enabled: true,
408
- };
409
- if (onCrossFilter) {
410
- onCrossFilter(nextItem);
411
- return;
412
- }
413
- setFilters((prev) => {
414
- const updated = [...prev, nextItem];
415
- triggerRef.current({ filters: updated, page: 1 });
416
- return updated;
417
- });
418
- setPage(1);
419
- setCursorHistory([]);
420
- },
421
- [onCrossFilter],
422
- );
423
-
424
- const handleRemoveFilter = (idx: number) => {
425
- const updated = filters.filter((_, i) => i !== idx);
426
- setFilters(updated);
427
- setPage(1);
428
- setCursorHistory([]);
429
- triggerQuery({ filters: updated, page: 1 });
430
- };
431
-
432
- const handleReset = () => {
433
- const baseQuery = spec.query ?? '';
434
- const baseFilters = spec.filters ?? [];
435
- const baseSort = spec.sort ?? [];
436
- const baseTimeRange: ReportTimeRange = spec.timeRange ?? { preset: 'last_24h' };
437
- setQueryText(baseQuery);
438
- setFilters(baseFilters);
439
- setSort(baseSort);
440
- setTimeRange(baseTimeRange);
441
- setCustomColumns(null);
442
- setPage(1);
443
- setCursorHistory([]);
444
- onExecute({
445
- query: baseQuery,
446
- filters: baseFilters,
447
- sort: baseSort,
448
- timeRange: baseTimeRange,
449
- page: 1,
450
- pageSize: spec.pageSize ?? 20,
451
- });
452
- };
453
-
454
- const handleBucketDrilldown = (bucketKey: string) => {
455
- if (!showToolbar || spec.allowInteractiveControls === false) return;
456
- const bucketField = spec.chart?.bucketField || dataView?.timeField;
457
- if (!bucketField || spec.chart?.bucketType === 'date_histogram') return;
458
- const item: ReportFilterItem = {
459
- id: `${Date.now()}`,
460
- field: bucketField,
461
- operator: 'eq',
462
- value: bucketKey,
463
- enabled: true,
464
- };
465
- if (onCrossFilter) {
466
- onCrossFilter(item);
467
- return;
468
- }
469
- const updated = [...filters, item];
470
- setFilters(updated);
471
- triggerQuery({ filters: updated, page: 1 });
472
- };
473
-
474
- const handleSelectExploreField = async (fieldName: string) => {
475
- setSelectedExploreField(fieldName);
476
- if (!onInspectTopValues) return;
477
- setTopValuesLoading(true);
478
- try {
479
- const top = await onInspectTopValues(fieldName, buildCurrentOverrides());
480
- setTopValuesData(top);
481
- } catch {
482
- setTopValuesData(null);
483
- } finally {
484
- setTopValuesLoading(false);
485
- }
486
- };
487
-
488
- const activeColumns = useMemo(
489
- () => (customColumns && customColumns.length > 0 ? customColumns : result?.columns ?? spec.columns ?? []),
490
- [customColumns, result?.columns, spec.columns],
491
- );
492
-
493
- const moveColumn = (index: number, direction: -1 | 1) => {
494
- const nextIdx = index + direction;
495
- if (nextIdx < 0 || nextIdx >= activeColumns.length) return;
496
- const copy = [...activeColumns];
497
- const [picked] = copy.splice(index, 1);
498
- copy.splice(nextIdx, 0, picked);
499
- setCustomColumns(copy);
500
- };
501
-
502
- const canInteract = showToolbar && spec.allowInteractiveControls !== false;
503
- const currentOpMeta = OPERATOR_OPTIONS.find((o) => o.value === draftFilterOp);
504
-
505
- const tableColumns: TableColumnsType<ReportRowHit> = useMemo(
506
- () =>
507
- activeColumns.map((colName) => {
508
- const activeSort = sort.find((s) => s.field === colName || s.field === `${colName}.keyword`);
509
- const canSortCol = aggregatableFields.some((f) => f.name === colName || f.name === `${colName}.keyword`);
510
- const colFormat = spec.fieldFormats?.[colName];
511
- const colWidth =
512
- colName === '@timestamp' ? 200 : colName === 'message' || colName.endsWith('.message') ? 320 : 165;
513
- return {
514
- title: colName,
515
- key: colName,
516
- width: colWidth,
517
- ellipsis: true,
518
- ...(canSortCol
519
- ? {
520
- sorter: true,
521
- sortOrder: activeSort ? (activeSort.order === 'asc' ? 'ascend' : 'descend') : null,
522
- }
523
- : {}),
524
- render: (_: unknown, record: ReportRowHit) => {
525
- const hl = record.highlights?.[colName]?.[0];
526
- const rawVal =
527
- colName === '_id'
528
- ? record._id
529
- : colName === '_index'
530
- ? record._index
531
- : getNestedValue(record.source, colName);
532
- const scalarVal = colName !== '@timestamp' ? toScalarCandidate(rawVal) : undefined;
533
-
534
- return (
535
- <span
536
- style={{
537
- display: 'flex',
538
- alignItems: 'center',
539
- justifyContent: 'space-between',
540
- gap: 6,
541
- width: '100%',
542
- maxWidth: '100%',
543
- minWidth: 0,
544
- }}
545
- >
546
- <span
547
- style={{
548
- flex: 1,
549
- minWidth: 0,
550
- overflow: 'hidden',
551
- textOverflow: 'ellipsis',
552
- whiteSpace: 'nowrap',
553
- }}
554
- >
555
- {hl ? <HighlightText text={hl} /> : renderFormattedCell(rawVal, colFormat)}
556
- </span>
557
- {canInteract && scalarVal !== undefined && (
558
- <span
559
- style={{ display: 'inline-flex', gap: 2, flexShrink: 0, opacity: 0.65 }}
560
- onClick={(e) => e.stopPropagation()}
561
- >
562
- <Tooltip title={t('Filter for value')}>
563
- <Button
564
- type="text"
565
- size="small"
566
- aria-label={`${t('Filter for value')}: ${colName}=${String(scalarVal)}`}
567
- icon={<PlusCircleOutlined style={{ fontSize: 12 }} />}
568
- style={{ width: 20, height: 20, padding: 0 }}
569
- onClick={() => applyQuickFieldFilter(colName, 'eq', scalarVal)}
570
- />
571
- </Tooltip>
572
- <Tooltip title={t('Filter out value')}>
573
- <Button
574
- type="text"
575
- size="small"
576
- aria-label={`${t('Filter out value')}: ${colName}!=${String(scalarVal)}`}
577
- icon={<MinusCircleOutlined style={{ fontSize: 12 }} />}
578
- style={{ width: 20, height: 20, padding: 0 }}
579
- onClick={() => applyQuickFieldFilter(colName, 'ne', scalarVal)}
580
- />
581
- </Tooltip>
582
- </span>
583
- )}
584
- </span>
585
- );
586
- },
587
- };
588
- }),
589
- [activeColumns, aggregatableFields, applyQuickFieldFilter, canInteract, sort, spec.fieldFormats, t],
590
- );
591
-
592
- return (
593
- <div style={{ width: '100%', maxWidth: '100%', minWidth: 0 }}>
594
- {/* Polite status region announces updated hit counts for screen readers without putting aria-live on <table> */}
595
- <div role="status" aria-live="polite" style={VISUALLY_HIDDEN_STYLE}>
596
- {!loading && result ? `${title}: ${result.total} ${t('Hits')}` : ''}
597
- </div>
598
-
599
- {canInteract && (
600
- <div style={{ marginBottom: 12, maxWidth: '100%' }}>
601
- <Space wrap style={{ width: '100%', maxWidth: '100%', justifyContent: 'space-between' }}>
602
- <Space wrap style={{ maxWidth: '100%' }}>
603
- <ElasticKqlInput
604
- ariaLabel={t('KQL / Search Query')}
605
- placeholder={t('Search KQL, e.g. status >= 500 AND service: "api"')}
606
- value={queryText}
607
- fields={fields}
608
- sampleRows={result?.rows}
609
- style={{ width: compact ? 220 : 280, maxWidth: '100%' }}
610
- onInspectTopValues={
611
- onInspectTopValues
612
- ? (field) => onInspectTopValues(field, buildCurrentOverrides({ query: '' }))
613
- : undefined
614
- }
615
- onChange={(nextVal) => {
616
- setQueryText(nextVal);
617
- }}
618
- onClear={() => {
619
- setQueryText('');
620
- setPage(1);
621
- setCursorHistory([]);
622
- triggerQuery({ query: '', page: 1 });
623
- }}
624
- onSubmit={(submittedVal) => {
625
- setPage(1);
626
- setCursorHistory([]);
627
- triggerQuery({ query: submittedVal, page: 1 });
628
- }}
629
- />
630
- {dataView?.timeField && (
631
- <>
632
- <Select
633
- aria-label={t('Time Field')}
634
- value={timeRange.preset}
635
- options={timeRangeOptions}
636
- style={{ minWidth: 150 }}
637
- onChange={(nextPreset) => {
638
- const nextRange: ReportTimeRange =
639
- nextPreset === 'custom'
640
- ? {
641
- preset: 'custom',
642
- from: timeRange.from ?? spec.timeRange?.from ?? 'now-24h',
643
- to: timeRange.to ?? spec.timeRange?.to ?? 'now',
644
- }
645
- : { preset: nextPreset };
646
- setTimeRange(nextRange);
647
- setPage(1);
648
- setCursorHistory([]);
649
- triggerQuery({ timeRange: nextRange, page: 1 });
650
- }}
651
- />
652
- {timeRange.preset === 'custom' && (
653
- <Space.Compact>
654
- <Input
655
- aria-label={t('From')}
656
- placeholder={t('From')}
657
- value={timeRange.from ?? ''}
658
- style={{ width: 165 }}
659
- onChange={(e) => setTimeRange((prev) => ({ ...prev, preset: 'custom', from: e.target.value }))}
660
- onPressEnter={() => {
661
- setPage(1);
662
- setCursorHistory([]);
663
- triggerQuery({ timeRange, page: 1 });
664
- }}
665
- />
666
- <Input
667
- aria-label={t('To')}
668
- placeholder={t('To')}
669
- value={timeRange.to ?? ''}
670
- style={{ width: 165 }}
671
- onChange={(e) => setTimeRange((prev) => ({ ...prev, preset: 'custom', to: e.target.value }))}
672
- onPressEnter={() => {
673
- setPage(1);
674
- setCursorHistory([]);
675
- triggerQuery({ timeRange, page: 1 });
676
- }}
677
- />
678
- </Space.Compact>
679
- )}
680
- </>
681
- )}
682
- <Popover
683
- trigger="click"
684
- title={editingFilterIdx !== null ? t('Edit Filter') : t('Add Filter')}
685
- open={filterPopoverOpen}
686
- onOpenChange={(open) => {
687
- setFilterPopoverOpen(open);
688
- if (!open) {
689
- setEditingFilterIdx(null);
690
- }
691
- }}
692
- content={
693
- <div style={{ width: 280 }}>
694
- <Form layout="vertical" size="small">
695
- <Form.Item label={t('Field')} style={{ marginBottom: 8 }}>
696
- <Select
697
- showSearch
698
- value={draftFilterField || undefined}
699
- placeholder={t('Field')}
700
- options={fields.map((f) => ({ label: `${f.name} (${f.type})`, value: f.name }))}
701
- onChange={(val) => setDraftFilterField(val)}
702
- />
703
- </Form.Item>
704
- <Form.Item label={t('Operator')} style={{ marginBottom: 8 }}>
705
- <Select
706
- value={draftFilterOp}
707
- options={OPERATOR_OPTIONS.map((o) => ({ label: o.label, value: o.value }))}
708
- onChange={(val) => setDraftFilterOp(val)}
709
- />
710
- </Form.Item>
711
- {currentOpMeta?.needsValue && (
712
- <Form.Item label={t('Value')} style={{ marginBottom: 8 }}>
713
- <Input value={draftFilterValue} onChange={(e) => setDraftFilterValue(e.target.value)} />
714
- </Form.Item>
715
- )}
716
- {currentOpMeta?.needsRange && (
717
- <Form.Item label={t('To Value')} style={{ marginBottom: 8 }}>
718
- <Input value={draftFilterValueTo} onChange={(e) => setDraftFilterValueTo(e.target.value)} />
719
- </Form.Item>
720
- )}
721
- <Space style={{ justifyContent: 'flex-end', width: '100%' }}>
722
- <Button
723
- size="small"
724
- onClick={() => {
725
- setFilterPopoverOpen(false);
726
- setEditingFilterIdx(null);
727
- }}
728
- >
729
- {t('Cancel')}
730
- </Button>
731
- <Button size="small" type="primary" onClick={handleSaveFilterPill}>
732
- {t('Apply')}
733
- </Button>
734
- </Space>
735
- </Form>
736
- </div>
737
- }
738
- >
739
- <Button icon={<FilterOutlined />} onClick={openAddFilterPopover}>
740
- {t('Add Filter')}
741
- </Button>
742
- </Popover>
743
-
744
- {spec.visualization === 'table' && aggregatableFields.length > 0 && (
745
- <Select
746
- allowClear
747
- aria-label={t('Sort')}
748
- placeholder={t('Sort')}
749
- style={{ minWidth: 165 }}
750
- value={sort[0] ? `${sort[0].field}:${sort[0].order}` : undefined}
751
- options={aggregatableFields.slice(0, 40).flatMap((f) => [
752
- { label: `${f.name} ↓`, value: `${f.name}:desc` },
753
- { label: `${f.name} ↑`, value: `${f.name}:asc` },
754
- ])}
755
- onChange={(encoded) => {
756
- if (!encoded) {
757
- setSort([]);
758
- setPage(1);
759
- setCursorHistory([]);
760
- triggerQuery({ sort: [], page: 1 });
761
- return;
762
- }
763
- const lastColon = encoded.lastIndexOf(':');
764
- const nextSort: ReportSortItem[] = [
765
- {
766
- field: encoded.slice(0, lastColon),
767
- order: encoded.slice(lastColon + 1) === 'asc' ? 'asc' : 'desc',
768
- },
769
- ];
770
- setSort(nextSort);
771
- setPage(1);
772
- setCursorHistory([]);
773
- triggerQuery({ sort: nextSort, page: 1 });
774
- }}
775
- />
776
- )}
777
-
778
- {spec.visualization === 'table' && selectableColumnFields.length > 0 && (
779
- <Popover
780
- trigger="click"
781
- title={t('Visible Columns')}
782
- open={columnsPopoverOpen}
783
- onOpenChange={setColumnsPopoverOpen}
784
- content={
785
- <div style={{ width: 280 }}>
786
- <Select
787
- mode="multiple"
788
- style={{ width: '100%', marginBottom: 8 }}
789
- value={activeColumns}
790
- options={selectableColumnFields.map((f) => ({ label: f.name, value: f.name }))}
791
- onChange={(cols) => setCustomColumns(cols)}
792
- />
793
- <div style={{ maxHeight: 200, overflowY: 'auto' }}>
794
- {activeColumns.map((col, idx) => (
795
- <div
796
- key={col}
797
- style={{
798
- display: 'flex',
799
- justifyContent: 'space-between',
800
- alignItems: 'center',
801
- padding: '3px 0',
802
- fontSize: 12,
803
- }}
804
- >
805
- <Text ellipsis style={{ maxWidth: 190 }}>
806
- {col}
807
- </Text>
808
- <Space size={2}>
809
- <Button
810
- size="small"
811
- type="text"
812
- aria-label={`${t('Move up')}: ${col}`}
813
- disabled={idx === 0}
814
- icon={<ArrowUpOutlined />}
815
- onClick={() => moveColumn(idx, -1)}
816
- />
817
- <Button
818
- size="small"
819
- type="text"
820
- aria-label={`${t('Move down')}: ${col}`}
821
- disabled={idx === activeColumns.length - 1}
822
- icon={<ArrowDownOutlined />}
823
- onClick={() => moveColumn(idx, 1)}
824
- />
825
- </Space>
826
- </div>
827
- ))}
828
- </div>
829
- </div>
830
- }
831
- >
832
- <Button icon={<SettingOutlined />}>{t('Columns')}</Button>
833
- </Popover>
834
- )}
835
-
836
- {spec.visualization === 'table' && onInspectTopValues && fields.length > 0 && (
837
- <Button
838
- icon={<DatabaseOutlined />}
839
- onClick={() => {
840
- setFieldsExplorerOpen(true);
841
- if (!selectedExploreField && selectableColumnFields[0]) {
842
- handleSelectExploreField(selectableColumnFields[0].name);
843
- }
844
- }}
845
- >
846
- {t('Fields Explorer')}
847
- </Button>
848
- )}
849
- </Space>
850
-
851
- <Space wrap>
852
- <Select
853
- aria-label={t('Auto refresh')}
854
- suffixIcon={<ClockCircleOutlined />}
855
- value={autoRefreshSec}
856
- options={autoRefreshOptions}
857
- style={{ width: 92 }}
858
- onChange={(sec: AutoRefreshInterval) => setAutoRefreshSec(sec)}
859
- />
860
- <Button
861
- type="primary"
862
- icon={<SearchOutlined />}
863
- onClick={() => {
864
- setPage(1);
865
- setCursorHistory([]);
866
- triggerQuery({ page: 1 });
867
- }}
868
- >
869
- {t('Search')}
870
- </Button>
871
- <Button icon={<ReloadOutlined />} aria-label={t('Refresh')} onClick={() => triggerQuery({ page })} />
872
- <Button icon={<RollbackOutlined />} onClick={handleReset}>
873
- {t('Reset')}
874
- </Button>
875
- {onExport && spec.allowExport !== false && (
876
- <Dropdown
877
- menu={{
878
- items: [
879
- {
880
- key: 'csv',
881
- label: t('Export CSV'),
882
- onClick: async () => {
883
- setExporting(true);
884
- try {
885
- await onExport('csv', activeColumns, buildCurrentOverrides());
886
- } finally {
887
- setExporting(false);
888
- }
889
- },
890
- },
891
- {
892
- key: 'ndjson',
893
- label: t('Export NDJSON'),
894
- onClick: async () => {
895
- setExporting(true);
896
- try {
897
- await onExport('ndjson', activeColumns, buildCurrentOverrides());
898
- } finally {
899
- setExporting(false);
900
- }
901
- },
902
- },
903
- ],
904
- }}
905
- >
906
- <Button loading={exporting} icon={<DownloadOutlined />}>
907
- {t('Export CSV')}
908
- </Button>
909
- </Dropdown>
910
- )}
911
- {result?.compiledDsl && (
912
- <Button icon={<CodeOutlined />} onClick={() => setInspectDslOpen(true)}>
913
- {t('Inspect DSL')}
914
- </Button>
915
- )}
916
- </Space>
917
- </Space>
918
-
919
- {((spec.lockedFilters?.length ?? 0) > 0 || filters.length > 0) && (
920
- <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
921
- {(spec.lockedFilters ?? []).map((flt, idx) => (
922
- <Tag key={flt.id || `locked-${flt.field}-${idx}`} icon={<LockOutlined />} color="gold">
923
- {flt.field} {flt.operator}
924
- {flt.value !== undefined
925
- ? ` ${Array.isArray(flt.value) ? flt.value.join(', ') : String(flt.value)}`
926
- : ''}
927
- {flt.valueTo !== undefined ? ` .. ${String(flt.valueTo)}` : ''}
928
- </Tag>
929
- ))}
930
- {filters.map((flt, idx) => (
931
- <Tag
932
- key={flt.id || `${flt.field}-${idx}`}
933
- closable
934
- color="processing"
935
- onClose={(e) => {
936
- e.preventDefault();
937
- e.stopPropagation();
938
- handleRemoveFilter(idx);
939
- }}
940
- >
941
- <span
942
- role="button"
943
- tabIndex={0}
944
- aria-label={`${t('Edit Filter')}: ${flt.field}`}
945
- style={{ cursor: 'pointer' }}
946
- onClick={() => openEditFilterPopover(idx)}
947
- onKeyDown={(e) => {
948
- if (e.key === 'Enter' || e.key === ' ') {
949
- e.preventDefault();
950
- openEditFilterPopover(idx);
951
- }
952
- }}
953
- >
954
- {flt.field} {flt.operator}
955
- {flt.value !== undefined
956
- ? ` ${Array.isArray(flt.value) ? flt.value.join(', ') : String(flt.value)}`
957
- : ''}
958
- {flt.valueTo !== undefined ? ` .. ${String(flt.valueTo)}` : ''}
959
- </span>
960
- </Tag>
961
- ))}
962
- </div>
963
- )}
964
- </div>
965
- )}
966
-
967
- {!canInteract && (spec.lockedFilters?.length ?? 0) > 0 && (
968
- <div style={{ marginBottom: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
969
- {(spec.lockedFilters ?? []).map((flt, idx) => (
970
- <Tag key={flt.id || `locked-${flt.field}-${idx}`} icon={<LockOutlined />} color="gold">
971
- {flt.field} {flt.operator}
972
- {flt.value !== undefined ? ` ${Array.isArray(flt.value) ? flt.value.join(', ') : String(flt.value)}` : ''}
973
- {flt.valueTo !== undefined ? ` .. ${String(flt.valueTo)}` : ''}
974
- </Tag>
975
- ))}
976
- </div>
977
- )}
978
-
979
- {error && <Alert type="error" showIcon message={error} style={{ marginBottom: 12 }} />}
980
-
981
- {result && (result.timedOut || (result.shards && result.shards.failed > 0)) && (
982
- <Alert
983
- type="warning"
984
- showIcon
985
- style={{ marginBottom: 12 }}
986
- message={t('Partial results warning')}
987
- description={
988
- <>
989
- {result.timedOut && <div>{t('Query timed out; displayed results may be incomplete.')}</div>}
990
- {result.shards && result.shards.failed > 0 && (
991
- <div>
992
- {t('Failed shards')}: {result.shards.failed} / {result.shards.total}
993
- </div>
994
- )}
995
- </>
996
- }
997
- />
998
- )}
999
-
1000
- <Spin spinning={loading}>
1001
- {!result ? (
1002
- <Empty description={t('No matching documents')} />
1003
- ) : spec.visualization === 'table' ? (
1004
- <div>
1005
- {result.histogram.length > 0 && spec.chart?.showHistogram !== false && (
1006
- <ReportHistogramStrip buckets={result.histogram} />
1007
- )}
1008
- <div
1009
- style={{
1010
- display: 'flex',
1011
- justifyContent: 'space-between',
1012
- alignItems: 'center',
1013
- marginBottom: 8,
1014
- fontSize: 12,
1015
- }}
1016
- >
1017
- <Text id={regionLabelId} strong>
1018
- {title} · {t('Hits')}: {result.total.toLocaleString()}
1019
- {result.totalRelation === 'gte' ? '+' : ''} ({result.tookMs} ms)
1020
- </Text>
1021
- {result.nextSearchAfter && cursorHistory.length > 0 && (
1022
- <Button
1023
- size="small"
1024
- onClick={() => {
1025
- setPage(1);
1026
- setCursorHistory([]);
1027
- triggerQuery({ page: 1 });
1028
- }}
1029
- >
1030
- {t('First page')}
1031
- </Button>
1032
- )}
1033
- </div>
1034
-
1035
- <div
1036
- role="region"
1037
- aria-labelledby={regionLabelId}
1038
- tabIndex={0}
1039
- style={{ width: '100%', maxWidth: '100%', minWidth: 0, overflowX: 'auto' }}
1040
- >
1041
- <Table<ReportRowHit>
1042
- size={compact ? 'small' : 'middle'}
1043
- scroll={{ x: 'max-content' }}
1044
- rowKey={(record) => `${record._index}:${record._id}`}
1045
- columns={tableColumns}
1046
- dataSource={result.rows}
1047
- onRow={(record) => ({
1048
- onClick: () => setSelectedDoc(record),
1049
- style: { cursor: 'pointer' },
1050
- })}
1051
- onChange={(pagination, _tableFilters, sorter) => {
1052
- const singleSorter = Array.isArray(sorter) ? sorter[0] : sorter;
1053
- if (singleSorter && singleSorter.columnKey && singleSorter.order) {
1054
- const nextSort: ReportSortItem[] = [
1055
- {
1056
- field: String(singleSorter.columnKey),
1057
- order: singleSorter.order === 'ascend' ? 'asc' : 'desc',
1058
- },
1059
- ];
1060
- setSort(nextSort);
1061
- setPage(1);
1062
- setCursorHistory([]);
1063
- triggerQuery({ sort: nextSort, page: 1 });
1064
- return;
1065
- }
1066
-
1067
- const nextPage = pagination.current ?? 1;
1068
- const pageSize = spec.pageSize ?? 20;
1069
- if (nextPage * pageSize > 10000 && result.nextSearchAfter) {
1070
- const updatedHistory = [...cursorHistory, result.nextSearchAfter];
1071
- setCursorHistory(updatedHistory);
1072
- setPage(nextPage);
1073
- triggerQuery({ page: nextPage, searchAfter: result.nextSearchAfter, pitId: result.pitId });
1074
- return;
1075
- }
1076
- setPage(nextPage);
1077
- triggerQuery({ page: nextPage });
1078
- }}
1079
- pagination={{
1080
- current: page,
1081
- pageSize: spec.pageSize ?? 20,
1082
- total: Math.min(result.total, 10000),
1083
- showSizeChanger: false,
1084
- }}
1085
- />
1086
- </div>
1087
-
1088
- {result.total >= 10000 && result.nextSearchAfter && (
1089
- <div style={{ marginTop: 8, textAlign: 'right' }}>
1090
- <Button
1091
- size="small"
1092
- onClick={() => {
1093
- if (!result.nextSearchAfter) return;
1094
- const updatedHistory = [...cursorHistory, result.nextSearchAfter];
1095
- setCursorHistory(updatedHistory);
1096
- setPage((p) => p + 1);
1097
- triggerQuery({ searchAfter: result.nextSearchAfter, pitId: result.pitId });
1098
- }}
1099
- >
1100
- {t('Next cursor page')}
1101
- </Button>
1102
- </div>
1103
- )}
1104
- </div>
1105
- ) : (
1106
- <ElasticBasicChart
1107
- title={title}
1108
- visualization={spec.visualization}
1109
- series={result.series}
1110
- seriesKeys={result.seriesKeys}
1111
- stackMode={spec.chart?.stackMode}
1112
- metricValue={result.metricValue}
1113
- previousMetricValue={result.previousMetricValue}
1114
- deltaPercent={result.deltaPercent}
1115
- metricLabel={result.metricLabel}
1116
- metricType={spec.chart?.metricType}
1117
- totalHits={result.total}
1118
- totalRelation={result.totalRelation}
1119
- onSelectBucket={handleBucketDrilldown}
1120
- />
1121
- )}
1122
- </Spin>
1123
-
1124
- <Modal
1125
- title={t('Elasticsearch Query DSL')}
1126
- open={inspectDslOpen}
1127
- footer={null}
1128
- onCancel={() => setInspectDslOpen(false)}
1129
- width="min(680px, calc(100vw - 32px))"
1130
- >
1131
- <pre style={{ maxHeight: 420, overflow: 'auto', fontSize: 12 }}>
1132
- {JSON.stringify(result?.compiledDsl ?? {}, null, 2)}
1133
- </pre>
1134
- </Modal>
1135
-
1136
- <Drawer
1137
- title={t('Fields Explorer')}
1138
- open={fieldsExplorerOpen}
1139
- onClose={() => setFieldsExplorerOpen(false)}
1140
- width="min(420px, 92vw)"
1141
- >
1142
- <Space direction="vertical" size={12} style={{ width: '100%' }}>
1143
- <Select
1144
- showSearch
1145
- style={{ width: '100%' }}
1146
- value={selectedExploreField || undefined}
1147
- placeholder={t('Field')}
1148
- options={selectableColumnFields.map((f) => ({ label: `${f.name} (${f.type})`, value: f.name }))}
1149
- onChange={(val) => {
1150
- handleSelectExploreField(val);
1151
- }}
1152
- />
1153
- <Spin spinning={topValuesLoading}>
1154
- {topValuesData && topValuesData.buckets.length > 0 ? (
1155
- <Space direction="vertical" size={8} style={{ width: '100%' }}>
1156
- <Text type="secondary" style={{ fontSize: 12 }}>
1157
- {t('Top values')} · {t('Hits')}: {topValuesData.totalDocs.toLocaleString()}
1158
- </Text>
1159
- {topValuesData.buckets.map((bucket) => (
1160
- <div key={bucket.value} style={{ fontSize: 12 }}>
1161
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
1162
- <Text ellipsis style={{ maxWidth: 220 }}>
1163
- {bucket.value}
1164
- </Text>
1165
- <Space size={4}>
1166
- <Text type="secondary">
1167
- {bucket.count} ({bucket.percentage}%)
1168
- </Text>
1169
- <Button
1170
- type="text"
1171
- size="small"
1172
- aria-label={`${t('Filter for value')}: ${selectedExploreField}=${bucket.value}`}
1173
- icon={<PlusCircleOutlined />}
1174
- onClick={() => applyQuickFieldFilter(selectedExploreField, 'eq', bucket.value)}
1175
- />
1176
- <Button
1177
- type="text"
1178
- size="small"
1179
- aria-label={`${t('Filter out value')}: ${selectedExploreField}!=${bucket.value}`}
1180
- icon={<MinusCircleOutlined />}
1181
- onClick={() => applyQuickFieldFilter(selectedExploreField, 'ne', bucket.value)}
1182
- />
1183
- </Space>
1184
- </div>
1185
- <Progress percent={bucket.percentage} showInfo={false} size="small" />
1186
- </div>
1187
- ))}
1188
- </Space>
1189
- ) : (
1190
- <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('No matching documents')} />
1191
- )}
1192
- </Spin>
1193
- </Space>
1194
- </Drawer>
1195
-
1196
- <Drawer
1197
- title={t('Document Details')}
1198
- open={Boolean(selectedDoc)}
1199
- onClose={() => setSelectedDoc(null)}
1200
- width="min(640px, 94vw)"
1201
- >
1202
- {selectedDoc && (
1203
- <Tabs
1204
- items={[
1205
- {
1206
- key: 'table',
1207
- label: t('Table View'),
1208
- children: (
1209
- <Descriptions bordered column={1} size="small">
1210
- <Descriptions.Item label="_index">{selectedDoc._index}</Descriptions.Item>
1211
- <Descriptions.Item label="_id">{selectedDoc._id}</Descriptions.Item>
1212
- {Object.entries(selectedDoc.source).map(([k, v]) => (
1213
- <Descriptions.Item key={k} label={k}>
1214
- <Space>
1215
- <span>{formatCellValue(v)}</span>
1216
- {canInteract && toScalarCandidate(v) !== undefined && (
1217
- <>
1218
- <Button
1219
- type="text"
1220
- size="small"
1221
- icon={<PlusCircleOutlined />}
1222
- onClick={() =>
1223
- applyQuickFieldFilter(k, 'eq', toScalarCandidate(v) as ScalarFilterValue)
1224
- }
1225
- />
1226
- <Button
1227
- type="text"
1228
- size="small"
1229
- icon={<MinusCircleOutlined />}
1230
- onClick={() =>
1231
- applyQuickFieldFilter(k, 'ne', toScalarCandidate(v) as ScalarFilterValue)
1232
- }
1233
- />
1234
- </>
1235
- )}
1236
- </Space>
1237
- </Descriptions.Item>
1238
- ))}
1239
- </Descriptions>
1240
- ),
1241
- },
1242
- {
1243
- key: 'json',
1244
- label: t('JSON View'),
1245
- children: (
1246
- <pre style={{ maxHeight: 520, overflow: 'auto', fontSize: 12 }}>
1247
- {JSON.stringify(selectedDoc, null, 2)}
1248
- </pre>
1249
- ),
1250
- },
1251
- ]}
1252
- />
1253
- )}
1254
- </Drawer>
1255
- </div>
1256
- );
1257
- };
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import {
11
+ ArrowDownOutlined,
12
+ ArrowUpOutlined,
13
+ ClockCircleOutlined,
14
+ CodeOutlined,
15
+ DatabaseOutlined,
16
+ DownloadOutlined,
17
+ FilterOutlined,
18
+ LockOutlined,
19
+ MinusCircleOutlined,
20
+ PlusCircleOutlined,
21
+ ReloadOutlined,
22
+ RollbackOutlined,
23
+ SearchOutlined,
24
+ SettingOutlined,
25
+ } from '@ant-design/icons';
26
+ import {
27
+ Alert,
28
+ Button,
29
+ Descriptions,
30
+ Drawer,
31
+ Dropdown,
32
+ Empty,
33
+ Form,
34
+ Input,
35
+ Modal,
36
+ Popover,
37
+ Progress,
38
+ Select,
39
+ Space,
40
+ Spin,
41
+ Table,
42
+ Tabs,
43
+ Tag,
44
+ Tooltip,
45
+ Typography,
46
+ } from 'antd';
47
+ import type { TableColumnsType } from 'antd';
48
+ import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
49
+ import type {
50
+ AutoRefreshInterval,
51
+ EsDataViewRecord,
52
+ EsFieldCapability,
53
+ ExportFormat,
54
+ FieldFormatType,
55
+ FieldTopValuesResult,
56
+ FilterOperator,
57
+ ReportExecutionResult,
58
+ ReportFilterItem,
59
+ ReportRowHit,
60
+ ReportRuntimeOverrides,
61
+ ReportSortItem,
62
+ ReportSpec,
63
+ ReportTimeRange,
64
+ ScalarFilterValue,
65
+ TimeRangePreset,
66
+ } from '../../shared/types';
67
+ import { useT } from '../locale';
68
+ import { ElasticBasicChart, ReportHistogramStrip } from './ElasticBasicCharts';
69
+ import { ElasticKqlInput } from './ElasticKqlInput';
70
+ import { HighlightText } from './HighlightText';
71
+
72
+ const { Text } = Typography;
73
+
74
+ const VISUALLY_HIDDEN_STYLE: React.CSSProperties = {
75
+ position: 'absolute',
76
+ clipPath: 'inset(50%)',
77
+ overflow: 'hidden',
78
+ width: 1,
79
+ height: 1,
80
+ margin: -1,
81
+ padding: 0,
82
+ border: 0,
83
+ whiteSpace: 'nowrap',
84
+ };
85
+
86
+ const OPERATOR_OPTIONS: Array<{ label: string; value: FilterOperator; needsValue: boolean; needsRange?: boolean }> = [
87
+ { label: 'is (=)', value: 'eq', needsValue: true },
88
+ { label: 'is not (!=)', value: 'ne', needsValue: true },
89
+ { label: 'contains', value: 'contains', needsValue: true },
90
+ { label: 'is one of (in)', value: 'in', needsValue: true },
91
+ { label: 'is not one of', value: 'not_in', needsValue: true },
92
+ { label: '>', value: 'gt', needsValue: true },
93
+ { label: '>=', value: 'gte', needsValue: true },
94
+ { label: '<', value: 'lt', needsValue: true },
95
+ { label: '<=', value: 'lte', needsValue: true },
96
+ { label: 'between', value: 'between', needsValue: true, needsRange: true },
97
+ { label: 'exists', value: 'exists', needsValue: false },
98
+ { label: 'does not exist', value: 'not_exists', needsValue: false },
99
+ ];
100
+
101
+ function getNestedValue(source: Record<string, unknown>, path: string): unknown {
102
+ if (path in source) return source[path];
103
+ const parts = path.split('.');
104
+ let current: unknown = source;
105
+ for (const part of parts) {
106
+ if (
107
+ current &&
108
+ typeof current === 'object' &&
109
+ !Array.isArray(current) &&
110
+ part in (current as Record<string, unknown>)
111
+ ) {
112
+ current = (current as Record<string, unknown>)[part];
113
+ } else {
114
+ return undefined;
115
+ }
116
+ }
117
+ return current;
118
+ }
119
+
120
+ function toScalarCandidate(value: unknown): ScalarFilterValue | undefined {
121
+ if (typeof value === 'string' && value.length <= 256) return value;
122
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
123
+ if (typeof value === 'boolean') return value;
124
+ return undefined;
125
+ }
126
+
127
+ function formatCellValue(value: unknown): string {
128
+ if (value === null || value === undefined) return '—';
129
+ if (typeof value === 'string') return value;
130
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
131
+ try {
132
+ return JSON.stringify(value);
133
+ } catch {
134
+ return String(value);
135
+ }
136
+ }
137
+
138
+ function formatHumanBytes(bytes: number): string {
139
+ if (!Number.isFinite(bytes)) return '0 B';
140
+ const abs = Math.abs(bytes);
141
+ if (abs >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
142
+ if (abs >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
143
+ if (abs >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
144
+ return `${bytes} B`;
145
+ }
146
+
147
+ function renderFormattedCell(rawVal: unknown, formatType?: FieldFormatType): React.ReactNode {
148
+ if (rawVal === null || rawVal === undefined) return '—';
149
+ if (!formatType || formatType === 'auto') {
150
+ return formatCellValue(rawVal);
151
+ }
152
+ if (formatType === 'duration_ms') {
153
+ const num = Number(rawVal);
154
+ if (!Number.isFinite(num)) return formatCellValue(rawVal);
155
+ return num >= 1000 ? `${(num / 1000).toFixed(2)} s` : `${num} ms`;
156
+ }
157
+ if (formatType === 'bytes') {
158
+ const num = Number(rawVal);
159
+ return Number.isFinite(num) ? formatHumanBytes(num) : formatCellValue(rawVal);
160
+ }
161
+ if (formatType === 'percent') {
162
+ const num = Number(rawVal);
163
+ return Number.isFinite(num) ? `${num.toFixed(2)}%` : formatCellValue(rawVal);
164
+ }
165
+ if (formatType === 'number') {
166
+ const num = Number(rawVal);
167
+ return Number.isFinite(num) ? num.toLocaleString() : formatCellValue(rawVal);
168
+ }
169
+ if (formatType === 'status_badge') {
170
+ const num = Number(rawVal);
171
+ if (Number.isFinite(num)) {
172
+ const color = num >= 500 ? 'error' : num >= 400 ? 'warning' : num >= 200 && num < 300 ? 'success' : 'default';
173
+ return <Tag color={color}>{num}</Tag>;
174
+ }
175
+ const text = String(rawVal);
176
+ const lower = text.toLowerCase();
177
+ const color =
178
+ lower.includes('err') || lower.includes('fatal') || lower.includes('crit')
179
+ ? 'error'
180
+ : lower.includes('warn')
181
+ ? 'warning'
182
+ : lower.includes('ok') || lower.includes('info')
183
+ ? 'processing'
184
+ : 'default';
185
+ return <Tag color={color}>{text}</Tag>;
186
+ }
187
+ if (formatType === 'url') {
188
+ const text = String(rawVal).trim();
189
+ if (/^https?:\/\//i.test(text)) {
190
+ return (
191
+ <a href={text} target="_blank" rel="noopener noreferrer" onClick={(e) => e.stopPropagation()}>
192
+ {text}
193
+ </a>
194
+ );
195
+ }
196
+ return text;
197
+ }
198
+ return formatCellValue(rawVal);
199
+ }
200
+
201
+ export interface ElasticReportRendererProps {
202
+ title: string;
203
+ spec: ReportSpec;
204
+ dataView?: EsDataViewRecord | null;
205
+ fields?: EsFieldCapability[];
206
+ result?: ReportExecutionResult | null;
207
+ loading?: boolean;
208
+ error?: string | null;
209
+ showToolbar?: boolean;
210
+ compact?: boolean;
211
+ onExecute: (overrides: ReportRuntimeOverrides) => void;
212
+ onCrossFilter?: (filterItem: ReportFilterItem) => void;
213
+ onInspectTopValues?: (field: string, overrides?: ReportRuntimeOverrides) => Promise<FieldTopValuesResult>;
214
+ onExport?: (format: ExportFormat, columns?: string[], overrides?: ReportRuntimeOverrides) => Promise<void>;
215
+ }
216
+
217
+ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
218
+ title,
219
+ spec,
220
+ dataView,
221
+ fields = [],
222
+ result,
223
+ loading = false,
224
+ error = null,
225
+ showToolbar = true,
226
+ compact = false,
227
+ onExecute,
228
+ onCrossFilter,
229
+ onInspectTopValues,
230
+ onExport,
231
+ }) => {
232
+ const t = useT();
233
+ const regionLabelId = useId();
234
+
235
+ const [queryText, setQueryText] = useState<string>(spec.query ?? '');
236
+ const [filters, setFilters] = useState<ReportFilterItem[]>(spec.filters ?? []);
237
+ const [sort, setSort] = useState<ReportSortItem[]>(spec.sort ?? []);
238
+ const [timeRange, setTimeRange] = useState<ReportTimeRange>(spec.timeRange ?? { preset: 'last_24h' });
239
+ const [customColumns, setCustomColumns] = useState<string[] | null>(null);
240
+ const [autoRefreshSec, setAutoRefreshSec] = useState<AutoRefreshInterval>(0);
241
+ const [page, setPage] = useState<number>(1);
242
+ const [cursorHistory, setCursorHistory] = useState<Array<Array<string | number | boolean | null>>>([]);
243
+
244
+ const [filterPopoverOpen, setFilterPopoverOpen] = useState(false);
245
+ const [editingFilterIdx, setEditingFilterIdx] = useState<number | null>(null);
246
+ const [draftFilterField, setDraftFilterField] = useState<string>('');
247
+ const [draftFilterOp, setDraftFilterOp] = useState<FilterOperator>('eq');
248
+ const [draftFilterValue, setDraftFilterValue] = useState<string>('');
249
+ const [draftFilterValueTo, setDraftFilterValueTo] = useState<string>('');
250
+
251
+ const [columnsPopoverOpen, setColumnsPopoverOpen] = useState(false);
252
+ const [fieldsExplorerOpen, setFieldsExplorerOpen] = useState(false);
253
+ const [selectedExploreField, setSelectedExploreField] = useState<string>('');
254
+ const [topValuesData, setTopValuesData] = useState<FieldTopValuesResult | null>(null);
255
+ const [topValuesLoading, setTopValuesLoading] = useState(false);
256
+ const [exporting, setExporting] = useState(false);
257
+
258
+ const [inspectDslOpen, setInspectDslOpen] = useState(false);
259
+ const [selectedDoc, setSelectedDoc] = useState<ReportRowHit | null>(null);
260
+
261
+ const serializedSpec = useMemo(() => JSON.stringify(spec), [spec]);
262
+ const appliedSpecRef = useRef<string>(serializedSpec);
263
+
264
+ useEffect(() => {
265
+ if (appliedSpecRef.current === serializedSpec) {
266
+ return;
267
+ }
268
+ appliedSpecRef.current = serializedSpec;
269
+ setQueryText(spec.query ?? '');
270
+ setFilters(spec.filters ?? []);
271
+ setSort(spec.sort ?? []);
272
+ setTimeRange(spec.timeRange ?? { preset: 'last_24h' });
273
+ setCustomColumns(null);
274
+ setPage(1);
275
+ setCursorHistory([]);
276
+ }, [serializedSpec, spec]);
277
+
278
+ const buildCurrentOverrides = (nextOverrides?: Partial<ReportRuntimeOverrides>): ReportRuntimeOverrides => ({
279
+ query: nextOverrides?.query !== undefined ? nextOverrides.query : queryText,
280
+ filters: nextOverrides?.filters !== undefined ? nextOverrides.filters : filters,
281
+ sort: nextOverrides?.sort !== undefined ? nextOverrides.sort : sort,
282
+ timeRange: nextOverrides?.timeRange !== undefined ? nextOverrides.timeRange : timeRange,
283
+ page: nextOverrides?.page ?? page,
284
+ pageSize: spec.pageSize ?? 20,
285
+ ...(nextOverrides?.searchAfter ? { searchAfter: nextOverrides.searchAfter } : {}),
286
+ ...(nextOverrides?.pitId ?? result?.pitId ? { pitId: nextOverrides?.pitId ?? result?.pitId } : {}),
287
+ });
288
+
289
+ const triggerQuery = (nextOverrides?: Partial<ReportRuntimeOverrides>) => {
290
+ const merged = buildCurrentOverrides({
291
+ ...nextOverrides,
292
+ page: nextOverrides?.page ?? 1,
293
+ });
294
+ onExecute(merged);
295
+ };
296
+
297
+ // Per-block Auto-Refresh timer (pauses automatically when browser tab is hidden)
298
+ const triggerRef = useRef(triggerQuery);
299
+ triggerRef.current = triggerQuery;
300
+ useEffect(() => {
301
+ if (!autoRefreshSec || autoRefreshSec <= 0) {
302
+ return;
303
+ }
304
+ const timer = setInterval(() => {
305
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
306
+ return;
307
+ }
308
+ triggerRef.current({ page });
309
+ }, autoRefreshSec * 1000);
310
+ return () => {
311
+ clearInterval(timer);
312
+ };
313
+ }, [autoRefreshSec, page]);
314
+
315
+ const aggregatableFields = useMemo(
316
+ () => fields.filter((f) => f.aggregatable || Boolean(f.keywordSubfield)),
317
+ [fields],
318
+ );
319
+
320
+ const selectableColumnFields = useMemo(() => fields.filter((f) => !f.isSubfield), [fields]);
321
+
322
+ const timeRangeOptions: Array<{ label: string; value: TimeRangePreset }> = useMemo(
323
+ () => [
324
+ { label: t('Last 15 minutes'), value: 'last_15m' },
325
+ { label: t('Last 1 hour'), value: 'last_1h' },
326
+ { label: t('Last 24 hours'), value: 'last_24h' },
327
+ { label: t('Last 7 days'), value: 'last_7d' },
328
+ { label: t('Last 30 days'), value: 'last_30d' },
329
+ { label: t('Last 90 days'), value: 'last_90d' },
330
+ { label: t('All time'), value: 'all' },
331
+ { label: t('Custom range'), value: 'custom' },
332
+ ],
333
+ [t],
334
+ );
335
+
336
+ const autoRefreshOptions: Array<{ label: string; value: AutoRefreshInterval }> = useMemo(
337
+ () => [
338
+ { label: t('Off'), value: 0 },
339
+ { label: '10s', value: 10 },
340
+ { label: '30s', value: 30 },
341
+ { label: '1m', value: 60 },
342
+ { label: '5m', value: 300 },
343
+ ],
344
+ [t],
345
+ );
346
+
347
+ const openAddFilterPopover = () => {
348
+ setEditingFilterIdx(null);
349
+ setDraftFilterOp('eq');
350
+ setDraftFilterValue('');
351
+ setDraftFilterValueTo('');
352
+ setFilterPopoverOpen(true);
353
+ };
354
+
355
+ const openEditFilterPopover = (idx: number) => {
356
+ const item = filters[idx];
357
+ if (!item) return;
358
+ setEditingFilterIdx(idx);
359
+ setDraftFilterField(item.field);
360
+ setDraftFilterOp(item.operator);
361
+ setDraftFilterValue(
362
+ Array.isArray(item.value) ? item.value.join(', ') : item.value !== undefined ? String(item.value) : '',
363
+ );
364
+ setDraftFilterValueTo(item.valueTo !== undefined ? String(item.valueTo) : '');
365
+ setFilterPopoverOpen(true);
366
+ };
367
+
368
+ const handleSaveFilterPill = () => {
369
+ if (!draftFilterField) return;
370
+ const opMeta = OPERATOR_OPTIONS.find((o) => o.value === draftFilterOp);
371
+ const parsedValue =
372
+ draftFilterOp === 'in' || draftFilterOp === 'not_in'
373
+ ? draftFilterValue
374
+ .split(',')
375
+ .map((part) => part.trim())
376
+ .filter(Boolean)
377
+ : draftFilterValue;
378
+ const nextItem: ReportFilterItem = {
379
+ id: editingFilterIdx !== null ? filters[editingFilterIdx]?.id ?? `${Date.now()}` : `${Date.now()}`,
380
+ field: draftFilterField,
381
+ operator: draftFilterOp,
382
+ ...(opMeta?.needsValue ? { value: parsedValue } : {}),
383
+ ...(opMeta?.needsRange && draftFilterValueTo ? { valueTo: draftFilterValueTo } : {}),
384
+ enabled: true,
385
+ };
386
+ const updated =
387
+ editingFilterIdx !== null
388
+ ? filters.map((item, i) => (i === editingFilterIdx ? nextItem : item))
389
+ : [...filters, nextItem];
390
+ setFilters(updated);
391
+ setPage(1);
392
+ setCursorHistory([]);
393
+ setFilterPopoverOpen(false);
394
+ setEditingFilterIdx(null);
395
+ setDraftFilterValue('');
396
+ setDraftFilterValueTo('');
397
+ triggerQuery({ filters: updated, page: 1 });
398
+ };
399
+
400
+ const applyQuickFieldFilter = useCallback(
401
+ (field: string, operator: 'eq' | 'ne', value: ScalarFilterValue) => {
402
+ const nextItem: ReportFilterItem = {
403
+ id: `${Date.now()}-${field}`,
404
+ field,
405
+ operator,
406
+ value,
407
+ enabled: true,
408
+ };
409
+ if (onCrossFilter) {
410
+ onCrossFilter(nextItem);
411
+ return;
412
+ }
413
+ setFilters((prev) => {
414
+ const updated = [...prev, nextItem];
415
+ triggerRef.current({ filters: updated, page: 1 });
416
+ return updated;
417
+ });
418
+ setPage(1);
419
+ setCursorHistory([]);
420
+ },
421
+ [onCrossFilter],
422
+ );
423
+
424
+ const handleRemoveFilter = (idx: number) => {
425
+ const updated = filters.filter((_, i) => i !== idx);
426
+ setFilters(updated);
427
+ setPage(1);
428
+ setCursorHistory([]);
429
+ triggerQuery({ filters: updated, page: 1 });
430
+ };
431
+
432
+ const handleReset = () => {
433
+ const baseQuery = spec.query ?? '';
434
+ const baseFilters = spec.filters ?? [];
435
+ const baseSort = spec.sort ?? [];
436
+ const baseTimeRange: ReportTimeRange = spec.timeRange ?? { preset: 'last_24h' };
437
+ setQueryText(baseQuery);
438
+ setFilters(baseFilters);
439
+ setSort(baseSort);
440
+ setTimeRange(baseTimeRange);
441
+ setCustomColumns(null);
442
+ setPage(1);
443
+ setCursorHistory([]);
444
+ onExecute({
445
+ query: baseQuery,
446
+ filters: baseFilters,
447
+ sort: baseSort,
448
+ timeRange: baseTimeRange,
449
+ page: 1,
450
+ pageSize: spec.pageSize ?? 20,
451
+ });
452
+ };
453
+
454
+ const handleBucketDrilldown = (bucketKey: string) => {
455
+ if (!showToolbar || spec.allowInteractiveControls === false) return;
456
+ const bucketField = spec.chart?.bucketField || dataView?.timeField;
457
+ if (!bucketField || spec.chart?.bucketType === 'date_histogram') return;
458
+ const item: ReportFilterItem = {
459
+ id: `${Date.now()}`,
460
+ field: bucketField,
461
+ operator: 'eq',
462
+ value: bucketKey,
463
+ enabled: true,
464
+ };
465
+ if (onCrossFilter) {
466
+ onCrossFilter(item);
467
+ return;
468
+ }
469
+ const updated = [...filters, item];
470
+ setFilters(updated);
471
+ triggerQuery({ filters: updated, page: 1 });
472
+ };
473
+
474
+ const handleSelectExploreField = async (fieldName: string) => {
475
+ setSelectedExploreField(fieldName);
476
+ if (!onInspectTopValues) return;
477
+ setTopValuesLoading(true);
478
+ try {
479
+ const top = await onInspectTopValues(fieldName, buildCurrentOverrides());
480
+ setTopValuesData(top);
481
+ } catch {
482
+ setTopValuesData(null);
483
+ } finally {
484
+ setTopValuesLoading(false);
485
+ }
486
+ };
487
+
488
+ const activeColumns = useMemo(
489
+ () => (customColumns && customColumns.length > 0 ? customColumns : result?.columns ?? spec.columns ?? []),
490
+ [customColumns, result?.columns, spec.columns],
491
+ );
492
+
493
+ const moveColumn = (index: number, direction: -1 | 1) => {
494
+ const nextIdx = index + direction;
495
+ if (nextIdx < 0 || nextIdx >= activeColumns.length) return;
496
+ const copy = [...activeColumns];
497
+ const [picked] = copy.splice(index, 1);
498
+ copy.splice(nextIdx, 0, picked);
499
+ setCustomColumns(copy);
500
+ };
501
+
502
+ const canInteract = showToolbar && spec.allowInteractiveControls !== false;
503
+ const currentOpMeta = OPERATOR_OPTIONS.find((o) => o.value === draftFilterOp);
504
+
505
+ const tableColumns: TableColumnsType<ReportRowHit> = useMemo(
506
+ () =>
507
+ activeColumns.map((colName) => {
508
+ const activeSort = sort.find((s) => s.field === colName || s.field === `${colName}.keyword`);
509
+ const canSortCol = aggregatableFields.some((f) => f.name === colName || f.name === `${colName}.keyword`);
510
+ const colFormat = spec.fieldFormats?.[colName];
511
+ const colWidth =
512
+ colName === '@timestamp' ? 200 : colName === 'message' || colName.endsWith('.message') ? 320 : 165;
513
+ return {
514
+ title: colName,
515
+ key: colName,
516
+ width: colWidth,
517
+ ellipsis: true,
518
+ ...(canSortCol
519
+ ? {
520
+ sorter: true,
521
+ sortOrder: activeSort ? (activeSort.order === 'asc' ? 'ascend' : 'descend') : null,
522
+ }
523
+ : {}),
524
+ render: (_: unknown, record: ReportRowHit) => {
525
+ const hl = record.highlights?.[colName]?.[0];
526
+ const rawVal =
527
+ colName === '_id'
528
+ ? record._id
529
+ : colName === '_index'
530
+ ? record._index
531
+ : getNestedValue(record.source, colName);
532
+ const scalarVal = colName !== '@timestamp' ? toScalarCandidate(rawVal) : undefined;
533
+
534
+ return (
535
+ <span
536
+ style={{
537
+ display: 'flex',
538
+ alignItems: 'center',
539
+ justifyContent: 'space-between',
540
+ gap: 6,
541
+ width: '100%',
542
+ maxWidth: '100%',
543
+ minWidth: 0,
544
+ }}
545
+ >
546
+ <span
547
+ style={{
548
+ flex: 1,
549
+ minWidth: 0,
550
+ overflow: 'hidden',
551
+ textOverflow: 'ellipsis',
552
+ whiteSpace: 'nowrap',
553
+ }}
554
+ >
555
+ {hl ? <HighlightText text={hl} /> : renderFormattedCell(rawVal, colFormat)}
556
+ </span>
557
+ {canInteract && scalarVal !== undefined && (
558
+ <span
559
+ style={{ display: 'inline-flex', gap: 2, flexShrink: 0, opacity: 0.65 }}
560
+ onClick={(e) => e.stopPropagation()}
561
+ >
562
+ <Tooltip title={t('Filter for value')}>
563
+ <Button
564
+ type="text"
565
+ size="small"
566
+ aria-label={`${t('Filter for value')}: ${colName}=${String(scalarVal)}`}
567
+ icon={<PlusCircleOutlined style={{ fontSize: 12 }} />}
568
+ style={{ width: 20, height: 20, padding: 0 }}
569
+ onClick={() => applyQuickFieldFilter(colName, 'eq', scalarVal)}
570
+ />
571
+ </Tooltip>
572
+ <Tooltip title={t('Filter out value')}>
573
+ <Button
574
+ type="text"
575
+ size="small"
576
+ aria-label={`${t('Filter out value')}: ${colName}!=${String(scalarVal)}`}
577
+ icon={<MinusCircleOutlined style={{ fontSize: 12 }} />}
578
+ style={{ width: 20, height: 20, padding: 0 }}
579
+ onClick={() => applyQuickFieldFilter(colName, 'ne', scalarVal)}
580
+ />
581
+ </Tooltip>
582
+ </span>
583
+ )}
584
+ </span>
585
+ );
586
+ },
587
+ };
588
+ }),
589
+ [activeColumns, aggregatableFields, applyQuickFieldFilter, canInteract, sort, spec.fieldFormats, t],
590
+ );
591
+
592
+ return (
593
+ <div style={{ width: '100%', maxWidth: '100%', minWidth: 0 }}>
594
+ {/* Polite status region announces updated hit counts for screen readers without putting aria-live on <table> */}
595
+ <div role="status" aria-live="polite" style={VISUALLY_HIDDEN_STYLE}>
596
+ {!loading && result ? `${title}: ${result.total} ${t('Hits')}` : ''}
597
+ </div>
598
+
599
+ {canInteract && (
600
+ <div style={{ marginBottom: 12, maxWidth: '100%' }}>
601
+ <Space wrap style={{ width: '100%', maxWidth: '100%', justifyContent: 'space-between' }}>
602
+ <Space wrap style={{ maxWidth: '100%' }}>
603
+ <ElasticKqlInput
604
+ ariaLabel={t('KQL / Search Query')}
605
+ placeholder={t('Search KQL, e.g. status >= 500 AND service: "api"')}
606
+ value={queryText}
607
+ fields={fields}
608
+ sampleRows={result?.rows}
609
+ style={{ width: compact ? 220 : 280, maxWidth: '100%' }}
610
+ onInspectTopValues={
611
+ onInspectTopValues
612
+ ? (field) => onInspectTopValues(field, buildCurrentOverrides({ query: '' }))
613
+ : undefined
614
+ }
615
+ onChange={(nextVal) => {
616
+ setQueryText(nextVal);
617
+ }}
618
+ onClear={() => {
619
+ setQueryText('');
620
+ setPage(1);
621
+ setCursorHistory([]);
622
+ triggerQuery({ query: '', page: 1 });
623
+ }}
624
+ onSubmit={(submittedVal) => {
625
+ setPage(1);
626
+ setCursorHistory([]);
627
+ triggerQuery({ query: submittedVal, page: 1 });
628
+ }}
629
+ />
630
+ {dataView?.timeField && (
631
+ <>
632
+ <Select
633
+ aria-label={t('Time Field')}
634
+ value={timeRange.preset}
635
+ options={timeRangeOptions}
636
+ style={{ minWidth: 150 }}
637
+ onChange={(nextPreset) => {
638
+ const nextRange: ReportTimeRange =
639
+ nextPreset === 'custom'
640
+ ? {
641
+ preset: 'custom',
642
+ from: timeRange.from ?? spec.timeRange?.from ?? 'now-24h',
643
+ to: timeRange.to ?? spec.timeRange?.to ?? 'now',
644
+ }
645
+ : { preset: nextPreset };
646
+ setTimeRange(nextRange);
647
+ setPage(1);
648
+ setCursorHistory([]);
649
+ triggerQuery({ timeRange: nextRange, page: 1 });
650
+ }}
651
+ />
652
+ {timeRange.preset === 'custom' && (
653
+ <Space.Compact>
654
+ <Input
655
+ aria-label={t('From')}
656
+ placeholder={t('From')}
657
+ value={timeRange.from ?? ''}
658
+ style={{ width: 165 }}
659
+ onChange={(e) => setTimeRange((prev) => ({ ...prev, preset: 'custom', from: e.target.value }))}
660
+ onPressEnter={() => {
661
+ setPage(1);
662
+ setCursorHistory([]);
663
+ triggerQuery({ timeRange, page: 1 });
664
+ }}
665
+ />
666
+ <Input
667
+ aria-label={t('To')}
668
+ placeholder={t('To')}
669
+ value={timeRange.to ?? ''}
670
+ style={{ width: 165 }}
671
+ onChange={(e) => setTimeRange((prev) => ({ ...prev, preset: 'custom', to: e.target.value }))}
672
+ onPressEnter={() => {
673
+ setPage(1);
674
+ setCursorHistory([]);
675
+ triggerQuery({ timeRange, page: 1 });
676
+ }}
677
+ />
678
+ </Space.Compact>
679
+ )}
680
+ </>
681
+ )}
682
+ <Popover
683
+ trigger="click"
684
+ title={editingFilterIdx !== null ? t('Edit Filter') : t('Add Filter')}
685
+ open={filterPopoverOpen}
686
+ onOpenChange={(open) => {
687
+ setFilterPopoverOpen(open);
688
+ if (!open) {
689
+ setEditingFilterIdx(null);
690
+ }
691
+ }}
692
+ content={
693
+ <div style={{ width: 280 }}>
694
+ <Form layout="vertical" size="small">
695
+ <Form.Item label={t('Field')} style={{ marginBottom: 8 }}>
696
+ <Select
697
+ showSearch
698
+ value={draftFilterField || undefined}
699
+ placeholder={t('Field')}
700
+ options={fields.map((f) => ({ label: `${f.name} (${f.type})`, value: f.name }))}
701
+ onChange={(val) => setDraftFilterField(val)}
702
+ />
703
+ </Form.Item>
704
+ <Form.Item label={t('Operator')} style={{ marginBottom: 8 }}>
705
+ <Select
706
+ value={draftFilterOp}
707
+ options={OPERATOR_OPTIONS.map((o) => ({ label: o.label, value: o.value }))}
708
+ onChange={(val) => setDraftFilterOp(val)}
709
+ />
710
+ </Form.Item>
711
+ {currentOpMeta?.needsValue && (
712
+ <Form.Item label={t('Value')} style={{ marginBottom: 8 }}>
713
+ <Input value={draftFilterValue} onChange={(e) => setDraftFilterValue(e.target.value)} />
714
+ </Form.Item>
715
+ )}
716
+ {currentOpMeta?.needsRange && (
717
+ <Form.Item label={t('To Value')} style={{ marginBottom: 8 }}>
718
+ <Input value={draftFilterValueTo} onChange={(e) => setDraftFilterValueTo(e.target.value)} />
719
+ </Form.Item>
720
+ )}
721
+ <Space style={{ justifyContent: 'flex-end', width: '100%' }}>
722
+ <Button
723
+ size="small"
724
+ onClick={() => {
725
+ setFilterPopoverOpen(false);
726
+ setEditingFilterIdx(null);
727
+ }}
728
+ >
729
+ {t('Cancel')}
730
+ </Button>
731
+ <Button size="small" type="primary" onClick={handleSaveFilterPill}>
732
+ {t('Apply')}
733
+ </Button>
734
+ </Space>
735
+ </Form>
736
+ </div>
737
+ }
738
+ >
739
+ <Button icon={<FilterOutlined />} onClick={openAddFilterPopover}>
740
+ {t('Add Filter')}
741
+ </Button>
742
+ </Popover>
743
+
744
+ {spec.visualization === 'table' && aggregatableFields.length > 0 && (
745
+ <Select
746
+ allowClear
747
+ aria-label={t('Sort')}
748
+ placeholder={t('Sort')}
749
+ style={{ minWidth: 165 }}
750
+ value={sort[0] ? `${sort[0].field}:${sort[0].order}` : undefined}
751
+ options={aggregatableFields.slice(0, 40).flatMap((f) => [
752
+ { label: `${f.name} ↓`, value: `${f.name}:desc` },
753
+ { label: `${f.name} ↑`, value: `${f.name}:asc` },
754
+ ])}
755
+ onChange={(encoded) => {
756
+ if (!encoded) {
757
+ setSort([]);
758
+ setPage(1);
759
+ setCursorHistory([]);
760
+ triggerQuery({ sort: [], page: 1 });
761
+ return;
762
+ }
763
+ const lastColon = encoded.lastIndexOf(':');
764
+ const nextSort: ReportSortItem[] = [
765
+ {
766
+ field: encoded.slice(0, lastColon),
767
+ order: encoded.slice(lastColon + 1) === 'asc' ? 'asc' : 'desc',
768
+ },
769
+ ];
770
+ setSort(nextSort);
771
+ setPage(1);
772
+ setCursorHistory([]);
773
+ triggerQuery({ sort: nextSort, page: 1 });
774
+ }}
775
+ />
776
+ )}
777
+
778
+ {spec.visualization === 'table' && selectableColumnFields.length > 0 && (
779
+ <Popover
780
+ trigger="click"
781
+ title={t('Visible Columns')}
782
+ open={columnsPopoverOpen}
783
+ onOpenChange={setColumnsPopoverOpen}
784
+ content={
785
+ <div style={{ width: 280 }}>
786
+ <Select
787
+ mode="multiple"
788
+ style={{ width: '100%', marginBottom: 8 }}
789
+ value={activeColumns}
790
+ options={selectableColumnFields.map((f) => ({ label: f.name, value: f.name }))}
791
+ onChange={(cols) => setCustomColumns(cols)}
792
+ />
793
+ <div style={{ maxHeight: 200, overflowY: 'auto' }}>
794
+ {activeColumns.map((col, idx) => (
795
+ <div
796
+ key={col}
797
+ style={{
798
+ display: 'flex',
799
+ justifyContent: 'space-between',
800
+ alignItems: 'center',
801
+ padding: '3px 0',
802
+ fontSize: 12,
803
+ }}
804
+ >
805
+ <Text ellipsis style={{ maxWidth: 190 }}>
806
+ {col}
807
+ </Text>
808
+ <Space size={2}>
809
+ <Button
810
+ size="small"
811
+ type="text"
812
+ aria-label={`${t('Move up')}: ${col}`}
813
+ disabled={idx === 0}
814
+ icon={<ArrowUpOutlined />}
815
+ onClick={() => moveColumn(idx, -1)}
816
+ />
817
+ <Button
818
+ size="small"
819
+ type="text"
820
+ aria-label={`${t('Move down')}: ${col}`}
821
+ disabled={idx === activeColumns.length - 1}
822
+ icon={<ArrowDownOutlined />}
823
+ onClick={() => moveColumn(idx, 1)}
824
+ />
825
+ </Space>
826
+ </div>
827
+ ))}
828
+ </div>
829
+ </div>
830
+ }
831
+ >
832
+ <Button icon={<SettingOutlined />}>{t('Columns')}</Button>
833
+ </Popover>
834
+ )}
835
+
836
+ {spec.visualization === 'table' && onInspectTopValues && fields.length > 0 && (
837
+ <Button
838
+ icon={<DatabaseOutlined />}
839
+ onClick={() => {
840
+ setFieldsExplorerOpen(true);
841
+ if (!selectedExploreField && selectableColumnFields[0]) {
842
+ handleSelectExploreField(selectableColumnFields[0].name);
843
+ }
844
+ }}
845
+ >
846
+ {t('Fields Explorer')}
847
+ </Button>
848
+ )}
849
+ </Space>
850
+
851
+ <Space wrap>
852
+ <Select
853
+ aria-label={t('Auto refresh')}
854
+ suffixIcon={<ClockCircleOutlined />}
855
+ value={autoRefreshSec}
856
+ options={autoRefreshOptions}
857
+ style={{ width: 92 }}
858
+ onChange={(sec: AutoRefreshInterval) => setAutoRefreshSec(sec)}
859
+ />
860
+ <Button
861
+ type="primary"
862
+ icon={<SearchOutlined />}
863
+ onClick={() => {
864
+ setPage(1);
865
+ setCursorHistory([]);
866
+ triggerQuery({ page: 1 });
867
+ }}
868
+ >
869
+ {t('Search')}
870
+ </Button>
871
+ <Button icon={<ReloadOutlined />} aria-label={t('Refresh')} onClick={() => triggerQuery({ page })} />
872
+ <Button icon={<RollbackOutlined />} onClick={handleReset}>
873
+ {t('Reset')}
874
+ </Button>
875
+ {onExport && spec.allowExport !== false && (
876
+ <Dropdown
877
+ menu={{
878
+ items: [
879
+ {
880
+ key: 'csv',
881
+ label: t('Export CSV'),
882
+ onClick: async () => {
883
+ setExporting(true);
884
+ try {
885
+ await onExport('csv', activeColumns, buildCurrentOverrides());
886
+ } finally {
887
+ setExporting(false);
888
+ }
889
+ },
890
+ },
891
+ {
892
+ key: 'ndjson',
893
+ label: t('Export NDJSON'),
894
+ onClick: async () => {
895
+ setExporting(true);
896
+ try {
897
+ await onExport('ndjson', activeColumns, buildCurrentOverrides());
898
+ } finally {
899
+ setExporting(false);
900
+ }
901
+ },
902
+ },
903
+ ],
904
+ }}
905
+ >
906
+ <Button loading={exporting} icon={<DownloadOutlined />}>
907
+ {t('Export CSV')}
908
+ </Button>
909
+ </Dropdown>
910
+ )}
911
+ {result?.compiledDsl && (
912
+ <Button icon={<CodeOutlined />} onClick={() => setInspectDslOpen(true)}>
913
+ {t('Inspect DSL')}
914
+ </Button>
915
+ )}
916
+ </Space>
917
+ </Space>
918
+
919
+ {((spec.lockedFilters?.length ?? 0) > 0 || filters.length > 0) && (
920
+ <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
921
+ {(spec.lockedFilters ?? []).map((flt, idx) => (
922
+ <Tag key={flt.id || `locked-${flt.field}-${idx}`} icon={<LockOutlined />} color="gold">
923
+ {flt.field} {flt.operator}
924
+ {flt.value !== undefined
925
+ ? ` ${Array.isArray(flt.value) ? flt.value.join(', ') : String(flt.value)}`
926
+ : ''}
927
+ {flt.valueTo !== undefined ? ` .. ${String(flt.valueTo)}` : ''}
928
+ </Tag>
929
+ ))}
930
+ {filters.map((flt, idx) => (
931
+ <Tag
932
+ key={flt.id || `${flt.field}-${idx}`}
933
+ closable
934
+ color="processing"
935
+ onClose={(e) => {
936
+ e.preventDefault();
937
+ e.stopPropagation();
938
+ handleRemoveFilter(idx);
939
+ }}
940
+ >
941
+ <span
942
+ role="button"
943
+ tabIndex={0}
944
+ aria-label={`${t('Edit Filter')}: ${flt.field}`}
945
+ style={{ cursor: 'pointer' }}
946
+ onClick={() => openEditFilterPopover(idx)}
947
+ onKeyDown={(e) => {
948
+ if (e.key === 'Enter' || e.key === ' ') {
949
+ e.preventDefault();
950
+ openEditFilterPopover(idx);
951
+ }
952
+ }}
953
+ >
954
+ {flt.field} {flt.operator}
955
+ {flt.value !== undefined
956
+ ? ` ${Array.isArray(flt.value) ? flt.value.join(', ') : String(flt.value)}`
957
+ : ''}
958
+ {flt.valueTo !== undefined ? ` .. ${String(flt.valueTo)}` : ''}
959
+ </span>
960
+ </Tag>
961
+ ))}
962
+ </div>
963
+ )}
964
+ </div>
965
+ )}
966
+
967
+ {!canInteract && (spec.lockedFilters?.length ?? 0) > 0 && (
968
+ <div style={{ marginBottom: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
969
+ {(spec.lockedFilters ?? []).map((flt, idx) => (
970
+ <Tag key={flt.id || `locked-${flt.field}-${idx}`} icon={<LockOutlined />} color="gold">
971
+ {flt.field} {flt.operator}
972
+ {flt.value !== undefined ? ` ${Array.isArray(flt.value) ? flt.value.join(', ') : String(flt.value)}` : ''}
973
+ {flt.valueTo !== undefined ? ` .. ${String(flt.valueTo)}` : ''}
974
+ </Tag>
975
+ ))}
976
+ </div>
977
+ )}
978
+
979
+ {error && <Alert type="error" showIcon message={error} style={{ marginBottom: 12 }} />}
980
+
981
+ {result && (result.timedOut || (result.shards && result.shards.failed > 0)) && (
982
+ <Alert
983
+ type="warning"
984
+ showIcon
985
+ style={{ marginBottom: 12 }}
986
+ message={t('Partial results warning')}
987
+ description={
988
+ <>
989
+ {result.timedOut && <div>{t('Query timed out; displayed results may be incomplete.')}</div>}
990
+ {result.shards && result.shards.failed > 0 && (
991
+ <div>
992
+ {t('Failed shards')}: {result.shards.failed} / {result.shards.total}
993
+ </div>
994
+ )}
995
+ </>
996
+ }
997
+ />
998
+ )}
999
+
1000
+ <Spin spinning={loading}>
1001
+ {!result ? (
1002
+ <Empty description={t('No matching documents')} />
1003
+ ) : spec.visualization === 'table' ? (
1004
+ <div>
1005
+ {result.histogram.length > 0 && spec.chart?.showHistogram !== false && (
1006
+ <ReportHistogramStrip buckets={result.histogram} />
1007
+ )}
1008
+ <div
1009
+ style={{
1010
+ display: 'flex',
1011
+ justifyContent: 'space-between',
1012
+ alignItems: 'center',
1013
+ marginBottom: 8,
1014
+ fontSize: 12,
1015
+ }}
1016
+ >
1017
+ <Text id={regionLabelId} strong>
1018
+ {title} · {t('Hits')}: {result.total.toLocaleString()}
1019
+ {result.totalRelation === 'gte' ? '+' : ''} ({result.tookMs} ms)
1020
+ </Text>
1021
+ {result.nextSearchAfter && cursorHistory.length > 0 && (
1022
+ <Button
1023
+ size="small"
1024
+ onClick={() => {
1025
+ setPage(1);
1026
+ setCursorHistory([]);
1027
+ triggerQuery({ page: 1 });
1028
+ }}
1029
+ >
1030
+ {t('First page')}
1031
+ </Button>
1032
+ )}
1033
+ </div>
1034
+
1035
+ <div
1036
+ role="region"
1037
+ aria-labelledby={regionLabelId}
1038
+ tabIndex={0}
1039
+ style={{ width: '100%', maxWidth: '100%', minWidth: 0, overflowX: 'auto' }}
1040
+ >
1041
+ <Table<ReportRowHit>
1042
+ size={compact ? 'small' : 'middle'}
1043
+ scroll={{ x: 'max-content' }}
1044
+ rowKey={(record) => `${record._index}:${record._id}`}
1045
+ columns={tableColumns}
1046
+ dataSource={result.rows}
1047
+ onRow={(record) => ({
1048
+ onClick: () => setSelectedDoc(record),
1049
+ style: { cursor: 'pointer' },
1050
+ })}
1051
+ onChange={(pagination, _tableFilters, sorter) => {
1052
+ const singleSorter = Array.isArray(sorter) ? sorter[0] : sorter;
1053
+ if (singleSorter && singleSorter.columnKey && singleSorter.order) {
1054
+ const nextSort: ReportSortItem[] = [
1055
+ {
1056
+ field: String(singleSorter.columnKey),
1057
+ order: singleSorter.order === 'ascend' ? 'asc' : 'desc',
1058
+ },
1059
+ ];
1060
+ setSort(nextSort);
1061
+ setPage(1);
1062
+ setCursorHistory([]);
1063
+ triggerQuery({ sort: nextSort, page: 1 });
1064
+ return;
1065
+ }
1066
+
1067
+ const nextPage = pagination.current ?? 1;
1068
+ const pageSize = spec.pageSize ?? 20;
1069
+ if (nextPage * pageSize > 10000 && result.nextSearchAfter) {
1070
+ const updatedHistory = [...cursorHistory, result.nextSearchAfter];
1071
+ setCursorHistory(updatedHistory);
1072
+ setPage(nextPage);
1073
+ triggerQuery({ page: nextPage, searchAfter: result.nextSearchAfter, pitId: result.pitId });
1074
+ return;
1075
+ }
1076
+ setPage(nextPage);
1077
+ triggerQuery({ page: nextPage });
1078
+ }}
1079
+ pagination={{
1080
+ current: page,
1081
+ pageSize: spec.pageSize ?? 20,
1082
+ total: Math.min(result.total, 10000),
1083
+ showSizeChanger: false,
1084
+ }}
1085
+ />
1086
+ </div>
1087
+
1088
+ {result.total >= 10000 && result.nextSearchAfter && (
1089
+ <div style={{ marginTop: 8, textAlign: 'right' }}>
1090
+ <Button
1091
+ size="small"
1092
+ onClick={() => {
1093
+ if (!result.nextSearchAfter) return;
1094
+ const updatedHistory = [...cursorHistory, result.nextSearchAfter];
1095
+ setCursorHistory(updatedHistory);
1096
+ setPage((p) => p + 1);
1097
+ triggerQuery({ searchAfter: result.nextSearchAfter, pitId: result.pitId });
1098
+ }}
1099
+ >
1100
+ {t('Next cursor page')}
1101
+ </Button>
1102
+ </div>
1103
+ )}
1104
+ </div>
1105
+ ) : (
1106
+ <ElasticBasicChart
1107
+ title={title}
1108
+ visualization={spec.visualization}
1109
+ series={result.series}
1110
+ seriesKeys={result.seriesKeys}
1111
+ stackMode={spec.chart?.stackMode}
1112
+ metricValue={result.metricValue}
1113
+ previousMetricValue={result.previousMetricValue}
1114
+ deltaPercent={result.deltaPercent}
1115
+ metricLabel={result.metricLabel}
1116
+ metricType={spec.chart?.metricType}
1117
+ totalHits={result.total}
1118
+ totalRelation={result.totalRelation}
1119
+ onSelectBucket={handleBucketDrilldown}
1120
+ />
1121
+ )}
1122
+ </Spin>
1123
+
1124
+ <Modal
1125
+ title={t('Elasticsearch Query DSL')}
1126
+ open={inspectDslOpen}
1127
+ footer={null}
1128
+ onCancel={() => setInspectDslOpen(false)}
1129
+ width="min(680px, calc(100vw - 32px))"
1130
+ >
1131
+ <pre style={{ maxHeight: 420, overflow: 'auto', fontSize: 12 }}>
1132
+ {JSON.stringify(result?.compiledDsl ?? {}, null, 2)}
1133
+ </pre>
1134
+ </Modal>
1135
+
1136
+ <Drawer
1137
+ title={t('Fields Explorer')}
1138
+ open={fieldsExplorerOpen}
1139
+ onClose={() => setFieldsExplorerOpen(false)}
1140
+ width="min(420px, 92vw)"
1141
+ >
1142
+ <Space direction="vertical" size={12} style={{ width: '100%' }}>
1143
+ <Select
1144
+ showSearch
1145
+ style={{ width: '100%' }}
1146
+ value={selectedExploreField || undefined}
1147
+ placeholder={t('Field')}
1148
+ options={selectableColumnFields.map((f) => ({ label: `${f.name} (${f.type})`, value: f.name }))}
1149
+ onChange={(val) => {
1150
+ handleSelectExploreField(val);
1151
+ }}
1152
+ />
1153
+ <Spin spinning={topValuesLoading}>
1154
+ {topValuesData && topValuesData.buckets.length > 0 ? (
1155
+ <Space direction="vertical" size={8} style={{ width: '100%' }}>
1156
+ <Text type="secondary" style={{ fontSize: 12 }}>
1157
+ {t('Top values')} · {t('Hits')}: {topValuesData.totalDocs.toLocaleString()}
1158
+ </Text>
1159
+ {topValuesData.buckets.map((bucket) => (
1160
+ <div key={bucket.value} style={{ fontSize: 12 }}>
1161
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
1162
+ <Text ellipsis style={{ maxWidth: 220 }}>
1163
+ {bucket.value}
1164
+ </Text>
1165
+ <Space size={4}>
1166
+ <Text type="secondary">
1167
+ {bucket.count} ({bucket.percentage}%)
1168
+ </Text>
1169
+ <Button
1170
+ type="text"
1171
+ size="small"
1172
+ aria-label={`${t('Filter for value')}: ${selectedExploreField}=${bucket.value}`}
1173
+ icon={<PlusCircleOutlined />}
1174
+ onClick={() => applyQuickFieldFilter(selectedExploreField, 'eq', bucket.value)}
1175
+ />
1176
+ <Button
1177
+ type="text"
1178
+ size="small"
1179
+ aria-label={`${t('Filter out value')}: ${selectedExploreField}!=${bucket.value}`}
1180
+ icon={<MinusCircleOutlined />}
1181
+ onClick={() => applyQuickFieldFilter(selectedExploreField, 'ne', bucket.value)}
1182
+ />
1183
+ </Space>
1184
+ </div>
1185
+ <Progress percent={bucket.percentage} showInfo={false} size="small" />
1186
+ </div>
1187
+ ))}
1188
+ </Space>
1189
+ ) : (
1190
+ <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('No matching documents')} />
1191
+ )}
1192
+ </Spin>
1193
+ </Space>
1194
+ </Drawer>
1195
+
1196
+ <Drawer
1197
+ title={t('Document Details')}
1198
+ open={Boolean(selectedDoc)}
1199
+ onClose={() => setSelectedDoc(null)}
1200
+ width="min(640px, 94vw)"
1201
+ >
1202
+ {selectedDoc && (
1203
+ <Tabs
1204
+ items={[
1205
+ {
1206
+ key: 'table',
1207
+ label: t('Table View'),
1208
+ children: (
1209
+ <Descriptions bordered column={1} size="small">
1210
+ <Descriptions.Item label="_index">{selectedDoc._index}</Descriptions.Item>
1211
+ <Descriptions.Item label="_id">{selectedDoc._id}</Descriptions.Item>
1212
+ {Object.entries(selectedDoc.source).map(([k, v]) => (
1213
+ <Descriptions.Item key={k} label={k}>
1214
+ <Space>
1215
+ <span>{formatCellValue(v)}</span>
1216
+ {canInteract && toScalarCandidate(v) !== undefined && (
1217
+ <>
1218
+ <Button
1219
+ type="text"
1220
+ size="small"
1221
+ icon={<PlusCircleOutlined />}
1222
+ onClick={() =>
1223
+ applyQuickFieldFilter(k, 'eq', toScalarCandidate(v) as ScalarFilterValue)
1224
+ }
1225
+ />
1226
+ <Button
1227
+ type="text"
1228
+ size="small"
1229
+ icon={<MinusCircleOutlined />}
1230
+ onClick={() =>
1231
+ applyQuickFieldFilter(k, 'ne', toScalarCandidate(v) as ScalarFilterValue)
1232
+ }
1233
+ />
1234
+ </>
1235
+ )}
1236
+ </Space>
1237
+ </Descriptions.Item>
1238
+ ))}
1239
+ </Descriptions>
1240
+ ),
1241
+ },
1242
+ {
1243
+ key: 'json',
1244
+ label: t('JSON View'),
1245
+ children: (
1246
+ <pre style={{ maxHeight: 520, overflow: 'auto', fontSize: 12 }}>
1247
+ {JSON.stringify(selectedDoc, null, 2)}
1248
+ </pre>
1249
+ ),
1250
+ },
1251
+ ]}
1252
+ />
1253
+ )}
1254
+ </Drawer>
1255
+ </div>
1256
+ );
1257
+ };