plugin-elastic-report 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/client-v2.d.ts +2 -2
  2. package/client-v2.js +1 -1
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/{ai → dist/ai}/skills/elastic-report/SKILLS.md +52 -34
  6. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  7. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +2 -1
  10. package/dist/locale/en-US.json +213 -198
  11. package/dist/locale/vi-VN.json +213 -198
  12. package/dist/locale/zh-CN.json +213 -198
  13. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  14. package/dist/server/mcp/ElasticReportToolCatalog.js +6 -4
  15. package/dist/server/plugin.js +4 -4
  16. package/dist/server/report-block-tools.js +340 -0
  17. package/dist/server/services/ElasticReportService.js +12 -6
  18. package/dist/shared/constants.js +9 -0
  19. package/package.json +2 -3
  20. package/server.d.ts +2 -2
  21. package/server.js +1 -1
  22. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  23. package/src/client/index.tsx +34 -34
  24. package/src/client/workflow-instructions.tsx +44 -44
  25. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -791
  26. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -178
  27. package/src/client-v2/api.ts +320 -320
  28. package/src/client-v2/bus/DashboardFilterBus.ts +212 -212
  29. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -652
  30. package/src/client-v2/components/ElasticFilterBar.tsx +372 -372
  31. package/src/client-v2/components/ElasticKqlInput.tsx +421 -421
  32. package/src/client-v2/components/ElasticReportBlock.tsx +306 -306
  33. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -1257
  34. package/src/client-v2/components/HighlightText.tsx +50 -50
  35. package/src/client-v2/components/ReportSelect.tsx +85 -85
  36. package/src/client-v2/index.tsx +14 -14
  37. package/src/client-v2/locale.ts +23 -23
  38. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -115
  39. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -118
  40. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1453
  41. package/src/client-v2/plugin.tsx +107 -72
  42. package/src/client-v2/report-destination.tsx +126 -0
  43. package/src/client-v2/utils/kqlAutocomplete.ts +861 -861
  44. package/src/client-v2/workflow/instructions.tsx +149 -149
  45. package/src/index.ts +11 -11
  46. package/src/locale/en-US.json +213 -198
  47. package/src/locale/vi-VN.json +213 -198
  48. package/src/locale/zh-CN.json +213 -198
  49. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  50. package/src/server/__tests__/query-compiler.test.ts +620 -620
  51. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -645
  52. package/src/server/acl-guard.ts +194 -194
  53. package/src/server/collections/es-report-data-views.ts +64 -64
  54. package/src/server/collections/es-reports.ts +80 -80
  55. package/src/server/index.ts +15 -15
  56. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  57. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -663
  58. package/src/server/plugin.ts +599 -599
  59. package/src/server/report-block-tools.ts +400 -0
  60. package/src/server/services/ElasticReportService.ts +494 -486
  61. package/src/server/services/ElasticsearchConnectionService.ts +728 -728
  62. package/src/server/services/ReportExportService.ts +282 -282
  63. package/src/server/services/ReportQueryCompiler.ts +1552 -1552
  64. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -124
  65. package/src/shared/constants.ts +39 -36
  66. package/src/shared/types.ts +272 -272
  67. package/dist/client-v2/851.142c93fc6d666b28.js +0 -10
  68. package/dist/client-v2/877.f4095a3dbcadf98f.js +0 -10
  69. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  70. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,652 +1,652 @@
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 { Button, Card, Empty, Space, Statistic, Table, Tag, Tooltip, Typography, theme } from 'antd';
11
- import type { TableColumnsType } from 'antd';
12
- import React, { useId, useMemo, useState } from 'react';
13
- import type {
14
- ChartStackMode,
15
- MetricAggType,
16
- ReportHistogramBucket,
17
- ReportSeriesPoint,
18
- ReportVisualizationType,
19
- } from '../../shared/types';
20
- import { useT } from '../locale';
21
-
22
- const { Text } = Typography;
23
-
24
- const PALETTE = ['#1677ff', '#13c2c2', '#52c41a', '#fa8c16', '#722ed1', '#eb2f96', '#2f54eb', '#faad14'];
25
-
26
- function formatCompactNumber(val: number): string {
27
- if (!Number.isFinite(val)) return '0';
28
- if (Math.abs(val) >= 1_000_000) return `${(val / 1_000_000).toFixed(2)}M`;
29
- if (Math.abs(val) >= 1_000) return `${(val / 1_000).toFixed(1)}k`;
30
- return Number.isInteger(val) ? String(val) : val.toFixed(2);
31
- }
32
-
33
- function truncateLabel(text: string, maxLen = 18): string {
34
- if (text.length <= maxLen) return text;
35
- return `${text.slice(0, maxLen - 1)}…`;
36
- }
37
-
38
- export interface ReportHistogramStripProps {
39
- buckets: ReportHistogramBucket[];
40
- }
41
-
42
- export const ReportHistogramStrip: React.FC<ReportHistogramStripProps> = ({ buckets }) => {
43
- const t = useT();
44
- const { token } = theme.useToken();
45
- const titleId = useId();
46
-
47
- if (!buckets.length) return null;
48
- const maxCount = Math.max(1, ...buckets.map((b) => b.count));
49
- const width = 720;
50
- const height = 68;
51
- const barGap = 2;
52
- const barWidth = Math.max(4, (width - barGap * buckets.length) / buckets.length);
53
-
54
- return (
55
- <figure style={{ margin: '0 0 12px 0' }}>
56
- <svg
57
- role="img"
58
- aria-labelledby={titleId}
59
- viewBox={`0 0 ${width} ${height}`}
60
- style={{ width: '100%', height: 68, display: 'block' }}
61
- >
62
- <title id={titleId}>{t('Date Histogram')}</title>
63
- {buckets.map((bucket, index) => {
64
- const barHeight = Math.max(bucket.count > 0 ? 3 : 1, Math.round((bucket.count / maxCount) * (height - 14)));
65
- const x = index * (barWidth + barGap);
66
- const y = height - barHeight - 2;
67
- return (
68
- <Tooltip key={`${bucket.key}-${index}`} title={`${bucket.key}: ${bucket.count}`}>
69
- <rect
70
- x={x}
71
- y={y}
72
- width={barWidth}
73
- height={barHeight}
74
- rx={2}
75
- fill={bucket.count > 0 ? token.colorPrimary : token.colorFillSecondary}
76
- opacity={0.85}
77
- />
78
- </Tooltip>
79
- );
80
- })}
81
- </svg>
82
- <figcaption
83
- style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: token.colorTextSecondary }}
84
- >
85
- <span>{buckets[0]?.key}</span>
86
- <span>{buckets[buckets.length - 1]?.key}</span>
87
- </figcaption>
88
- </figure>
89
- );
90
- };
91
-
92
- export interface ElasticBasicChartProps {
93
- title: string;
94
- visualization: Exclude<ReportVisualizationType, 'table'>;
95
- series: ReportSeriesPoint[];
96
- seriesKeys?: string[];
97
- stackMode?: ChartStackMode;
98
- metricValue: number | null;
99
- previousMetricValue?: number | null;
100
- deltaPercent?: number | null;
101
- metricLabel: string;
102
- metricType?: MetricAggType;
103
- totalHits: number;
104
- totalRelation?: 'eq' | 'gte';
105
- onSelectBucket?: (bucketKey: string) => void;
106
- }
107
-
108
- export const ElasticBasicChart: React.FC<ElasticBasicChartProps> = ({
109
- title,
110
- visualization,
111
- series,
112
- seriesKeys,
113
- stackMode = 'none',
114
- metricValue,
115
- previousMetricValue,
116
- deltaPercent,
117
- metricLabel,
118
- metricType,
119
- totalHits,
120
- totalRelation = 'eq',
121
- onSelectBucket,
122
- }) => {
123
- const t = useT();
124
- const { token } = theme.useToken();
125
- const svgTitleId = useId();
126
- const [showTableAlt, setShowTableAlt] = useState(false);
127
-
128
- const activeSeriesKeys = useMemo(() => (seriesKeys && seriesKeys.length > 0 ? seriesKeys : []), [seriesKeys]);
129
- const hasMultiSeries = activeSeriesKeys.length > 0 && visualization !== 'pie' && visualization !== 'metric';
130
-
131
- const altTableColumns: TableColumnsType<ReportSeriesPoint> = useMemo(() => {
132
- const base: TableColumnsType<ReportSeriesPoint> = [{ title: t('Bucket Field'), dataIndex: 'label', key: 'label' }];
133
- if (hasMultiSeries) {
134
- for (const sKey of activeSeriesKeys) {
135
- base.push({
136
- title: sKey,
137
- key: `series-${sKey}`,
138
- render: (_: unknown, row: ReportSeriesPoint) => {
139
- const sub = row.breakdown?.find((b) => b.seriesKey === sKey);
140
- return sub ? sub.value.toLocaleString() : '0';
141
- },
142
- });
143
- }
144
- } else {
145
- base.push({ title: metricLabel || t('Value'), dataIndex: 'value', key: 'value' });
146
- }
147
- base.push({ title: t('Hits'), dataIndex: 'count', key: 'count' });
148
- return base;
149
- }, [activeSeriesKeys, hasMultiSeries, metricLabel, t]);
150
-
151
- if (visualization === 'metric') {
152
- const isTruncatedCount =
153
- totalRelation === 'gte' && (metricType === 'count' || metricType === undefined || metricValue === totalHits);
154
- return (
155
- <Card variant="borderless" style={{ textAlign: 'center', padding: '16px 8px' }}>
156
- <Statistic
157
- title={metricLabel || title}
158
- value={metricValue ?? 0}
159
- prefix={isTruncatedCount ? '≥ ' : undefined}
160
- valueStyle={{ fontSize: 36, fontWeight: 600, color: token.colorPrimary }}
161
- />
162
- {deltaPercent !== undefined && deltaPercent !== null && (
163
- <div style={{ marginTop: 6 }}>
164
- <Tag color={deltaPercent > 0 ? 'geekblue' : deltaPercent < 0 ? 'cyan' : 'default'}>
165
- {deltaPercent > 0 ? `▲ +${deltaPercent}%` : deltaPercent < 0 ? `▼ ${deltaPercent}%` : '0%'}
166
- </Tag>
167
- {previousMetricValue !== undefined && previousMetricValue !== null && (
168
- <Text type="secondary" style={{ fontSize: 12 }}>
169
- {t('vs previous period')}: {previousMetricValue.toLocaleString()}
170
- </Text>
171
- )}
172
- </div>
173
- )}
174
- <div style={{ marginTop: 4 }}>
175
- <Text type="secondary" style={{ fontSize: 12 }}>
176
- {t('Hits')}: {totalHits.toLocaleString()}
177
- {totalRelation === 'gte' ? '+' : ''}
178
- </Text>
179
- </div>
180
- </Card>
181
- );
182
- }
183
-
184
- if (!series.length) {
185
- return <Empty description={t('No matching documents')} />;
186
- }
187
-
188
- const svgWidth = 760;
189
- const svgHeight = 260;
190
- const padLeft = 56;
191
- const padRight = 24;
192
- const padTop = 20;
193
- const padBottom = 46;
194
- const plotW = svgWidth - padLeft - padRight;
195
- const plotH = svgHeight - padTop - padBottom;
196
-
197
- const isPercentStack = hasMultiSeries && stackMode === 'percent';
198
- const isStacked = hasMultiSeries && (stackMode === 'stacked' || stackMode === 'percent');
199
-
200
- const computedMaxVal = (() => {
201
- if (isPercentStack) return 100;
202
- if (isStacked) {
203
- return Math.max(
204
- 1,
205
- ...series.map((pt) => (pt.breakdown ?? []).reduce((acc, sub) => acc + Math.max(0, sub.value), 0)),
206
- );
207
- }
208
- if (hasMultiSeries) {
209
- return Math.max(1, ...series.flatMap((pt) => (pt.breakdown ?? []).map((sub) => Math.abs(sub.value))));
210
- }
211
- return Math.max(1, ...series.map((p) => Math.abs(p.value)));
212
- })();
213
-
214
- const renderCartesian = () => {
215
- const ticks = [0, 0.25, 0.5, 0.75, 1];
216
- if (visualization === 'bar') {
217
- const gap = Math.max(6, Math.min(20, Math.floor(plotW / (series.length * 4))));
218
- const barW = Math.max(8, (plotW - gap * (series.length + 1)) / series.length);
219
- return (
220
- <svg
221
- role="img"
222
- aria-labelledby={svgTitleId}
223
- viewBox={`0 0 ${svgWidth} ${svgHeight}`}
224
- style={{ width: '100%', height: svgHeight, display: 'block' }}
225
- >
226
- <title id={svgTitleId}>{`${title} — ${metricLabel}`}</title>
227
- {ticks.map((ratio) => {
228
- const y = padTop + plotH * (1 - ratio);
229
- const tickLabel = isPercentStack
230
- ? `${Math.round(ratio * 100)}%`
231
- : formatCompactNumber(computedMaxVal * ratio);
232
- return (
233
- <g key={`grid-${ratio}`}>
234
- <line
235
- x1={padLeft}
236
- y1={y}
237
- x2={svgWidth - padRight}
238
- y2={y}
239
- stroke={token.colorSplit}
240
- strokeDasharray="3 3"
241
- />
242
- <text x={padLeft - 8} y={y + 4} textAnchor="end" fontSize={11} fill={token.colorTextSecondary}>
243
- {tickLabel}
244
- </text>
245
- </g>
246
- );
247
- })}
248
- {series.map((pt, idx) => {
249
- const groupX = padLeft + gap + idx * (barW + gap);
250
- const showLabel = series.length <= 12 || idx % Math.ceil(series.length / 8) === 0;
251
-
252
- if (hasMultiSeries) {
253
- const bucketSum = Math.max(
254
- 0.0001,
255
- (pt.breakdown ?? []).reduce((sum, b) => sum + Math.max(0, b.value), 0),
256
- );
257
- if (isStacked) {
258
- let cumulativeH = 0;
259
- return (
260
- <g key={`${pt.key}-${idx}`}>
261
- {activeSeriesKeys.map((sKey, sIdx) => {
262
- const subVal = Math.max(0, pt.breakdown?.find((b) => b.seriesKey === sKey)?.value ?? 0);
263
- const normRatio = isPercentStack ? subVal / bucketSum : subVal / computedMaxVal;
264
- const segH = Math.max(0, normRatio * plotH);
265
- const segY = padTop + plotH - cumulativeH - segH;
266
- cumulativeH += segH;
267
- if (segH <= 0) return null;
268
- const tooltipVal = isPercentStack
269
- ? `${sKey}: ${subVal.toLocaleString()} (${((subVal / bucketSum) * 100).toFixed(1)}%)`
270
- : `${sKey}: ${subVal.toLocaleString()}`;
271
- return (
272
- <Tooltip key={sKey} title={`${pt.label} · ${tooltipVal}`}>
273
- <rect
274
- x={groupX}
275
- y={segY}
276
- width={barW}
277
- height={segH}
278
- fill={PALETTE[sIdx % PALETTE.length]}
279
- style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
280
- onClick={() => onSelectBucket?.(pt.key)}
281
- />
282
- </Tooltip>
283
- );
284
- })}
285
- {showLabel && (
286
- <text
287
- x={groupX + barW / 2}
288
- y={svgHeight - 16}
289
- textAnchor="middle"
290
- fontSize={11}
291
- fill={token.colorTextSecondary}
292
- >
293
- {truncateLabel(pt.label, 14)}
294
- </text>
295
- )}
296
- </g>
297
- );
298
- }
299
-
300
- // Grouped side-by-side bars
301
- const subBarW = Math.max(3, (barW - (activeSeriesKeys.length - 1) * 2) / activeSeriesKeys.length);
302
- return (
303
- <g key={`${pt.key}-${idx}`}>
304
- {activeSeriesKeys.map((sKey, sIdx) => {
305
- const subVal = Math.max(0, pt.breakdown?.find((b) => b.seriesKey === sKey)?.value ?? 0);
306
- const segH = Math.max(subVal > 0 ? 2 : 0, (subVal / computedMaxVal) * plotH);
307
- const subX = groupX + sIdx * (subBarW + 2);
308
- const subY = padTop + plotH - segH;
309
- return (
310
- <Tooltip key={sKey} title={`${pt.label} · ${sKey}: ${subVal.toLocaleString()}`}>
311
- <rect
312
- x={subX}
313
- y={subY}
314
- width={subBarW}
315
- height={segH}
316
- rx={2}
317
- fill={PALETTE[sIdx % PALETTE.length]}
318
- style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
319
- onClick={() => onSelectBucket?.(pt.key)}
320
- />
321
- </Tooltip>
322
- );
323
- })}
324
- {showLabel && (
325
- <text
326
- x={groupX + barW / 2}
327
- y={svgHeight - 16}
328
- textAnchor="middle"
329
- fontSize={11}
330
- fill={token.colorTextSecondary}
331
- >
332
- {truncateLabel(pt.label, 14)}
333
- </text>
334
- )}
335
- </g>
336
- );
337
- }
338
-
339
- const h = Math.max(2, (Math.max(0, pt.value) / computedMaxVal) * plotH);
340
- const y = padTop + plotH - h;
341
- const color = PALETTE[idx % PALETTE.length];
342
- return (
343
- <g key={`${pt.key}-${idx}`}>
344
- <Tooltip title={`${pt.label}: ${pt.value.toLocaleString()} (${pt.count} docs)`}>
345
- <rect
346
- x={groupX}
347
- y={y}
348
- width={barW}
349
- height={h}
350
- rx={3}
351
- fill={color}
352
- style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
353
- onClick={() => onSelectBucket?.(pt.key)}
354
- />
355
- </Tooltip>
356
- {showLabel && (
357
- <text
358
- x={groupX + barW / 2}
359
- y={svgHeight - 16}
360
- textAnchor="middle"
361
- fontSize={11}
362
- fill={token.colorTextSecondary}
363
- >
364
- {truncateLabel(pt.label, 14)}
365
- </text>
366
- )}
367
- </g>
368
- );
369
- })}
370
- </svg>
371
- );
372
- }
373
-
374
- // Line or Area chart (single-series or multi-series)
375
- const stepX = series.length > 1 ? plotW / (series.length - 1) : 0;
376
-
377
- if (hasMultiSeries) {
378
- return (
379
- <svg
380
- role="img"
381
- aria-labelledby={svgTitleId}
382
- viewBox={`0 0 ${svgWidth} ${svgHeight}`}
383
- style={{ width: '100%', height: svgHeight, display: 'block' }}
384
- >
385
- <title id={svgTitleId}>{`${title} — ${metricLabel}`}</title>
386
- {ticks.map((ratio) => {
387
- const y = padTop + plotH * (1 - ratio);
388
- return (
389
- <g key={`grid-${ratio}`}>
390
- <line
391
- x1={padLeft}
392
- y1={y}
393
- x2={svgWidth - padRight}
394
- y2={y}
395
- stroke={token.colorSplit}
396
- strokeDasharray="3 3"
397
- />
398
- <text x={padLeft - 8} y={y + 4} textAnchor="end" fontSize={11} fill={token.colorTextSecondary}>
399
- {formatCompactNumber(computedMaxVal * ratio)}
400
- </text>
401
- </g>
402
- );
403
- })}
404
- {activeSeriesKeys.map((sKey, sIdx) => {
405
- const color = PALETTE[sIdx % PALETTE.length];
406
- const pts = series.map((pt, idx) => {
407
- const x = series.length > 1 ? padLeft + idx * stepX : padLeft + plotW / 2;
408
- const val = Math.max(0, pt.breakdown?.find((b) => b.seriesKey === sKey)?.value ?? 0);
409
- const y = padTop + plotH - (val / computedMaxVal) * plotH;
410
- return { x, y, val, pt };
411
- });
412
- const polylineStr = pts.map((c) => `${c.x},${c.y}`).join(' ');
413
- const areaStr =
414
- pts.length > 0
415
- ? `M ${pts[0].x},${padTop + plotH} ` +
416
- pts.map((c) => `L ${c.x},${c.y}`).join(' ') +
417
- ` L ${pts[pts.length - 1].x},${padTop + plotH} Z`
418
- : '';
419
- return (
420
- <g key={sKey}>
421
- {visualization === 'area' && areaStr && <path d={areaStr} fill={color} opacity={0.16} />}
422
- <polyline fill="none" stroke={color} strokeWidth={2.2} points={polylineStr} />
423
- {pts.map((c, idx) => (
424
- <Tooltip key={`${sKey}-${idx}`} title={`${c.pt.label} · ${sKey}: ${c.val.toLocaleString()}`}>
425
- <circle cx={c.x} cy={c.y} r={3.5} fill={color} />
426
- </Tooltip>
427
- ))}
428
- </g>
429
- );
430
- })}
431
- {series.map((pt, idx) => {
432
- const showLabel = series.length <= 8 || idx % Math.ceil(series.length / 6) === 0;
433
- if (!showLabel) return null;
434
- const x = series.length > 1 ? padLeft + idx * stepX : padLeft + plotW / 2;
435
- return (
436
- <text
437
- key={`lbl-${idx}`}
438
- x={x}
439
- y={svgHeight - 16}
440
- textAnchor="middle"
441
- fontSize={11}
442
- fill={token.colorTextSecondary}
443
- >
444
- {truncateLabel(pt.label, 16)}
445
- </text>
446
- );
447
- })}
448
- </svg>
449
- );
450
- }
451
-
452
- const coords = series.map((pt, idx) => {
453
- const x = series.length > 1 ? padLeft + idx * stepX : padLeft + plotW / 2;
454
- const y = padTop + plotH - (Math.max(0, pt.value) / computedMaxVal) * plotH;
455
- return { x, y, pt };
456
- });
457
- const polylinePoints = coords.map((c) => `${c.x},${c.y}`).join(' ');
458
- const areaPath =
459
- coords.length > 0
460
- ? `M ${coords[0].x},${padTop + plotH} ` +
461
- coords.map((c) => `L ${c.x},${c.y}`).join(' ') +
462
- ` L ${coords[coords.length - 1].x},${padTop + plotH} Z`
463
- : '';
464
-
465
- return (
466
- <svg
467
- role="img"
468
- aria-labelledby={svgTitleId}
469
- viewBox={`0 0 ${svgWidth} ${svgHeight}`}
470
- style={{ width: '100%', height: svgHeight, display: 'block' }}
471
- >
472
- <title id={svgTitleId}>{`${title} — ${metricLabel}`}</title>
473
- {ticks.map((ratio) => {
474
- const y = padTop + plotH * (1 - ratio);
475
- return (
476
- <g key={`grid-${ratio}`}>
477
- <line
478
- x1={padLeft}
479
- y1={y}
480
- x2={svgWidth - padRight}
481
- y2={y}
482
- stroke={token.colorSplit}
483
- strokeDasharray="3 3"
484
- />
485
- <text x={padLeft - 8} y={y + 4} textAnchor="end" fontSize={11} fill={token.colorTextSecondary}>
486
- {formatCompactNumber(computedMaxVal * ratio)}
487
- </text>
488
- </g>
489
- );
490
- })}
491
- {visualization === 'area' && areaPath && <path d={areaPath} fill={token.colorPrimary} opacity={0.18} />}
492
- <polyline fill="none" stroke={token.colorPrimary} strokeWidth={2.5} points={polylinePoints} />
493
- {coords.map((c, idx) => {
494
- const showLabel = series.length <= 8 || idx % Math.ceil(series.length / 6) === 0;
495
- return (
496
- <g key={`${c.pt.key}-${idx}`}>
497
- <Tooltip title={`${c.pt.label}: ${c.pt.value.toLocaleString()}`}>
498
- <circle
499
- cx={c.x}
500
- cy={c.y}
501
- r={4}
502
- fill={token.colorPrimary}
503
- style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
504
- onClick={() => onSelectBucket?.(c.pt.key)}
505
- />
506
- </Tooltip>
507
- {showLabel && (
508
- <text x={c.x} y={svgHeight - 16} textAnchor="middle" fontSize={11} fill={token.colorTextSecondary}>
509
- {truncateLabel(c.pt.label, 16)}
510
- </text>
511
- )}
512
- </g>
513
- );
514
- })}
515
- </svg>
516
- );
517
- };
518
-
519
- const renderPie = () => {
520
- const totalValue = series.reduce((sum, item) => sum + Math.max(0, item.value), 0) || 1;
521
- const cx = 130;
522
- const cy = 120;
523
- const r = 95;
524
- let cumulativeAngle = -Math.PI / 2;
525
-
526
- return (
527
- <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 24 }}>
528
- <svg role="img" aria-labelledby={svgTitleId} viewBox="0 0 260 240" style={{ width: 260, height: 240 }}>
529
- <title id={svgTitleId}>{`${title} — ${metricLabel}`}</title>
530
- {series.map((item, idx) => {
531
- const val = Math.max(0, item.value);
532
- const sliceAngle = (val / totalValue) * Math.PI * 2;
533
- const startAngle = cumulativeAngle;
534
- const endAngle = cumulativeAngle + sliceAngle;
535
- cumulativeAngle = endAngle;
536
-
537
- const x1 = cx + r * Math.cos(startAngle);
538
- const y1 = cy + r * Math.sin(startAngle);
539
- const x2 = cx + r * Math.cos(endAngle);
540
- const y2 = cy + r * Math.sin(endAngle);
541
- const largeArc = sliceAngle > Math.PI ? 1 : 0;
542
- const pathData =
543
- series.length === 1
544
- ? `M ${cx} ${cy - r} A ${r} ${r} 0 1 1 ${cx - 0.01} ${cy - r} Z`
545
- : `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} Z`;
546
- const pct = ((val / totalValue) * 100).toFixed(1);
547
-
548
- return (
549
- <Tooltip key={`${item.key}-${idx}`} title={`${item.label}: ${item.value.toLocaleString()} (${pct}%)`}>
550
- <path
551
- d={pathData}
552
- fill={PALETTE[idx % PALETTE.length]}
553
- stroke={token.colorBgContainer}
554
- strokeWidth={1.5}
555
- style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
556
- onClick={() => onSelectBucket?.(item.key)}
557
- />
558
- </Tooltip>
559
- );
560
- })}
561
- </svg>
562
- <div style={{ flex: 1, minWidth: 200 }}>
563
- <Space direction="vertical" size={6} style={{ width: '100%' }}>
564
- {series.map((item, idx) => {
565
- const pct = ((Math.max(0, item.value) / totalValue) * 100).toFixed(1);
566
- return (
567
- <div
568
- key={`legend-${item.key}-${idx}`}
569
- style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 13 }}
570
- >
571
- <Space size={8}>
572
- <span
573
- aria-hidden="true"
574
- style={{
575
- display: 'inline-block',
576
- width: 10,
577
- height: 10,
578
- borderRadius: 2,
579
- backgroundColor: PALETTE[idx % PALETTE.length],
580
- }}
581
- />
582
- <Text ellipsis style={{ maxWidth: 220 }}>
583
- {item.label}
584
- </Text>
585
- </Space>
586
- <Text strong>
587
- {item.value.toLocaleString()} ({pct}%)
588
- </Text>
589
- </div>
590
- );
591
- })}
592
- </Space>
593
- </div>
594
- </div>
595
- );
596
- };
597
-
598
- return (
599
- <figure style={{ margin: 0, width: '100%', maxWidth: '100%', minWidth: 0 }}>
600
- <div
601
- style={{
602
- display: 'flex',
603
- flexWrap: 'wrap',
604
- justifyContent: 'space-between',
605
- alignItems: 'center',
606
- gap: 8,
607
- marginBottom: 8,
608
- }}
609
- >
610
- <figcaption style={{ fontSize: 12, color: token.colorTextSecondary }}>
611
- {metricLabel} · {t('Hits')}: {totalHits.toLocaleString()}
612
- {totalRelation === 'gte' ? '+' : ''}
613
- </figcaption>
614
- <Space wrap size={12}>
615
- {hasMultiSeries &&
616
- activeSeriesKeys.map((sKey, sIdx) => (
617
- <span key={sKey} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12 }}>
618
- <span
619
- aria-hidden="true"
620
- style={{
621
- display: 'inline-block',
622
- width: 10,
623
- height: 10,
624
- borderRadius: 2,
625
- backgroundColor: PALETTE[sIdx % PALETTE.length],
626
- }}
627
- />
628
- <span>{sKey}</span>
629
- </span>
630
- ))}
631
- <Button size="small" type="link" onClick={() => setShowTableAlt((prev) => !prev)}>
632
- {showTableAlt ? t('Show chart') : t('Show data table')}
633
- </Button>
634
- </Space>
635
- </div>
636
- {showTableAlt ? (
637
- <Table
638
- size="small"
639
- rowKey="key"
640
- pagination={false}
641
- scroll={{ x: 'max-content' }}
642
- dataSource={series}
643
- columns={altTableColumns}
644
- />
645
- ) : visualization === 'pie' ? (
646
- renderPie()
647
- ) : (
648
- renderCartesian()
649
- )}
650
- </figure>
651
- );
652
- };
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 { Button, Card, Empty, Space, Statistic, Table, Tag, Tooltip, Typography, theme } from 'antd';
11
+ import type { TableColumnsType } from 'antd';
12
+ import React, { useId, useMemo, useState } from 'react';
13
+ import type {
14
+ ChartStackMode,
15
+ MetricAggType,
16
+ ReportHistogramBucket,
17
+ ReportSeriesPoint,
18
+ ReportVisualizationType,
19
+ } from '../../shared/types';
20
+ import { useT } from '../locale';
21
+
22
+ const { Text } = Typography;
23
+
24
+ const PALETTE = ['#1677ff', '#13c2c2', '#52c41a', '#fa8c16', '#722ed1', '#eb2f96', '#2f54eb', '#faad14'];
25
+
26
+ function formatCompactNumber(val: number): string {
27
+ if (!Number.isFinite(val)) return '0';
28
+ if (Math.abs(val) >= 1_000_000) return `${(val / 1_000_000).toFixed(2)}M`;
29
+ if (Math.abs(val) >= 1_000) return `${(val / 1_000).toFixed(1)}k`;
30
+ return Number.isInteger(val) ? String(val) : val.toFixed(2);
31
+ }
32
+
33
+ function truncateLabel(text: string, maxLen = 18): string {
34
+ if (text.length <= maxLen) return text;
35
+ return `${text.slice(0, maxLen - 1)}…`;
36
+ }
37
+
38
+ export interface ReportHistogramStripProps {
39
+ buckets: ReportHistogramBucket[];
40
+ }
41
+
42
+ export const ReportHistogramStrip: React.FC<ReportHistogramStripProps> = ({ buckets }) => {
43
+ const t = useT();
44
+ const { token } = theme.useToken();
45
+ const titleId = useId();
46
+
47
+ if (!buckets.length) return null;
48
+ const maxCount = Math.max(1, ...buckets.map((b) => b.count));
49
+ const width = 720;
50
+ const height = 68;
51
+ const barGap = 2;
52
+ const barWidth = Math.max(4, (width - barGap * buckets.length) / buckets.length);
53
+
54
+ return (
55
+ <figure style={{ margin: '0 0 12px 0' }}>
56
+ <svg
57
+ role="img"
58
+ aria-labelledby={titleId}
59
+ viewBox={`0 0 ${width} ${height}`}
60
+ style={{ width: '100%', height: 68, display: 'block' }}
61
+ >
62
+ <title id={titleId}>{t('Date Histogram')}</title>
63
+ {buckets.map((bucket, index) => {
64
+ const barHeight = Math.max(bucket.count > 0 ? 3 : 1, Math.round((bucket.count / maxCount) * (height - 14)));
65
+ const x = index * (barWidth + barGap);
66
+ const y = height - barHeight - 2;
67
+ return (
68
+ <Tooltip key={`${bucket.key}-${index}`} title={`${bucket.key}: ${bucket.count}`}>
69
+ <rect
70
+ x={x}
71
+ y={y}
72
+ width={barWidth}
73
+ height={barHeight}
74
+ rx={2}
75
+ fill={bucket.count > 0 ? token.colorPrimary : token.colorFillSecondary}
76
+ opacity={0.85}
77
+ />
78
+ </Tooltip>
79
+ );
80
+ })}
81
+ </svg>
82
+ <figcaption
83
+ style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: token.colorTextSecondary }}
84
+ >
85
+ <span>{buckets[0]?.key}</span>
86
+ <span>{buckets[buckets.length - 1]?.key}</span>
87
+ </figcaption>
88
+ </figure>
89
+ );
90
+ };
91
+
92
+ export interface ElasticBasicChartProps {
93
+ title: string;
94
+ visualization: Exclude<ReportVisualizationType, 'table'>;
95
+ series: ReportSeriesPoint[];
96
+ seriesKeys?: string[];
97
+ stackMode?: ChartStackMode;
98
+ metricValue: number | null;
99
+ previousMetricValue?: number | null;
100
+ deltaPercent?: number | null;
101
+ metricLabel: string;
102
+ metricType?: MetricAggType;
103
+ totalHits: number;
104
+ totalRelation?: 'eq' | 'gte';
105
+ onSelectBucket?: (bucketKey: string) => void;
106
+ }
107
+
108
+ export const ElasticBasicChart: React.FC<ElasticBasicChartProps> = ({
109
+ title,
110
+ visualization,
111
+ series,
112
+ seriesKeys,
113
+ stackMode = 'none',
114
+ metricValue,
115
+ previousMetricValue,
116
+ deltaPercent,
117
+ metricLabel,
118
+ metricType,
119
+ totalHits,
120
+ totalRelation = 'eq',
121
+ onSelectBucket,
122
+ }) => {
123
+ const t = useT();
124
+ const { token } = theme.useToken();
125
+ const svgTitleId = useId();
126
+ const [showTableAlt, setShowTableAlt] = useState(false);
127
+
128
+ const activeSeriesKeys = useMemo(() => (seriesKeys && seriesKeys.length > 0 ? seriesKeys : []), [seriesKeys]);
129
+ const hasMultiSeries = activeSeriesKeys.length > 0 && visualization !== 'pie' && visualization !== 'metric';
130
+
131
+ const altTableColumns: TableColumnsType<ReportSeriesPoint> = useMemo(() => {
132
+ const base: TableColumnsType<ReportSeriesPoint> = [{ title: t('Bucket Field'), dataIndex: 'label', key: 'label' }];
133
+ if (hasMultiSeries) {
134
+ for (const sKey of activeSeriesKeys) {
135
+ base.push({
136
+ title: sKey,
137
+ key: `series-${sKey}`,
138
+ render: (_: unknown, row: ReportSeriesPoint) => {
139
+ const sub = row.breakdown?.find((b) => b.seriesKey === sKey);
140
+ return sub ? sub.value.toLocaleString() : '0';
141
+ },
142
+ });
143
+ }
144
+ } else {
145
+ base.push({ title: metricLabel || t('Value'), dataIndex: 'value', key: 'value' });
146
+ }
147
+ base.push({ title: t('Hits'), dataIndex: 'count', key: 'count' });
148
+ return base;
149
+ }, [activeSeriesKeys, hasMultiSeries, metricLabel, t]);
150
+
151
+ if (visualization === 'metric') {
152
+ const isTruncatedCount =
153
+ totalRelation === 'gte' && (metricType === 'count' || metricType === undefined || metricValue === totalHits);
154
+ return (
155
+ <Card variant="borderless" style={{ textAlign: 'center', padding: '16px 8px' }}>
156
+ <Statistic
157
+ title={metricLabel || title}
158
+ value={metricValue ?? 0}
159
+ prefix={isTruncatedCount ? '≥ ' : undefined}
160
+ valueStyle={{ fontSize: 36, fontWeight: 600, color: token.colorPrimary }}
161
+ />
162
+ {deltaPercent !== undefined && deltaPercent !== null && (
163
+ <div style={{ marginTop: 6 }}>
164
+ <Tag color={deltaPercent > 0 ? 'geekblue' : deltaPercent < 0 ? 'cyan' : 'default'}>
165
+ {deltaPercent > 0 ? `▲ +${deltaPercent}%` : deltaPercent < 0 ? `▼ ${deltaPercent}%` : '0%'}
166
+ </Tag>
167
+ {previousMetricValue !== undefined && previousMetricValue !== null && (
168
+ <Text type="secondary" style={{ fontSize: 12 }}>
169
+ {t('vs previous period')}: {previousMetricValue.toLocaleString()}
170
+ </Text>
171
+ )}
172
+ </div>
173
+ )}
174
+ <div style={{ marginTop: 4 }}>
175
+ <Text type="secondary" style={{ fontSize: 12 }}>
176
+ {t('Hits')}: {totalHits.toLocaleString()}
177
+ {totalRelation === 'gte' ? '+' : ''}
178
+ </Text>
179
+ </div>
180
+ </Card>
181
+ );
182
+ }
183
+
184
+ if (!series.length) {
185
+ return <Empty description={t('No matching documents')} />;
186
+ }
187
+
188
+ const svgWidth = 760;
189
+ const svgHeight = 260;
190
+ const padLeft = 56;
191
+ const padRight = 24;
192
+ const padTop = 20;
193
+ const padBottom = 46;
194
+ const plotW = svgWidth - padLeft - padRight;
195
+ const plotH = svgHeight - padTop - padBottom;
196
+
197
+ const isPercentStack = hasMultiSeries && stackMode === 'percent';
198
+ const isStacked = hasMultiSeries && (stackMode === 'stacked' || stackMode === 'percent');
199
+
200
+ const computedMaxVal = (() => {
201
+ if (isPercentStack) return 100;
202
+ if (isStacked) {
203
+ return Math.max(
204
+ 1,
205
+ ...series.map((pt) => (pt.breakdown ?? []).reduce((acc, sub) => acc + Math.max(0, sub.value), 0)),
206
+ );
207
+ }
208
+ if (hasMultiSeries) {
209
+ return Math.max(1, ...series.flatMap((pt) => (pt.breakdown ?? []).map((sub) => Math.abs(sub.value))));
210
+ }
211
+ return Math.max(1, ...series.map((p) => Math.abs(p.value)));
212
+ })();
213
+
214
+ const renderCartesian = () => {
215
+ const ticks = [0, 0.25, 0.5, 0.75, 1];
216
+ if (visualization === 'bar') {
217
+ const gap = Math.max(6, Math.min(20, Math.floor(plotW / (series.length * 4))));
218
+ const barW = Math.max(8, (plotW - gap * (series.length + 1)) / series.length);
219
+ return (
220
+ <svg
221
+ role="img"
222
+ aria-labelledby={svgTitleId}
223
+ viewBox={`0 0 ${svgWidth} ${svgHeight}`}
224
+ style={{ width: '100%', height: svgHeight, display: 'block' }}
225
+ >
226
+ <title id={svgTitleId}>{`${title} — ${metricLabel}`}</title>
227
+ {ticks.map((ratio) => {
228
+ const y = padTop + plotH * (1 - ratio);
229
+ const tickLabel = isPercentStack
230
+ ? `${Math.round(ratio * 100)}%`
231
+ : formatCompactNumber(computedMaxVal * ratio);
232
+ return (
233
+ <g key={`grid-${ratio}`}>
234
+ <line
235
+ x1={padLeft}
236
+ y1={y}
237
+ x2={svgWidth - padRight}
238
+ y2={y}
239
+ stroke={token.colorSplit}
240
+ strokeDasharray="3 3"
241
+ />
242
+ <text x={padLeft - 8} y={y + 4} textAnchor="end" fontSize={11} fill={token.colorTextSecondary}>
243
+ {tickLabel}
244
+ </text>
245
+ </g>
246
+ );
247
+ })}
248
+ {series.map((pt, idx) => {
249
+ const groupX = padLeft + gap + idx * (barW + gap);
250
+ const showLabel = series.length <= 12 || idx % Math.ceil(series.length / 8) === 0;
251
+
252
+ if (hasMultiSeries) {
253
+ const bucketSum = Math.max(
254
+ 0.0001,
255
+ (pt.breakdown ?? []).reduce((sum, b) => sum + Math.max(0, b.value), 0),
256
+ );
257
+ if (isStacked) {
258
+ let cumulativeH = 0;
259
+ return (
260
+ <g key={`${pt.key}-${idx}`}>
261
+ {activeSeriesKeys.map((sKey, sIdx) => {
262
+ const subVal = Math.max(0, pt.breakdown?.find((b) => b.seriesKey === sKey)?.value ?? 0);
263
+ const normRatio = isPercentStack ? subVal / bucketSum : subVal / computedMaxVal;
264
+ const segH = Math.max(0, normRatio * plotH);
265
+ const segY = padTop + plotH - cumulativeH - segH;
266
+ cumulativeH += segH;
267
+ if (segH <= 0) return null;
268
+ const tooltipVal = isPercentStack
269
+ ? `${sKey}: ${subVal.toLocaleString()} (${((subVal / bucketSum) * 100).toFixed(1)}%)`
270
+ : `${sKey}: ${subVal.toLocaleString()}`;
271
+ return (
272
+ <Tooltip key={sKey} title={`${pt.label} · ${tooltipVal}`}>
273
+ <rect
274
+ x={groupX}
275
+ y={segY}
276
+ width={barW}
277
+ height={segH}
278
+ fill={PALETTE[sIdx % PALETTE.length]}
279
+ style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
280
+ onClick={() => onSelectBucket?.(pt.key)}
281
+ />
282
+ </Tooltip>
283
+ );
284
+ })}
285
+ {showLabel && (
286
+ <text
287
+ x={groupX + barW / 2}
288
+ y={svgHeight - 16}
289
+ textAnchor="middle"
290
+ fontSize={11}
291
+ fill={token.colorTextSecondary}
292
+ >
293
+ {truncateLabel(pt.label, 14)}
294
+ </text>
295
+ )}
296
+ </g>
297
+ );
298
+ }
299
+
300
+ // Grouped side-by-side bars
301
+ const subBarW = Math.max(3, (barW - (activeSeriesKeys.length - 1) * 2) / activeSeriesKeys.length);
302
+ return (
303
+ <g key={`${pt.key}-${idx}`}>
304
+ {activeSeriesKeys.map((sKey, sIdx) => {
305
+ const subVal = Math.max(0, pt.breakdown?.find((b) => b.seriesKey === sKey)?.value ?? 0);
306
+ const segH = Math.max(subVal > 0 ? 2 : 0, (subVal / computedMaxVal) * plotH);
307
+ const subX = groupX + sIdx * (subBarW + 2);
308
+ const subY = padTop + plotH - segH;
309
+ return (
310
+ <Tooltip key={sKey} title={`${pt.label} · ${sKey}: ${subVal.toLocaleString()}`}>
311
+ <rect
312
+ x={subX}
313
+ y={subY}
314
+ width={subBarW}
315
+ height={segH}
316
+ rx={2}
317
+ fill={PALETTE[sIdx % PALETTE.length]}
318
+ style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
319
+ onClick={() => onSelectBucket?.(pt.key)}
320
+ />
321
+ </Tooltip>
322
+ );
323
+ })}
324
+ {showLabel && (
325
+ <text
326
+ x={groupX + barW / 2}
327
+ y={svgHeight - 16}
328
+ textAnchor="middle"
329
+ fontSize={11}
330
+ fill={token.colorTextSecondary}
331
+ >
332
+ {truncateLabel(pt.label, 14)}
333
+ </text>
334
+ )}
335
+ </g>
336
+ );
337
+ }
338
+
339
+ const h = Math.max(2, (Math.max(0, pt.value) / computedMaxVal) * plotH);
340
+ const y = padTop + plotH - h;
341
+ const color = PALETTE[idx % PALETTE.length];
342
+ return (
343
+ <g key={`${pt.key}-${idx}`}>
344
+ <Tooltip title={`${pt.label}: ${pt.value.toLocaleString()} (${pt.count} docs)`}>
345
+ <rect
346
+ x={groupX}
347
+ y={y}
348
+ width={barW}
349
+ height={h}
350
+ rx={3}
351
+ fill={color}
352
+ style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
353
+ onClick={() => onSelectBucket?.(pt.key)}
354
+ />
355
+ </Tooltip>
356
+ {showLabel && (
357
+ <text
358
+ x={groupX + barW / 2}
359
+ y={svgHeight - 16}
360
+ textAnchor="middle"
361
+ fontSize={11}
362
+ fill={token.colorTextSecondary}
363
+ >
364
+ {truncateLabel(pt.label, 14)}
365
+ </text>
366
+ )}
367
+ </g>
368
+ );
369
+ })}
370
+ </svg>
371
+ );
372
+ }
373
+
374
+ // Line or Area chart (single-series or multi-series)
375
+ const stepX = series.length > 1 ? plotW / (series.length - 1) : 0;
376
+
377
+ if (hasMultiSeries) {
378
+ return (
379
+ <svg
380
+ role="img"
381
+ aria-labelledby={svgTitleId}
382
+ viewBox={`0 0 ${svgWidth} ${svgHeight}`}
383
+ style={{ width: '100%', height: svgHeight, display: 'block' }}
384
+ >
385
+ <title id={svgTitleId}>{`${title} — ${metricLabel}`}</title>
386
+ {ticks.map((ratio) => {
387
+ const y = padTop + plotH * (1 - ratio);
388
+ return (
389
+ <g key={`grid-${ratio}`}>
390
+ <line
391
+ x1={padLeft}
392
+ y1={y}
393
+ x2={svgWidth - padRight}
394
+ y2={y}
395
+ stroke={token.colorSplit}
396
+ strokeDasharray="3 3"
397
+ />
398
+ <text x={padLeft - 8} y={y + 4} textAnchor="end" fontSize={11} fill={token.colorTextSecondary}>
399
+ {formatCompactNumber(computedMaxVal * ratio)}
400
+ </text>
401
+ </g>
402
+ );
403
+ })}
404
+ {activeSeriesKeys.map((sKey, sIdx) => {
405
+ const color = PALETTE[sIdx % PALETTE.length];
406
+ const pts = series.map((pt, idx) => {
407
+ const x = series.length > 1 ? padLeft + idx * stepX : padLeft + plotW / 2;
408
+ const val = Math.max(0, pt.breakdown?.find((b) => b.seriesKey === sKey)?.value ?? 0);
409
+ const y = padTop + plotH - (val / computedMaxVal) * plotH;
410
+ return { x, y, val, pt };
411
+ });
412
+ const polylineStr = pts.map((c) => `${c.x},${c.y}`).join(' ');
413
+ const areaStr =
414
+ pts.length > 0
415
+ ? `M ${pts[0].x},${padTop + plotH} ` +
416
+ pts.map((c) => `L ${c.x},${c.y}`).join(' ') +
417
+ ` L ${pts[pts.length - 1].x},${padTop + plotH} Z`
418
+ : '';
419
+ return (
420
+ <g key={sKey}>
421
+ {visualization === 'area' && areaStr && <path d={areaStr} fill={color} opacity={0.16} />}
422
+ <polyline fill="none" stroke={color} strokeWidth={2.2} points={polylineStr} />
423
+ {pts.map((c, idx) => (
424
+ <Tooltip key={`${sKey}-${idx}`} title={`${c.pt.label} · ${sKey}: ${c.val.toLocaleString()}`}>
425
+ <circle cx={c.x} cy={c.y} r={3.5} fill={color} />
426
+ </Tooltip>
427
+ ))}
428
+ </g>
429
+ );
430
+ })}
431
+ {series.map((pt, idx) => {
432
+ const showLabel = series.length <= 8 || idx % Math.ceil(series.length / 6) === 0;
433
+ if (!showLabel) return null;
434
+ const x = series.length > 1 ? padLeft + idx * stepX : padLeft + plotW / 2;
435
+ return (
436
+ <text
437
+ key={`lbl-${idx}`}
438
+ x={x}
439
+ y={svgHeight - 16}
440
+ textAnchor="middle"
441
+ fontSize={11}
442
+ fill={token.colorTextSecondary}
443
+ >
444
+ {truncateLabel(pt.label, 16)}
445
+ </text>
446
+ );
447
+ })}
448
+ </svg>
449
+ );
450
+ }
451
+
452
+ const coords = series.map((pt, idx) => {
453
+ const x = series.length > 1 ? padLeft + idx * stepX : padLeft + plotW / 2;
454
+ const y = padTop + plotH - (Math.max(0, pt.value) / computedMaxVal) * plotH;
455
+ return { x, y, pt };
456
+ });
457
+ const polylinePoints = coords.map((c) => `${c.x},${c.y}`).join(' ');
458
+ const areaPath =
459
+ coords.length > 0
460
+ ? `M ${coords[0].x},${padTop + plotH} ` +
461
+ coords.map((c) => `L ${c.x},${c.y}`).join(' ') +
462
+ ` L ${coords[coords.length - 1].x},${padTop + plotH} Z`
463
+ : '';
464
+
465
+ return (
466
+ <svg
467
+ role="img"
468
+ aria-labelledby={svgTitleId}
469
+ viewBox={`0 0 ${svgWidth} ${svgHeight}`}
470
+ style={{ width: '100%', height: svgHeight, display: 'block' }}
471
+ >
472
+ <title id={svgTitleId}>{`${title} — ${metricLabel}`}</title>
473
+ {ticks.map((ratio) => {
474
+ const y = padTop + plotH * (1 - ratio);
475
+ return (
476
+ <g key={`grid-${ratio}`}>
477
+ <line
478
+ x1={padLeft}
479
+ y1={y}
480
+ x2={svgWidth - padRight}
481
+ y2={y}
482
+ stroke={token.colorSplit}
483
+ strokeDasharray="3 3"
484
+ />
485
+ <text x={padLeft - 8} y={y + 4} textAnchor="end" fontSize={11} fill={token.colorTextSecondary}>
486
+ {formatCompactNumber(computedMaxVal * ratio)}
487
+ </text>
488
+ </g>
489
+ );
490
+ })}
491
+ {visualization === 'area' && areaPath && <path d={areaPath} fill={token.colorPrimary} opacity={0.18} />}
492
+ <polyline fill="none" stroke={token.colorPrimary} strokeWidth={2.5} points={polylinePoints} />
493
+ {coords.map((c, idx) => {
494
+ const showLabel = series.length <= 8 || idx % Math.ceil(series.length / 6) === 0;
495
+ return (
496
+ <g key={`${c.pt.key}-${idx}`}>
497
+ <Tooltip title={`${c.pt.label}: ${c.pt.value.toLocaleString()}`}>
498
+ <circle
499
+ cx={c.x}
500
+ cy={c.y}
501
+ r={4}
502
+ fill={token.colorPrimary}
503
+ style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
504
+ onClick={() => onSelectBucket?.(c.pt.key)}
505
+ />
506
+ </Tooltip>
507
+ {showLabel && (
508
+ <text x={c.x} y={svgHeight - 16} textAnchor="middle" fontSize={11} fill={token.colorTextSecondary}>
509
+ {truncateLabel(c.pt.label, 16)}
510
+ </text>
511
+ )}
512
+ </g>
513
+ );
514
+ })}
515
+ </svg>
516
+ );
517
+ };
518
+
519
+ const renderPie = () => {
520
+ const totalValue = series.reduce((sum, item) => sum + Math.max(0, item.value), 0) || 1;
521
+ const cx = 130;
522
+ const cy = 120;
523
+ const r = 95;
524
+ let cumulativeAngle = -Math.PI / 2;
525
+
526
+ return (
527
+ <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 24 }}>
528
+ <svg role="img" aria-labelledby={svgTitleId} viewBox="0 0 260 240" style={{ width: 260, height: 240 }}>
529
+ <title id={svgTitleId}>{`${title} — ${metricLabel}`}</title>
530
+ {series.map((item, idx) => {
531
+ const val = Math.max(0, item.value);
532
+ const sliceAngle = (val / totalValue) * Math.PI * 2;
533
+ const startAngle = cumulativeAngle;
534
+ const endAngle = cumulativeAngle + sliceAngle;
535
+ cumulativeAngle = endAngle;
536
+
537
+ const x1 = cx + r * Math.cos(startAngle);
538
+ const y1 = cy + r * Math.sin(startAngle);
539
+ const x2 = cx + r * Math.cos(endAngle);
540
+ const y2 = cy + r * Math.sin(endAngle);
541
+ const largeArc = sliceAngle > Math.PI ? 1 : 0;
542
+ const pathData =
543
+ series.length === 1
544
+ ? `M ${cx} ${cy - r} A ${r} ${r} 0 1 1 ${cx - 0.01} ${cy - r} Z`
545
+ : `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} Z`;
546
+ const pct = ((val / totalValue) * 100).toFixed(1);
547
+
548
+ return (
549
+ <Tooltip key={`${item.key}-${idx}`} title={`${item.label}: ${item.value.toLocaleString()} (${pct}%)`}>
550
+ <path
551
+ d={pathData}
552
+ fill={PALETTE[idx % PALETTE.length]}
553
+ stroke={token.colorBgContainer}
554
+ strokeWidth={1.5}
555
+ style={{ cursor: onSelectBucket ? 'pointer' : 'default' }}
556
+ onClick={() => onSelectBucket?.(item.key)}
557
+ />
558
+ </Tooltip>
559
+ );
560
+ })}
561
+ </svg>
562
+ <div style={{ flex: 1, minWidth: 200 }}>
563
+ <Space direction="vertical" size={6} style={{ width: '100%' }}>
564
+ {series.map((item, idx) => {
565
+ const pct = ((Math.max(0, item.value) / totalValue) * 100).toFixed(1);
566
+ return (
567
+ <div
568
+ key={`legend-${item.key}-${idx}`}
569
+ style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 13 }}
570
+ >
571
+ <Space size={8}>
572
+ <span
573
+ aria-hidden="true"
574
+ style={{
575
+ display: 'inline-block',
576
+ width: 10,
577
+ height: 10,
578
+ borderRadius: 2,
579
+ backgroundColor: PALETTE[idx % PALETTE.length],
580
+ }}
581
+ />
582
+ <Text ellipsis style={{ maxWidth: 220 }}>
583
+ {item.label}
584
+ </Text>
585
+ </Space>
586
+ <Text strong>
587
+ {item.value.toLocaleString()} ({pct}%)
588
+ </Text>
589
+ </div>
590
+ );
591
+ })}
592
+ </Space>
593
+ </div>
594
+ </div>
595
+ );
596
+ };
597
+
598
+ return (
599
+ <figure style={{ margin: 0, width: '100%', maxWidth: '100%', minWidth: 0 }}>
600
+ <div
601
+ style={{
602
+ display: 'flex',
603
+ flexWrap: 'wrap',
604
+ justifyContent: 'space-between',
605
+ alignItems: 'center',
606
+ gap: 8,
607
+ marginBottom: 8,
608
+ }}
609
+ >
610
+ <figcaption style={{ fontSize: 12, color: token.colorTextSecondary }}>
611
+ {metricLabel} · {t('Hits')}: {totalHits.toLocaleString()}
612
+ {totalRelation === 'gte' ? '+' : ''}
613
+ </figcaption>
614
+ <Space wrap size={12}>
615
+ {hasMultiSeries &&
616
+ activeSeriesKeys.map((sKey, sIdx) => (
617
+ <span key={sKey} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12 }}>
618
+ <span
619
+ aria-hidden="true"
620
+ style={{
621
+ display: 'inline-block',
622
+ width: 10,
623
+ height: 10,
624
+ borderRadius: 2,
625
+ backgroundColor: PALETTE[sIdx % PALETTE.length],
626
+ }}
627
+ />
628
+ <span>{sKey}</span>
629
+ </span>
630
+ ))}
631
+ <Button size="small" type="link" onClick={() => setShowTableAlt((prev) => !prev)}>
632
+ {showTableAlt ? t('Show chart') : t('Show data table')}
633
+ </Button>
634
+ </Space>
635
+ </div>
636
+ {showTableAlt ? (
637
+ <Table
638
+ size="small"
639
+ rowKey="key"
640
+ pagination={false}
641
+ scroll={{ x: 'max-content' }}
642
+ dataSource={series}
643
+ columns={altTableColumns}
644
+ />
645
+ ) : visualization === 'pie' ? (
646
+ renderPie()
647
+ ) : (
648
+ renderCartesian()
649
+ )}
650
+ </figure>
651
+ );
652
+ };