/
GraphNG.tsx
227 lines (189 loc) · 7.42 KB
/
GraphNG.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import React, { Component } from 'react';
import uPlot, { AlignedData } from 'uplot';
import {
DataFrame,
DataLinkPostProcessor,
Field,
FieldMatcherID,
fieldMatchers,
FieldType,
getLinksSupplier,
InterpolateFunction,
TimeRange,
TimeZone,
} from '@grafana/data';
import { VizLegendOptions } from '@grafana/schema';
import { Themeable2, PanelContextRoot, VizLayout } from '@grafana/ui';
import { UPlotChart } from '@grafana/ui/src/components/uPlot/Plot';
import { AxisProps } from '@grafana/ui/src/components/uPlot/config/UPlotAxisBuilder';
import { Renderers, UPlotConfigBuilder } from '@grafana/ui/src/components/uPlot/config/UPlotConfigBuilder';
import { ScaleProps } from '@grafana/ui/src/components/uPlot/config/UPlotScaleBuilder';
import { pluginLog } from '@grafana/ui/src/components/uPlot/utils';
import { GraphNGLegendEvent, XYFieldMatchers } from './types';
import { preparePlotFrame as defaultPreparePlotFrame } from './utils';
/**
* @internal -- not a public API
*/
export type PropDiffFn<T extends any = any> = (prev: T, next: T) => boolean;
export interface GraphNGProps extends Themeable2 {
frames: DataFrame[];
structureRev?: number; // a number that will change when the frames[] structure changes
width: number;
height: number;
timeRange: TimeRange;
timeZone: TimeZone[] | TimeZone;
legend: VizLegendOptions;
fields?: XYFieldMatchers; // default will assume timeseries data
renderers?: Renderers;
tweakScale?: (opts: ScaleProps, forField: Field) => ScaleProps;
tweakAxis?: (opts: AxisProps, forField: Field) => AxisProps;
onLegendClick?: (event: GraphNGLegendEvent) => void;
children?: (builder: UPlotConfigBuilder, alignedFrame: DataFrame) => React.ReactNode;
prepConfig: (alignedFrame: DataFrame, allFrames: DataFrame[], getTimeRange: () => TimeRange) => UPlotConfigBuilder;
propsToDiff?: Array<string | PropDiffFn>;
preparePlotFrame?: (frames: DataFrame[], dimFields: XYFieldMatchers) => DataFrame | null;
renderLegend: (config: UPlotConfigBuilder) => React.ReactElement | null;
replaceVariables: InterpolateFunction;
dataLinkPostProcessor?: DataLinkPostProcessor;
/**
* needed for propsToDiff to re-init the plot & config
* this is a generic approach to plot re-init, without having to specify which panel-level options
* should cause invalidation. we can drop this in favor of something like panelOptionsRev that gets passed in
* similar to structureRev. then we can drop propsToDiff entirely.
*/
options?: Record<string, any>;
}
function sameProps(prevProps: any, nextProps: any, propsToDiff: Array<string | PropDiffFn> = []) {
for (const propName of propsToDiff) {
if (typeof propName === 'function') {
if (!propName(prevProps, nextProps)) {
return false;
}
} else if (nextProps[propName] !== prevProps[propName]) {
return false;
}
}
return true;
}
/**
* @internal -- not a public API
*/
export interface GraphNGState {
alignedFrame: DataFrame;
alignedData?: AlignedData;
config?: UPlotConfigBuilder;
}
/**
* "Time as X" core component, expects ascending x
*/
export class GraphNG extends Component<GraphNGProps, GraphNGState> {
static contextType = PanelContextRoot;
private plotInstance: React.RefObject<uPlot>;
constructor(props: GraphNGProps) {
super(props);
let state = this.prepState(props);
state.alignedData = state.config!.prepData!([state.alignedFrame]) as AlignedData;
this.state = state;
this.plotInstance = React.createRef();
}
getTimeRange = () => this.props.timeRange;
prepState(props: GraphNGProps, withConfig = true) {
let state: GraphNGState = null as any;
const { frames, fields, preparePlotFrame, replaceVariables, dataLinkPostProcessor } = props;
const preparePlotFrameFn = preparePlotFrame ?? defaultPreparePlotFrame;
const matchYDefault = fieldMatchers.get(FieldMatcherID.byTypes).get(new Set([FieldType.number, FieldType.enum]));
// if there are data links, we have to keep all fields so they're index-matched, then filter out dimFields.y
const withLinks = frames.some((frame) => frame.fields.some((field) => (field.config.links?.length ?? 0) > 0));
const dimFields = fields ?? {
x: fieldMatchers.get(FieldMatcherID.firstTimeField).get({}),
y: withLinks ? () => true : matchYDefault,
};
const alignedFrame = preparePlotFrameFn(frames, dimFields, props.timeRange);
pluginLog('GraphNG', false, 'data aligned', alignedFrame);
if (alignedFrame) {
let alignedFrameFinal = alignedFrame;
if (withLinks) {
const timeZone = Array.isArray(this.props.timeZone) ? this.props.timeZone[0] : this.props.timeZone;
alignedFrame.fields.forEach((field) => {
field.getLinks = getLinksSupplier(
alignedFrame,
field,
{
...field.state?.scopedVars,
__dataContext: {
value: {
data: [alignedFrame],
field: field,
frame: alignedFrame,
frameIndex: 0,
},
},
},
replaceVariables,
timeZone,
dataLinkPostProcessor
);
});
// filter join field and dimFields.y
alignedFrameFinal = {
...alignedFrame,
fields: alignedFrame.fields.filter((field, i) => i === 0 || dimFields.y(field, alignedFrame, [alignedFrame])),
};
}
let config = this.state?.config;
if (withConfig) {
config = props.prepConfig(alignedFrameFinal, this.props.frames, this.getTimeRange);
pluginLog('GraphNG', false, 'config prepared', config);
}
state = {
alignedFrame: alignedFrameFinal,
config,
};
pluginLog('GraphNG', false, 'data prepared', state.alignedData);
}
return state;
}
componentDidUpdate(prevProps: GraphNGProps) {
const { frames, structureRev, timeZone, propsToDiff } = this.props;
const propsChanged = !sameProps(prevProps, this.props, propsToDiff);
if (frames !== prevProps.frames || propsChanged || timeZone !== prevProps.timeZone) {
let newState = this.prepState(this.props, false);
if (newState) {
const shouldReconfig =
this.state.config === undefined ||
timeZone !== prevProps.timeZone ||
structureRev !== prevProps.structureRev ||
!structureRev ||
propsChanged;
if (shouldReconfig) {
newState.config = this.props.prepConfig(newState.alignedFrame, this.props.frames, this.getTimeRange);
pluginLog('GraphNG', false, 'config recreated', newState.config);
}
newState.alignedData = newState.config!.prepData!([newState.alignedFrame]) as AlignedData;
this.setState(newState);
}
}
}
render() {
const { width, height, children, renderLegend } = this.props;
const { config, alignedFrame, alignedData } = this.state;
if (!config) {
return null;
}
return (
<VizLayout width={width} height={height} legend={renderLegend(config)}>
{(vizWidth: number, vizHeight: number) => (
<UPlotChart
config={config}
data={alignedData!}
width={vizWidth}
height={vizHeight}
plotRef={(u) => ((this.plotInstance as React.MutableRefObject<uPlot>).current = u)}
>
{children ? children(config, alignedFrame) : null}
</UPlotChart>
)}
</VizLayout>
);
}
}