plugin-elastic-report 0.1.1 → 0.7.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 (60) hide show
  1. package/ai/skills/elastic-report/SKILLS.md +5 -3
  2. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  3. package/dist/client/index.js +1 -1
  4. package/dist/client-v2/851.142c93fc6d666b28.js +10 -0
  5. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  6. package/dist/client-v2/877.f4095a3dbcadf98f.js +10 -0
  7. package/dist/client-v2/index.js +1 -1
  8. package/dist/externalVersion.js +3 -2
  9. package/dist/locale/en-US.json +100 -1
  10. package/dist/locale/vi-VN.json +100 -1
  11. package/dist/locale/zh-CN.json +100 -1
  12. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  13. package/dist/server/acl-guard.js +97 -25
  14. package/dist/server/collections/es-report-data-views.js +6 -0
  15. package/dist/server/collections/es-reports.js +6 -0
  16. package/dist/server/mcp/ElasticReportToolCatalog.js +232 -10
  17. package/dist/server/plugin.js +153 -19
  18. package/dist/server/services/ElasticReportService.js +125 -11
  19. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  20. package/dist/server/services/ReportExportService.js +243 -0
  21. package/dist/server/services/ReportQueryCompiler.js +532 -91
  22. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  23. package/dist/shared/constants.js +17 -2
  24. package/package.json +3 -2
  25. package/src/client/index.tsx +16 -1
  26. package/src/client/workflow-instructions.tsx +44 -0
  27. package/src/client-v2/__tests__/elastic-report.test.tsx +519 -39
  28. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  29. package/src/client-v2/api.ts +96 -0
  30. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  31. package/src/client-v2/components/ElasticBasicCharts.tsx +345 -92
  32. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  33. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  34. package/src/client-v2/components/ElasticReportBlock.tsx +157 -11
  35. package/src/client-v2/components/ElasticReportRenderer.tsx +621 -71
  36. package/src/client-v2/components/ReportSelect.tsx +39 -26
  37. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  38. package/src/client-v2/models/ElasticReportBlockModel.tsx +36 -3
  39. package/src/client-v2/pages/ElasticReportManager.tsx +432 -26
  40. package/src/client-v2/plugin.tsx +20 -0
  41. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  42. package/src/client-v2/workflow/instructions.tsx +149 -0
  43. package/src/locale/en-US.json +100 -1
  44. package/src/locale/vi-VN.json +100 -1
  45. package/src/locale/zh-CN.json +100 -1
  46. package/src/server/__tests__/query-compiler.test.ts +390 -1
  47. package/src/server/__tests__/report-mcp-acl.integration.test.ts +271 -3
  48. package/src/server/acl-guard.ts +119 -28
  49. package/src/server/collections/es-report-data-views.ts +6 -0
  50. package/src/server/collections/es-reports.ts +6 -0
  51. package/src/server/mcp/ElasticReportToolCatalog.ts +255 -9
  52. package/src/server/plugin.ts +189 -21
  53. package/src/server/services/ElasticReportService.ts +165 -5
  54. package/src/server/services/ElasticsearchConnectionService.ts +375 -48
  55. package/src/server/services/ReportExportService.ts +282 -0
  56. package/src/server/services/ReportQueryCompiler.ts +629 -94
  57. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  58. package/src/shared/constants.ts +7 -0
  59. package/src/shared/types.ts +98 -1
  60. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
@@ -7,30 +7,52 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
- import { CodeOutlined, FilterOutlined, ReloadOutlined, RollbackOutlined, SearchOutlined } from '@ant-design/icons';
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';
11
26
  import {
12
27
  Alert,
13
28
  Button,
14
29
  Descriptions,
15
30
  Drawer,
31
+ Dropdown,
16
32
  Empty,
17
33
  Form,
18
34
  Input,
19
35
  Modal,
20
36
  Popover,
37
+ Progress,
21
38
  Select,
22
39
  Space,
23
40
  Spin,
24
41
  Table,
25
42
  Tabs,
26
43
  Tag,
44
+ Tooltip,
27
45
  Typography,
28
46
  } from 'antd';
29
47
  import type { TableColumnsType } from 'antd';
30
- import React, { useEffect, useId, useMemo, useRef, useState } from 'react';
48
+ import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
31
49
  import type {
50
+ AutoRefreshInterval,
32
51
  EsDataViewRecord,
33
52
  EsFieldCapability,
53
+ ExportFormat,
54
+ FieldFormatType,
55
+ FieldTopValuesResult,
34
56
  FilterOperator,
35
57
  ReportExecutionResult,
36
58
  ReportFilterItem,
@@ -38,10 +60,13 @@ import type {
38
60
  ReportRuntimeOverrides,
39
61
  ReportSortItem,
40
62
  ReportSpec,
63
+ ReportTimeRange,
64
+ ScalarFilterValue,
41
65
  TimeRangePreset,
42
66
  } from '../../shared/types';
43
67
  import { useT } from '../locale';
44
68
  import { ElasticBasicChart, ReportHistogramStrip } from './ElasticBasicCharts';
69
+ import { ElasticKqlInput } from './ElasticKqlInput';
45
70
  import { HighlightText } from './HighlightText';
46
71
 
47
72
  const { Text } = Typography;
@@ -92,6 +117,13 @@ function getNestedValue(source: Record<string, unknown>, path: string): unknown
92
117
  return current;
93
118
  }
94
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
+
95
127
  function formatCellValue(value: unknown): string {
96
128
  if (value === null || value === undefined) return '—';
97
129
  if (typeof value === 'string') return value;
@@ -103,6 +135,69 @@ function formatCellValue(value: unknown): string {
103
135
  }
104
136
  }
105
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
+
106
201
  export interface ElasticReportRendererProps {
107
202
  title: string;
108
203
  spec: ReportSpec;
@@ -114,6 +209,9 @@ export interface ElasticReportRendererProps {
114
209
  showToolbar?: boolean;
115
210
  compact?: boolean;
116
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>;
117
215
  }
118
216
 
119
217
  export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
@@ -127,6 +225,9 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
127
225
  showToolbar = true,
128
226
  compact = false,
129
227
  onExecute,
228
+ onCrossFilter,
229
+ onInspectTopValues,
230
+ onExport,
130
231
  }) => {
131
232
  const t = useT();
132
233
  const regionLabelId = useId();
@@ -134,7 +235,9 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
134
235
  const [queryText, setQueryText] = useState<string>(spec.query ?? '');
135
236
  const [filters, setFilters] = useState<ReportFilterItem[]>(spec.filters ?? []);
136
237
  const [sort, setSort] = useState<ReportSortItem[]>(spec.sort ?? []);
137
- const [timePreset, setTimePreset] = useState<TimeRangePreset>(spec.timeRange?.preset ?? 'last_24h');
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);
138
241
  const [page, setPage] = useState<number>(1);
139
242
  const [cursorHistory, setCursorHistory] = useState<Array<Array<string | number | boolean | null>>>([]);
140
243
 
@@ -145,6 +248,13 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
145
248
  const [draftFilterValue, setDraftFilterValue] = useState<string>('');
146
249
  const [draftFilterValueTo, setDraftFilterValueTo] = useState<string>('');
147
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
+
148
258
  const [inspectDslOpen, setInspectDslOpen] = useState(false);
149
259
  const [selectedDoc, setSelectedDoc] = useState<ReportRowHit | null>(null);
150
260
 
@@ -159,16 +269,56 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
159
269
  setQueryText(spec.query ?? '');
160
270
  setFilters(spec.filters ?? []);
161
271
  setSort(spec.sort ?? []);
162
- setTimePreset(spec.timeRange?.preset ?? 'last_24h');
272
+ setTimeRange(spec.timeRange ?? { preset: 'last_24h' });
273
+ setCustomColumns(null);
163
274
  setPage(1);
164
275
  setCursorHistory([]);
165
276
  }, [serializedSpec, spec]);
166
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
+
167
315
  const aggregatableFields = useMemo(
168
316
  () => fields.filter((f) => f.aggregatable || Boolean(f.keywordSubfield)),
169
317
  [fields],
170
318
  );
171
319
 
320
+ const selectableColumnFields = useMemo(() => fields.filter((f) => !f.isSubfield), [fields]);
321
+
172
322
  const timeRangeOptions: Array<{ label: string; value: TimeRangePreset }> = useMemo(
173
323
  () => [
174
324
  { label: t('Last 15 minutes'), value: 'last_15m' },
@@ -178,22 +328,21 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
178
328
  { label: t('Last 30 days'), value: 'last_30d' },
179
329
  { label: t('Last 90 days'), value: 'last_90d' },
180
330
  { label: t('All time'), value: 'all' },
331
+ { label: t('Custom range'), value: 'custom' },
181
332
  ],
182
333
  [t],
183
334
  );
184
335
 
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
- };
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
+ );
197
346
 
198
347
  const openAddFilterPopover = () => {
199
348
  setEditingFilterIdx(null);
@@ -248,6 +397,30 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
248
397
  triggerQuery({ filters: updated, page: 1 });
249
398
  };
250
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
+
251
424
  const handleRemoveFilter = (idx: number) => {
252
425
  const updated = filters.filter((_, i) => i !== idx);
253
426
  setFilters(updated);
@@ -260,18 +433,19 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
260
433
  const baseQuery = spec.query ?? '';
261
434
  const baseFilters = spec.filters ?? [];
262
435
  const baseSort = spec.sort ?? [];
263
- const basePreset = spec.timeRange?.preset ?? 'last_24h';
436
+ const baseTimeRange: ReportTimeRange = spec.timeRange ?? { preset: 'last_24h' };
264
437
  setQueryText(baseQuery);
265
438
  setFilters(baseFilters);
266
439
  setSort(baseSort);
267
- setTimePreset(basePreset);
440
+ setTimeRange(baseTimeRange);
441
+ setCustomColumns(null);
268
442
  setPage(1);
269
443
  setCursorHistory([]);
270
444
  onExecute({
271
445
  query: baseQuery,
272
446
  filters: baseFilters,
273
447
  sort: baseSort,
274
- timeRange: spec.timeRange ?? { preset: basePreset },
448
+ timeRange: baseTimeRange,
275
449
  page: 1,
276
450
  pageSize: spec.pageSize ?? 20,
277
451
  });
@@ -281,24 +455,65 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
281
455
  if (!showToolbar || spec.allowInteractiveControls === false) return;
282
456
  const bucketField = spec.chart?.bucketField || dataView?.timeField;
283
457
  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
- ];
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];
288
470
  setFilters(updated);
289
471
  triggerQuery({ filters: updated, page: 1 });
290
472
  };
291
473
 
292
- const activeColumns = useMemo(() => result?.columns ?? spec.columns ?? [], [result?.columns, spec.columns]);
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);
293
504
 
294
505
  const tableColumns: TableColumnsType<ReportRowHit> = useMemo(
295
506
  () =>
296
507
  activeColumns.map((colName) => {
297
508
  const activeSort = sort.find((s) => s.field === colName || s.field === `${colName}.keyword`);
298
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;
299
513
  return {
300
514
  title: colName,
301
515
  key: colName,
516
+ width: colWidth,
302
517
  ellipsis: true,
303
518
  ...(canSortCol
304
519
  ? {
@@ -308,71 +523,161 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
308
523
  : {}),
309
524
  render: (_: unknown, record: ReportRowHit) => {
310
525
  const hl = record.highlights?.[colName]?.[0];
311
- if (hl) {
312
- return <HighlightText text={hl} />;
313
- }
314
526
  const rawVal =
315
527
  colName === '_id'
316
528
  ? record._id
317
529
  : colName === '_index'
318
530
  ? record._index
319
531
  : getNestedValue(record.source, colName);
320
- return <span>{formatCellValue(rawVal)}</span>;
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
+ );
321
586
  },
322
587
  };
323
588
  }),
324
- [activeColumns, aggregatableFields, sort],
589
+ [activeColumns, aggregatableFields, applyQuickFieldFilter, canInteract, sort, spec.fieldFormats, t],
325
590
  );
326
591
 
327
- const canInteract = showToolbar && spec.allowInteractiveControls !== false;
328
- const currentOpMeta = OPERATOR_OPTIONS.find((o) => o.value === draftFilterOp);
329
-
330
592
  return (
331
- <div>
593
+ <div style={{ width: '100%', maxWidth: '100%', minWidth: 0 }}>
332
594
  {/* Polite status region announces updated hit counts for screen readers without putting aria-live on <table> */}
333
595
  <div role="status" aria-live="polite" style={VISUALLY_HIDDEN_STYLE}>
334
596
  {!loading && result ? `${title}: ${result.total} ${t('Hits')}` : ''}
335
597
  </div>
336
598
 
337
599
  {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')}
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')}
344
605
  placeholder={t('Search KQL, e.g. status >= 500 AND service: "api"')}
345
- prefix={<SearchOutlined aria-hidden="true" />}
346
606
  value={queryText}
347
- style={{ minWidth: compact ? 220 : 320 }}
348
- onChange={(e) => {
349
- const nextVal = e.target.value;
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) => {
350
616
  setQueryText(nextVal);
351
- if (nextVal === '' && e.type === 'click') {
352
- setPage(1);
353
- setCursorHistory([]);
354
- triggerQuery({ query: '', page: 1 });
355
- }
356
617
  }}
357
- onPressEnter={() => {
618
+ onClear={() => {
619
+ setQueryText('');
358
620
  setPage(1);
359
621
  setCursorHistory([]);
360
- triggerQuery({ query: queryText, page: 1 });
622
+ triggerQuery({ query: '', page: 1 });
623
+ }}
624
+ onSubmit={(submittedVal) => {
625
+ setPage(1);
626
+ setCursorHistory([]);
627
+ triggerQuery({ query: submittedVal, page: 1 });
361
628
  }}
362
629
  />
363
630
  {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
- />
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
+ </>
376
681
  )}
377
682
  <Popover
378
683
  trigger="click"
@@ -441,7 +746,7 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
441
746
  allowClear
442
747
  aria-label={t('Sort')}
443
748
  placeholder={t('Sort')}
444
- style={{ minWidth: 170 }}
749
+ style={{ minWidth: 165 }}
445
750
  value={sort[0] ? `${sort[0].field}:${sort[0].order}` : undefined}
446
751
  options={aggregatableFields.slice(0, 40).flatMap((f) => [
447
752
  { label: `${f.name} ↓`, value: `${f.name}:desc` },
@@ -469,9 +774,89 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
469
774
  }}
470
775
  />
471
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
+ )}
472
849
  </Space>
473
850
 
474
- <Space>
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
+ />
475
860
  <Button
476
861
  type="primary"
477
862
  icon={<SearchOutlined />}
@@ -487,6 +872,42 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
487
872
  <Button icon={<RollbackOutlined />} onClick={handleReset}>
488
873
  {t('Reset')}
489
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
+ )}
490
911
  {result?.compiledDsl && (
491
912
  <Button icon={<CodeOutlined />} onClick={() => setInspectDslOpen(true)}>
492
913
  {t('Inspect DSL')}
@@ -495,8 +916,17 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
495
916
  </Space>
496
917
  </Space>
497
918
 
498
- {filters.length > 0 && (
919
+ {((spec.lockedFilters?.length ?? 0) > 0 || filters.length > 0) && (
499
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
+ ))}
500
930
  {filters.map((flt, idx) => (
501
931
  <Tag
502
932
  key={flt.id || `${flt.field}-${idx}`}
@@ -534,8 +964,39 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
534
964
  </div>
535
965
  )}
536
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
+
537
979
  {error && <Alert type="error" showIcon message={error} style={{ marginBottom: 12 }} />}
538
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
+
539
1000
  <Spin spinning={loading}>
540
1001
  {!result ? (
541
1002
  <Empty description={t('No matching documents')} />
@@ -575,10 +1036,11 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
575
1036
  role="region"
576
1037
  aria-labelledby={regionLabelId}
577
1038
  tabIndex={0}
578
- style={{ overflowX: 'auto', maxInlineSize: '100%', containerType: 'inline-size' }}
1039
+ style={{ width: '100%', maxWidth: '100%', minWidth: 0, overflowX: 'auto' }}
579
1040
  >
580
1041
  <Table<ReportRowHit>
581
1042
  size={compact ? 'small' : 'middle'}
1043
+ scroll={{ x: 'max-content' }}
582
1044
  rowKey={(record) => `${record._index}:${record._id}`}
583
1045
  columns={tableColumns}
584
1046
  dataSource={result.rows}
@@ -608,7 +1070,7 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
608
1070
  const updatedHistory = [...cursorHistory, result.nextSearchAfter];
609
1071
  setCursorHistory(updatedHistory);
610
1072
  setPage(nextPage);
611
- triggerQuery({ page: nextPage, searchAfter: result.nextSearchAfter });
1073
+ triggerQuery({ page: nextPage, searchAfter: result.nextSearchAfter, pitId: result.pitId });
612
1074
  return;
613
1075
  }
614
1076
  setPage(nextPage);
@@ -632,7 +1094,7 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
632
1094
  const updatedHistory = [...cursorHistory, result.nextSearchAfter];
633
1095
  setCursorHistory(updatedHistory);
634
1096
  setPage((p) => p + 1);
635
- triggerQuery({ searchAfter: result.nextSearchAfter });
1097
+ triggerQuery({ searchAfter: result.nextSearchAfter, pitId: result.pitId });
636
1098
  }}
637
1099
  >
638
1100
  {t('Next cursor page')}
@@ -645,9 +1107,15 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
645
1107
  title={title}
646
1108
  visualization={spec.visualization}
647
1109
  series={result.series}
1110
+ seriesKeys={result.seriesKeys}
1111
+ stackMode={spec.chart?.stackMode}
648
1112
  metricValue={result.metricValue}
1113
+ previousMetricValue={result.previousMetricValue}
1114
+ deltaPercent={result.deltaPercent}
649
1115
  metricLabel={result.metricLabel}
1116
+ metricType={spec.chart?.metricType}
650
1117
  totalHits={result.total}
1118
+ totalRelation={result.totalRelation}
651
1119
  onSelectBucket={handleBucketDrilldown}
652
1120
  />
653
1121
  )}
@@ -658,18 +1126,78 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
658
1126
  open={inspectDslOpen}
659
1127
  footer={null}
660
1128
  onCancel={() => setInspectDslOpen(false)}
661
- width={680}
1129
+ width="min(680px, calc(100vw - 32px))"
662
1130
  >
663
1131
  <pre style={{ maxHeight: 420, overflow: 'auto', fontSize: 12 }}>
664
1132
  {JSON.stringify(result?.compiledDsl ?? {}, null, 2)}
665
1133
  </pre>
666
1134
  </Modal>
667
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
+
668
1196
  <Drawer
669
1197
  title={t('Document Details')}
670
1198
  open={Boolean(selectedDoc)}
671
1199
  onClose={() => setSelectedDoc(null)}
672
- width={640}
1200
+ width="min(640px, 94vw)"
673
1201
  >
674
1202
  {selectedDoc && (
675
1203
  <Tabs
@@ -683,7 +1211,29 @@ export const ElasticReportRenderer: React.FC<ElasticReportRendererProps> = ({
683
1211
  <Descriptions.Item label="_id">{selectedDoc._id}</Descriptions.Item>
684
1212
  {Object.entries(selectedDoc.source).map(([k, v]) => (
685
1213
  <Descriptions.Item key={k} label={k}>
686
- {formatCellValue(v)}
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>
687
1237
  </Descriptions.Item>
688
1238
  ))}
689
1239
  </Descriptions>