plugin-elastic-report 0.1.1 → 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 (80) 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/dist/ai/skills/elastic-report/SKILLS.md +52 -0
  6. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  7. package/dist/client/index.js +1 -1
  8. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  9. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  10. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  11. package/dist/client-v2/index.js +1 -1
  12. package/dist/externalVersion.js +5 -3
  13. package/dist/locale/en-US.json +213 -99
  14. package/dist/locale/vi-VN.json +213 -99
  15. package/dist/locale/zh-CN.json +213 -99
  16. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  17. package/dist/server/acl-guard.js +97 -25
  18. package/dist/server/collections/es-report-data-views.js +6 -0
  19. package/dist/server/collections/es-reports.js +6 -0
  20. package/dist/server/mcp/ElasticReportToolCatalog.js +238 -14
  21. package/dist/server/plugin.js +156 -22
  22. package/dist/server/report-block-tools.js +340 -0
  23. package/dist/server/services/ElasticReportService.js +137 -17
  24. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  25. package/dist/server/services/ReportExportService.js +243 -0
  26. package/dist/server/services/ReportQueryCompiler.js +532 -91
  27. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  28. package/dist/shared/constants.js +26 -2
  29. package/package.json +3 -3
  30. package/server.d.ts +2 -2
  31. package/server.js +1 -1
  32. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  33. package/src/client/index.tsx +34 -19
  34. package/src/client/workflow-instructions.tsx +44 -0
  35. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -311
  36. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  37. package/src/client-v2/api.ts +320 -224
  38. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  39. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -399
  40. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  41. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  42. package/src/client-v2/components/ElasticReportBlock.tsx +306 -160
  43. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -707
  44. package/src/client-v2/components/HighlightText.tsx +50 -50
  45. package/src/client-v2/components/ReportSelect.tsx +85 -72
  46. package/src/client-v2/index.tsx +14 -14
  47. package/src/client-v2/locale.ts +23 -23
  48. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  49. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -85
  50. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1047
  51. package/src/client-v2/plugin.tsx +107 -52
  52. package/src/client-v2/report-destination.tsx +126 -0
  53. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  54. package/src/client-v2/workflow/instructions.tsx +149 -0
  55. package/src/index.ts +11 -11
  56. package/src/locale/en-US.json +213 -99
  57. package/src/locale/vi-VN.json +213 -99
  58. package/src/locale/zh-CN.json +213 -99
  59. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  60. package/src/server/__tests__/query-compiler.test.ts +620 -231
  61. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -377
  62. package/src/server/acl-guard.ts +194 -103
  63. package/src/server/collections/es-report-data-views.ts +64 -58
  64. package/src/server/collections/es-reports.ts +80 -74
  65. package/src/server/index.ts +15 -15
  66. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  67. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -417
  68. package/src/server/plugin.ts +599 -431
  69. package/src/server/report-block-tools.ts +400 -0
  70. package/src/server/services/ElasticReportService.ts +494 -326
  71. package/src/server/services/ElasticsearchConnectionService.ts +728 -401
  72. package/src/server/services/ReportExportService.ts +282 -0
  73. package/src/server/services/ReportQueryCompiler.ts +1552 -1017
  74. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  75. package/src/shared/constants.ts +39 -29
  76. package/src/shared/types.ts +272 -175
  77. package/ai/skills/elastic-report/SKILLS.md +0 -32
  78. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
  79. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  80. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,707 +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 { CodeOutlined, FilterOutlined, ReloadOutlined, RollbackOutlined, SearchOutlined } from '@ant-design/icons';
11
- import {
12
- Alert,
13
- Button,
14
- Descriptions,
15
- Drawer,
16
- Empty,
17
- Form,
18
- Input,
19
- Modal,
20
- Popover,
21
- Select,
22
- Space,
23
- Spin,
24
- Table,
25
- Tabs,
26
- Tag,
27
- Typography,
28
- } from 'antd';
29
- import type { TableColumnsType } from 'antd';
30
- import React, { useEffect, useId, useMemo, useRef, useState } from 'react';
31
- import type {
32
- EsDataViewRecord,
33
- EsFieldCapability,
34
- FilterOperator,
35
- ReportExecutionResult,
36
- ReportFilterItem,
37
- ReportRowHit,
38
- ReportRuntimeOverrides,
39
- ReportSortItem,
40
- ReportSpec,
41
- TimeRangePreset,
42
- } from '../../shared/types';
43
- import { useT } from '../locale';
44
- import { ElasticBasicChart, ReportHistogramStrip } from './ElasticBasicCharts';
45
- import { HighlightText } from './HighlightText';
46
-
47
- const { Text } = Typography;
48
-
49
- const VISUALLY_HIDDEN_STYLE: React.CSSProperties = {
50
- position: 'absolute',
51
- clipPath: 'inset(50%)',
52
- overflow: 'hidden',
53
- width: 1,
54
- height: 1,
55
- margin: -1,
56
- padding: 0,
57
- border: 0,
58
- whiteSpace: 'nowrap',
59
- };
60
-
61
- const OPERATOR_OPTIONS: Array<{ label: string; value: FilterOperator; needsValue: boolean; needsRange?: boolean }> = [
62
- { label: 'is (=)', value: 'eq', needsValue: true },
63
- { label: 'is not (!=)', value: 'ne', needsValue: true },
64
- { label: 'contains', value: 'contains', needsValue: true },
65
- { label: 'is one of (in)', value: 'in', needsValue: true },
66
- { label: 'is not one of', value: 'not_in', needsValue: true },
67
- { label: '>', value: 'gt', needsValue: true },
68
- { label: '>=', value: 'gte', needsValue: true },
69
- { label: '<', value: 'lt', needsValue: true },
70
- { label: '<=', value: 'lte', needsValue: true },
71
- { label: 'between', value: 'between', needsValue: true, needsRange: true },
72
- { label: 'exists', value: 'exists', needsValue: false },
73
- { label: 'does not exist', value: 'not_exists', needsValue: false },
74
- ];
75
-
76
- function getNestedValue(source: Record<string, unknown>, path: string): unknown {
77
- if (path in source) return source[path];
78
- const parts = path.split('.');
79
- let current: unknown = source;
80
- for (const part of parts) {
81
- if (
82
- current &&
83
- typeof current === 'object' &&
84
- !Array.isArray(current) &&
85
- part in (current as Record<string, unknown>)
86
- ) {
87
- current = (current as Record<string, unknown>)[part];
88
- } else {
89
- return undefined;
90
- }
91
- }
92
- return current;
93
- }
94
-
95
- function formatCellValue(value: unknown): string {
96
- if (value === null || value === undefined) return '—';
97
- if (typeof value === 'string') return value;
98
- if (typeof value === 'number' || typeof value === 'boolean') return String(value);
99
- try {
100
- return JSON.stringify(value);
101
- } catch {
102
- return String(value);
103
- }
104
- }
105
-
106
- export interface ElasticReportRendererProps {
107
- title: string;
108
- spec: ReportSpec;
109
- dataView?: EsDataViewRecord | null;
110
- fields?: EsFieldCapability[];
111
- result?: ReportExecutionResult | null;
112
- loading?: boolean;
113
- error?: string | null;
114
- showToolbar?: boolean;
115
- compact?: boolean;
116
- onExecute: (overrides: ReportRuntimeOverrides) => void;
117
- }
118
-
119
- export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
120
- title,
121
- spec,
122
- dataView,
123
- fields = [],
124
- result,
125
- loading = false,
126
- error = null,
127
- showToolbar = true,
128
- compact = false,
129
- onExecute,
130
- }) => {
131
- const t = useT();
132
- const regionLabelId = useId();
133
-
134
- const [queryText, setQueryText] = useState<string>(spec.query ?? '');
135
- const [filters, setFilters] = useState<ReportFilterItem[]>(spec.filters ?? []);
136
- const [sort, setSort] = useState<ReportSortItem[]>(spec.sort ?? []);
137
- const [timePreset, setTimePreset] = useState<TimeRangePreset>(spec.timeRange?.preset ?? 'last_24h');
138
- const [page, setPage] = useState<number>(1);
139
- const [cursorHistory, setCursorHistory] = useState<Array<Array<string | number | boolean | null>>>([]);
140
-
141
- const [filterPopoverOpen, setFilterPopoverOpen] = useState(false);
142
- const [editingFilterIdx, setEditingFilterIdx] = useState<number | null>(null);
143
- const [draftFilterField, setDraftFilterField] = useState<string>('');
144
- const [draftFilterOp, setDraftFilterOp] = useState<FilterOperator>('eq');
145
- const [draftFilterValue, setDraftFilterValue] = useState<string>('');
146
- const [draftFilterValueTo, setDraftFilterValueTo] = useState<string>('');
147
-
148
- const [inspectDslOpen, setInspectDslOpen] = useState(false);
149
- const [selectedDoc, setSelectedDoc] = useState<ReportRowHit | null>(null);
150
-
151
- const serializedSpec = useMemo(() => JSON.stringify(spec), [spec]);
152
- const appliedSpecRef = useRef<string>(serializedSpec);
153
-
154
- useEffect(() => {
155
- if (appliedSpecRef.current === serializedSpec) {
156
- return;
157
- }
158
- appliedSpecRef.current = serializedSpec;
159
- setQueryText(spec.query ?? '');
160
- setFilters(spec.filters ?? []);
161
- setSort(spec.sort ?? []);
162
- setTimePreset(spec.timeRange?.preset ?? 'last_24h');
163
- setPage(1);
164
- setCursorHistory([]);
165
- }, [serializedSpec, spec]);
166
-
167
- const aggregatableFields = useMemo(
168
- () => fields.filter((f) => f.aggregatable || Boolean(f.keywordSubfield)),
169
- [fields],
170
- );
171
-
172
- const timeRangeOptions: Array<{ label: string; value: TimeRangePreset }> = useMemo(
173
- () => [
174
- { label: t('Last 15 minutes'), value: 'last_15m' },
175
- { label: t('Last 1 hour'), value: 'last_1h' },
176
- { label: t('Last 24 hours'), value: 'last_24h' },
177
- { label: t('Last 7 days'), value: 'last_7d' },
178
- { label: t('Last 30 days'), value: 'last_30d' },
179
- { label: t('Last 90 days'), value: 'last_90d' },
180
- { label: t('All time'), value: 'all' },
181
- ],
182
- [t],
183
- );
184
-
185
- const triggerQuery = (nextOverrides?: Partial<ReportRuntimeOverrides>) => {
186
- const merged: ReportRuntimeOverrides = {
187
- query: nextOverrides?.query !== undefined ? nextOverrides.query : queryText,
188
- filters: nextOverrides?.filters !== undefined ? nextOverrides.filters : filters,
189
- sort: nextOverrides?.sort !== undefined ? nextOverrides.sort : sort,
190
- timeRange: nextOverrides?.timeRange !== undefined ? nextOverrides.timeRange : { preset: timePreset },
191
- page: nextOverrides?.page ?? 1,
192
- pageSize: spec.pageSize ?? 20,
193
- ...(nextOverrides?.searchAfter ? { searchAfter: nextOverrides.searchAfter } : {}),
194
- };
195
- onExecute(merged);
196
- };
197
-
198
- const openAddFilterPopover = () => {
199
- setEditingFilterIdx(null);
200
- setDraftFilterOp('eq');
201
- setDraftFilterValue('');
202
- setDraftFilterValueTo('');
203
- setFilterPopoverOpen(true);
204
- };
205
-
206
- const openEditFilterPopover = (idx: number) => {
207
- const item = filters[idx];
208
- if (!item) return;
209
- setEditingFilterIdx(idx);
210
- setDraftFilterField(item.field);
211
- setDraftFilterOp(item.operator);
212
- setDraftFilterValue(
213
- Array.isArray(item.value) ? item.value.join(', ') : item.value !== undefined ? String(item.value) : '',
214
- );
215
- setDraftFilterValueTo(item.valueTo !== undefined ? String(item.valueTo) : '');
216
- setFilterPopoverOpen(true);
217
- };
218
-
219
- const handleSaveFilterPill = () => {
220
- if (!draftFilterField) return;
221
- const opMeta = OPERATOR_OPTIONS.find((o) => o.value === draftFilterOp);
222
- const parsedValue =
223
- draftFilterOp === 'in' || draftFilterOp === 'not_in'
224
- ? draftFilterValue
225
- .split(',')
226
- .map((part) => part.trim())
227
- .filter(Boolean)
228
- : draftFilterValue;
229
- const nextItem: ReportFilterItem = {
230
- id: editingFilterIdx !== null ? filters[editingFilterIdx]?.id ?? `${Date.now()}` : `${Date.now()}`,
231
- field: draftFilterField,
232
- operator: draftFilterOp,
233
- ...(opMeta?.needsValue ? { value: parsedValue } : {}),
234
- ...(opMeta?.needsRange && draftFilterValueTo ? { valueTo: draftFilterValueTo } : {}),
235
- enabled: true,
236
- };
237
- const updated =
238
- editingFilterIdx !== null
239
- ? filters.map((item, i) => (i === editingFilterIdx ? nextItem : item))
240
- : [...filters, nextItem];
241
- setFilters(updated);
242
- setPage(1);
243
- setCursorHistory([]);
244
- setFilterPopoverOpen(false);
245
- setEditingFilterIdx(null);
246
- setDraftFilterValue('');
247
- setDraftFilterValueTo('');
248
- triggerQuery({ filters: updated, page: 1 });
249
- };
250
-
251
- const handleRemoveFilter = (idx: number) => {
252
- const updated = filters.filter((_, i) => i !== idx);
253
- setFilters(updated);
254
- setPage(1);
255
- setCursorHistory([]);
256
- triggerQuery({ filters: updated, page: 1 });
257
- };
258
-
259
- const handleReset = () => {
260
- const baseQuery = spec.query ?? '';
261
- const baseFilters = spec.filters ?? [];
262
- const baseSort = spec.sort ?? [];
263
- const basePreset = spec.timeRange?.preset ?? 'last_24h';
264
- setQueryText(baseQuery);
265
- setFilters(baseFilters);
266
- setSort(baseSort);
267
- setTimePreset(basePreset);
268
- setPage(1);
269
- setCursorHistory([]);
270
- onExecute({
271
- query: baseQuery,
272
- filters: baseFilters,
273
- sort: baseSort,
274
- timeRange: spec.timeRange ?? { preset: basePreset },
275
- page: 1,
276
- pageSize: spec.pageSize ?? 20,
277
- });
278
- };
279
-
280
- const handleBucketDrilldown = (bucketKey: string) => {
281
- if (!showToolbar || spec.allowInteractiveControls === false) return;
282
- const bucketField = spec.chart?.bucketField || dataView?.timeField;
283
- if (!bucketField || spec.chart?.bucketType === 'date_histogram') return;
284
- const updated: ReportFilterItem[] = [
285
- ...filters,
286
- { id: `${Date.now()}`, field: bucketField, operator: 'eq', value: bucketKey, enabled: true },
287
- ];
288
- setFilters(updated);
289
- triggerQuery({ filters: updated, page: 1 });
290
- };
291
-
292
- const activeColumns = useMemo(() => result?.columns ?? spec.columns ?? [], [result?.columns, spec.columns]);
293
-
294
- const tableColumns: TableColumnsType<ReportRowHit> = useMemo(
295
- () =>
296
- activeColumns.map((colName) => {
297
- const activeSort = sort.find((s) => s.field === colName || s.field === `${colName}.keyword`);
298
- const canSortCol = aggregatableFields.some((f) => f.name === colName || f.name === `${colName}.keyword`);
299
- return {
300
- title: colName,
301
- key: colName,
302
- ellipsis: true,
303
- ...(canSortCol
304
- ? {
305
- sorter: true,
306
- sortOrder: activeSort ? (activeSort.order === 'asc' ? 'ascend' : 'descend') : null,
307
- }
308
- : {}),
309
- render: (_: unknown, record: ReportRowHit) => {
310
- const hl = record.highlights?.[colName]?.[0];
311
- if (hl) {
312
- return <HighlightText text={hl} />;
313
- }
314
- const rawVal =
315
- colName === '_id'
316
- ? record._id
317
- : colName === '_index'
318
- ? record._index
319
- : getNestedValue(record.source, colName);
320
- return <span>{formatCellValue(rawVal)}</span>;
321
- },
322
- };
323
- }),
324
- [activeColumns, aggregatableFields, sort],
325
- );
326
-
327
- const canInteract = showToolbar && spec.allowInteractiveControls !== false;
328
- const currentOpMeta = OPERATOR_OPTIONS.find((o) => o.value === draftFilterOp);
329
-
330
- return (
331
- <div>
332
- {/* Polite status region announces updated hit counts for screen readers without putting aria-live on <table> */}
333
- <div role="status" aria-live="polite" style={VISUALLY_HIDDEN_STYLE}>
334
- {!loading && result ? `${title}: ${result.total} ${t('Hits')}` : ''}
335
- </div>
336
-
337
- {canInteract && (
338
- <div style={{ marginBottom: 12 }}>
339
- <Space wrap style={{ width: '100%', justifyContent: 'space-between' }}>
340
- <Space wrap>
341
- <Input
342
- allowClear
343
- aria-label={t('KQL / Search Query')}
344
- placeholder={t('Search KQL, e.g. status >= 500 AND service: "api"')}
345
- prefix={<SearchOutlined aria-hidden="true" />}
346
- value={queryText}
347
- style={{ minWidth: compact ? 220 : 320 }}
348
- onChange={(e) => {
349
- const nextVal = e.target.value;
350
- setQueryText(nextVal);
351
- if (nextVal === '' && e.type === 'click') {
352
- setPage(1);
353
- setCursorHistory([]);
354
- triggerQuery({ query: '', page: 1 });
355
- }
356
- }}
357
- onPressEnter={() => {
358
- setPage(1);
359
- setCursorHistory([]);
360
- triggerQuery({ query: queryText, page: 1 });
361
- }}
362
- />
363
- {dataView?.timeField && (
364
- <Select
365
- aria-label={t('Time Field')}
366
- value={timePreset}
367
- options={timeRangeOptions}
368
- style={{ minWidth: 150 }}
369
- onChange={(nextPreset) => {
370
- setTimePreset(nextPreset);
371
- setPage(1);
372
- setCursorHistory([]);
373
- triggerQuery({ timeRange: { preset: nextPreset }, page: 1 });
374
- }}
375
- />
376
- )}
377
- <Popover
378
- trigger="click"
379
- title={editingFilterIdx !== null ? t('Edit Filter') : t('Add Filter')}
380
- open={filterPopoverOpen}
381
- onOpenChange={(open) => {
382
- setFilterPopoverOpen(open);
383
- if (!open) {
384
- setEditingFilterIdx(null);
385
- }
386
- }}
387
- content={
388
- <div style={{ width: 280 }}>
389
- <Form layout="vertical" size="small">
390
- <Form.Item label={t('Field')} style={{ marginBottom: 8 }}>
391
- <Select
392
- showSearch
393
- value={draftFilterField || undefined}
394
- placeholder={t('Field')}
395
- options={fields.map((f) => ({ label: `${f.name} (${f.type})`, value: f.name }))}
396
- onChange={(val) => setDraftFilterField(val)}
397
- />
398
- </Form.Item>
399
- <Form.Item label={t('Operator')} style={{ marginBottom: 8 }}>
400
- <Select
401
- value={draftFilterOp}
402
- options={OPERATOR_OPTIONS.map((o) => ({ label: o.label, value: o.value }))}
403
- onChange={(val) => setDraftFilterOp(val)}
404
- />
405
- </Form.Item>
406
- {currentOpMeta?.needsValue && (
407
- <Form.Item label={t('Value')} style={{ marginBottom: 8 }}>
408
- <Input value={draftFilterValue} onChange={(e) => setDraftFilterValue(e.target.value)} />
409
- </Form.Item>
410
- )}
411
- {currentOpMeta?.needsRange && (
412
- <Form.Item label={t('To Value')} style={{ marginBottom: 8 }}>
413
- <Input value={draftFilterValueTo} onChange={(e) => setDraftFilterValueTo(e.target.value)} />
414
- </Form.Item>
415
- )}
416
- <Space style={{ justifyContent: 'flex-end', width: '100%' }}>
417
- <Button
418
- size="small"
419
- onClick={() => {
420
- setFilterPopoverOpen(false);
421
- setEditingFilterIdx(null);
422
- }}
423
- >
424
- {t('Cancel')}
425
- </Button>
426
- <Button size="small" type="primary" onClick={handleSaveFilterPill}>
427
- {t('Apply')}
428
- </Button>
429
- </Space>
430
- </Form>
431
- </div>
432
- }
433
- >
434
- <Button icon={<FilterOutlined />} onClick={openAddFilterPopover}>
435
- {t('Add Filter')}
436
- </Button>
437
- </Popover>
438
-
439
- {spec.visualization === 'table' && aggregatableFields.length > 0 && (
440
- <Select
441
- allowClear
442
- aria-label={t('Sort')}
443
- placeholder={t('Sort')}
444
- style={{ minWidth: 170 }}
445
- value={sort[0] ? `${sort[0].field}:${sort[0].order}` : undefined}
446
- options={aggregatableFields.slice(0, 40).flatMap((f) => [
447
- { label: `${f.name} ↓`, value: `${f.name}:desc` },
448
- { label: `${f.name} ↑`, value: `${f.name}:asc` },
449
- ])}
450
- onChange={(encoded) => {
451
- if (!encoded) {
452
- setSort([]);
453
- setPage(1);
454
- setCursorHistory([]);
455
- triggerQuery({ sort: [], page: 1 });
456
- return;
457
- }
458
- const lastColon = encoded.lastIndexOf(':');
459
- const nextSort: ReportSortItem[] = [
460
- {
461
- field: encoded.slice(0, lastColon),
462
- order: encoded.slice(lastColon + 1) === 'asc' ? 'asc' : 'desc',
463
- },
464
- ];
465
- setSort(nextSort);
466
- setPage(1);
467
- setCursorHistory([]);
468
- triggerQuery({ sort: nextSort, page: 1 });
469
- }}
470
- />
471
- )}
472
- </Space>
473
-
474
- <Space>
475
- <Button
476
- type="primary"
477
- icon={<SearchOutlined />}
478
- onClick={() => {
479
- setPage(1);
480
- setCursorHistory([]);
481
- triggerQuery({ page: 1 });
482
- }}
483
- >
484
- {t('Search')}
485
- </Button>
486
- <Button icon={<ReloadOutlined />} aria-label={t('Refresh')} onClick={() => triggerQuery({ page })} />
487
- <Button icon={<RollbackOutlined />} onClick={handleReset}>
488
- {t('Reset')}
489
- </Button>
490
- {result?.compiledDsl && (
491
- <Button icon={<CodeOutlined />} onClick={() => setInspectDslOpen(true)}>
492
- {t('Inspect DSL')}
493
- </Button>
494
- )}
495
- </Space>
496
- </Space>
497
-
498
- {filters.length > 0 && (
499
- <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
500
- {filters.map((flt, idx) => (
501
- <Tag
502
- key={flt.id || `${flt.field}-${idx}`}
503
- closable
504
- color="processing"
505
- onClose={(e) => {
506
- e.preventDefault();
507
- e.stopPropagation();
508
- handleRemoveFilter(idx);
509
- }}
510
- >
511
- <span
512
- role="button"
513
- tabIndex={0}
514
- aria-label={`${t('Edit Filter')}: ${flt.field}`}
515
- style={{ cursor: 'pointer' }}
516
- onClick={() => openEditFilterPopover(idx)}
517
- onKeyDown={(e) => {
518
- if (e.key === 'Enter' || e.key === ' ') {
519
- e.preventDefault();
520
- openEditFilterPopover(idx);
521
- }
522
- }}
523
- >
524
- {flt.field} {flt.operator}
525
- {flt.value !== undefined
526
- ? ` ${Array.isArray(flt.value) ? flt.value.join(', ') : String(flt.value)}`
527
- : ''}
528
- {flt.valueTo !== undefined ? ` .. ${String(flt.valueTo)}` : ''}
529
- </span>
530
- </Tag>
531
- ))}
532
- </div>
533
- )}
534
- </div>
535
- )}
536
-
537
- {error && <Alert type="error" showIcon message={error} style={{ marginBottom: 12 }} />}
538
-
539
- <Spin spinning={loading}>
540
- {!result ? (
541
- <Empty description={t('No matching documents')} />
542
- ) : spec.visualization === 'table' ? (
543
- <div>
544
- {result.histogram.length > 0 && spec.chart?.showHistogram !== false && (
545
- <ReportHistogramStrip buckets={result.histogram} />
546
- )}
547
- <div
548
- style={{
549
- display: 'flex',
550
- justifyContent: 'space-between',
551
- alignItems: 'center',
552
- marginBottom: 8,
553
- fontSize: 12,
554
- }}
555
- >
556
- <Text id={regionLabelId} strong>
557
- {title} · {t('Hits')}: {result.total.toLocaleString()}
558
- {result.totalRelation === 'gte' ? '+' : ''} ({result.tookMs} ms)
559
- </Text>
560
- {result.nextSearchAfter && cursorHistory.length > 0 && (
561
- <Button
562
- size="small"
563
- onClick={() => {
564
- setPage(1);
565
- setCursorHistory([]);
566
- triggerQuery({ page: 1 });
567
- }}
568
- >
569
- {t('First page')}
570
- </Button>
571
- )}
572
- </div>
573
-
574
- <div
575
- role="region"
576
- aria-labelledby={regionLabelId}
577
- tabIndex={0}
578
- style={{ overflowX: 'auto', maxInlineSize: '100%', containerType: 'inline-size' }}
579
- >
580
- <Table<ReportRowHit>
581
- size={compact ? 'small' : 'middle'}
582
- rowKey={(record) => `${record._index}:${record._id}`}
583
- columns={tableColumns}
584
- dataSource={result.rows}
585
- onRow={(record) => ({
586
- onClick: () => setSelectedDoc(record),
587
- style: { cursor: 'pointer' },
588
- })}
589
- onChange={(pagination, _tableFilters, sorter) => {
590
- const singleSorter = Array.isArray(sorter) ? sorter[0] : sorter;
591
- if (singleSorter && singleSorter.columnKey && singleSorter.order) {
592
- const nextSort: ReportSortItem[] = [
593
- {
594
- field: String(singleSorter.columnKey),
595
- order: singleSorter.order === 'ascend' ? 'asc' : 'desc',
596
- },
597
- ];
598
- setSort(nextSort);
599
- setPage(1);
600
- setCursorHistory([]);
601
- triggerQuery({ sort: nextSort, page: 1 });
602
- return;
603
- }
604
-
605
- const nextPage = pagination.current ?? 1;
606
- const pageSize = spec.pageSize ?? 20;
607
- if (nextPage * pageSize > 10000 && result.nextSearchAfter) {
608
- const updatedHistory = [...cursorHistory, result.nextSearchAfter];
609
- setCursorHistory(updatedHistory);
610
- setPage(nextPage);
611
- triggerQuery({ page: nextPage, searchAfter: result.nextSearchAfter });
612
- return;
613
- }
614
- setPage(nextPage);
615
- triggerQuery({ page: nextPage });
616
- }}
617
- pagination={{
618
- current: page,
619
- pageSize: spec.pageSize ?? 20,
620
- total: Math.min(result.total, 10000),
621
- showSizeChanger: false,
622
- }}
623
- />
624
- </div>
625
-
626
- {result.total >= 10000 && result.nextSearchAfter && (
627
- <div style={{ marginTop: 8, textAlign: 'right' }}>
628
- <Button
629
- size="small"
630
- onClick={() => {
631
- if (!result.nextSearchAfter) return;
632
- const updatedHistory = [...cursorHistory, result.nextSearchAfter];
633
- setCursorHistory(updatedHistory);
634
- setPage((p) => p + 1);
635
- triggerQuery({ searchAfter: result.nextSearchAfter });
636
- }}
637
- >
638
- {t('Next cursor page')}
639
- </Button>
640
- </div>
641
- )}
642
- </div>
643
- ) : (
644
- <ElasticBasicChart
645
- title={title}
646
- visualization={spec.visualization}
647
- series={result.series}
648
- metricValue={result.metricValue}
649
- metricLabel={result.metricLabel}
650
- totalHits={result.total}
651
- onSelectBucket={handleBucketDrilldown}
652
- />
653
- )}
654
- </Spin>
655
-
656
- <Modal
657
- title={t('Elasticsearch Query DSL')}
658
- open={inspectDslOpen}
659
- footer={null}
660
- onCancel={() => setInspectDslOpen(false)}
661
- width={680}
662
- >
663
- <pre style={{ maxHeight: 420, overflow: 'auto', fontSize: 12 }}>
664
- {JSON.stringify(result?.compiledDsl ?? {}, null, 2)}
665
- </pre>
666
- </Modal>
667
-
668
- <Drawer
669
- title={t('Document Details')}
670
- open={Boolean(selectedDoc)}
671
- onClose={() => setSelectedDoc(null)}
672
- width={640}
673
- >
674
- {selectedDoc && (
675
- <Tabs
676
- items={[
677
- {
678
- key: 'table',
679
- label: t('Table View'),
680
- children: (
681
- <Descriptions bordered column={1} size="small">
682
- <Descriptions.Item label="_index">{selectedDoc._index}</Descriptions.Item>
683
- <Descriptions.Item label="_id">{selectedDoc._id}</Descriptions.Item>
684
- {Object.entries(selectedDoc.source).map(([k, v]) => (
685
- <Descriptions.Item key={k} label={k}>
686
- {formatCellValue(v)}
687
- </Descriptions.Item>
688
- ))}
689
- </Descriptions>
690
- ),
691
- },
692
- {
693
- key: 'json',
694
- label: t('JSON View'),
695
- children: (
696
- <pre style={{ maxHeight: 520, overflow: 'auto', fontSize: 12 }}>
697
- {JSON.stringify(selectedDoc, null, 2)}
698
- </pre>
699
- ),
700
- },
701
- ]}
702
- />
703
- )}
704
- </Drawer>
705
- </div>
706
- );
707
- };
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
+ };