-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSmoothieComponent.tsx
316 lines (255 loc) · 8.75 KB
/
SmoothieComponent.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import * as React from 'react';
import { SmoothieChart, TimeSeries, IChartOptions, ITimeSeriesOptions, ITimeSeriesPresentationOptions } from 'smoothie';
function DefaultTooltip(props: { display?: boolean; time?: number; data?: TooltipData }) {
if (!props.display) return <div />;
return (
<div style={{ userSelect: 'none' }}>
<strong>{props.time}</strong>
{props.data ? (
<ul>
{props.data.map((data, i) => (
<li key={i}>{data.value}</li>
))}
</ul>
) : (
<div />
)}
</div>
);
}
export type ToolTip = typeof DefaultTooltip;
// TODO: SmoothieCharts should update their types so that this is less hacky
type CanvasStyle = CanvasGradient | CanvasPattern;
/**
* undefined means 0
*/
type rgba = { r?: number; g?: number; b?: number; a?: number };
type RGBA = Required<rgba>;
export type PresentationOptions = rgba & {
fillStyle?: rgba | CanvasStyle | ITimeSeriesPresentationOptions['fillStyle'];
strokeStyle?: rgba | CanvasStyle | ITimeSeriesPresentationOptions['strokeStyle'];
} & Omit<ITimeSeriesPresentationOptions, 'fillStyle' | 'strokeStyle'>;
function isCanvasStyle(value: any): value is CanvasStyle {
return value instanceof CanvasGradient || value instanceof CanvasPattern;
}
function isRgba(style: PresentationOptions['fillStyle'] | PresentationOptions['strokeStyle']): style is rgba {
if (isCanvasStyle(style)) return false;
if (typeof style !== 'object') return false;
return true;
return typeof style === 'object';
}
function convertRGBAtoCSSString(rgba: RGBA): string {
const css = `rgba(${rgba.r},${rgba.g},${rgba.b},${rgba.a})`;
return css;
}
function extractRGBAFromPresentationOptions(options: PresentationOptions): RGBA {
const { r, g, b, a } = options;
return {
r: r ?? 0,
g: g ?? 0,
b: b ?? 0,
a: a ?? 0,
};
}
/**
* We want to let users specify the presentation options a little more loosely.
*
* This converts our `PresentationOptions` to the options that SmoothieChart expects.
*/
function seriesOptsParser(opts: PresentationOptions): ITimeSeriesPresentationOptions {
const defColor = extractRGBAFromPresentationOptions(opts);
let fillStyle: PresentationOptions['fillStyle'];
if (isCanvasStyle(opts.fillStyle) || typeof opts.fillStyle === 'string') {
fillStyle = opts.fillStyle;
} else {
fillStyle = convertRGBAtoCSSString({ ...defColor, ...{ a: 0.2 }, ...opts.fillStyle });
}
let strokeStyle: PresentationOptions['strokeStyle'];
if (isCanvasStyle(opts.strokeStyle) || typeof opts.strokeStyle === 'string') {
strokeStyle = opts.strokeStyle;
} else {
strokeStyle = convertRGBAtoCSSString({ ...defColor, ...{ a: 1 }, ...opts.strokeStyle });
}
const ret = {
...opts,
data: '',
// TODO: SmoothieCharts should update their types so that this is less hacky
fillStyle: fillStyle as ITimeSeriesPresentationOptions['fillStyle'],
strokeStyle: strokeStyle as ITimeSeriesPresentationOptions['strokeStyle'],
};
delete ret.r;
delete ret.g;
delete ret.b;
delete ret.a;
delete ret.data;
return ret;
}
type TooltipData = { series: any; index: number; value: number }[];
type SmoothieComponentState = {
tooltip: { time?: number; data?: TooltipData; display?: boolean; top?: number; left?: number };
};
type Style = { [x: string]: number | string };
export type SmoothieComponentSeries = { data: TimeSeries } & PresentationOptions;
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
/**
* Props that we've defined in this package
*/
type ReactSmoothieProps = {
streamDelay?: number;
height?: number;
width?: number;
series?: SmoothieComponentSeries[];
tooltip?: true | false | ToolTip;
doNotSimplifyData?: boolean;
style?: Style;
tooltipParentStyle?: Style;
containerStyle?: Style;
classNameCanvas?: string;
className?: string;
classNameTooltip?: string;
classNameContainer?: string;
};
/**
* Props that we pass onto underlying Smoothie instance
*/
type SmoothieProps = Omit<IChartOptions, 'tooltip'>;
export type SmoothieComponentProps = ReactSmoothieProps & SmoothieProps;
class SmoothieComponent extends React.Component<SmoothieComponentProps, SmoothieComponentState> {
smoothie: SmoothieChart;
canvas: HTMLCanvasElement;
static defaultProps = {
width: 800,
height: 200,
streamDelay: 0,
};
constructor(props: SmoothieComponentProps) {
super(props);
this.state = { tooltip: {} };
let opts: IChartOptions = Object.assign({}, props, { tooltip: !!props.tooltip });
// SmoothieCharts's tooltip injects a div at the end of the page.
// This will not do. We shall make our own and intercept the data.
let updateTooltip = (o: SmoothieComponentState['tooltip']) => {
this.setState(state => {
Object.assign(state.tooltip, o);
return state;
});
};
opts.tooltipFormatter = (t, data) => {
updateTooltip({
time: t,
data: props.doNotSimplifyData
? data
: data.map(set => ({
index: set.index,
value: set.value,
series: { options: (set.series as TimeSeries & { options: any }).options },
})),
});
return '';
};
let smoothie = new SmoothieChart(opts) as SmoothieChart & {
// We need to tell TypeScript about some non-exposed internal variables
mouseY: number;
mouseX: number;
// TODO: type this more better
tooltipEl: any;
};
let lastDisplay: string;
// Intercept the set data
smoothie.tooltipEl = {
style: {
// Intercept when smoothie.js sets tooltipEl.style.display
set display(v: 'block' | 'string') {
if (v === lastDisplay) return;
lastDisplay = v;
updateTooltip({ display: v == 'block' });
},
// Get smoothie's mouse events
set top(v: any) {
updateTooltip({
top: smoothie.mouseY,
left: smoothie.mouseX,
});
},
},
};
if (props.series) {
props.series.forEach(series => {
if (!(series.data instanceof TimeSeries)) {
throw Error('Invalid type passed to series option');
}
smoothie.addTimeSeries(series.data, seriesOptsParser(series));
});
}
this.smoothie = smoothie;
}
componentWillUnmount() {
this.smoothie.stop();
}
componentDidUpdate(prevProps: SmoothieComponentProps, prevState: SmoothieComponentState) {
for (const series of prevProps.series) {
if (!this.props.series.includes(series)) this.smoothie.removeTimeSeries(series.data);
}
for (const series of this.props.series) {
if (!prevProps.series.includes(series)) this.smoothie.addTimeSeries(series.data, seriesOptsParser(series));
}
}
render() {
let style = {} as { [x: string]: number | string };
if (this.props.responsive === true) {
style.width = '100%';
style.height = this.props.height;
}
// Prevent extra pixels in wrapping element
style.display = 'block';
style = this.props.style || style;
let tooltipParentStyle = this.props.tooltipParentStyle || {
pointerEvents: 'none',
position: 'absolute',
left: this.state.tooltip.left,
top: this.state.tooltip.top,
};
let Tooltip = this.props.tooltip as boolean | ToolTip;
if (Tooltip === true) {
Tooltip = DefaultTooltip;
}
let canvas = (
<canvas
className={this.props.classNameCanvas || this.props.className}
style={style}
width={this.props.responsive === true ? undefined : this.props.width}
height={this.props.height}
ref={canv => (this.canvas = canv) && this.smoothie.streamTo(canv, this.props.streamDelay)}
/>
);
let tooltip;
if (Tooltip) {
tooltip = (
<div style={tooltipParentStyle} className={this.props.classNameTooltip}>
<Tooltip {...this.state.tooltip} />
</div>
);
}
return (
<div className={this.props.classNameContainer} style={this.props.containerStyle || { position: 'relative' }}>
{canvas}
{tooltip}
</div>
);
}
addTimeSeries(addOpts: PresentationOptions): TimeSeries;
addTimeSeries(tsOpts: ITimeSeriesOptions, addOpts: PresentationOptions): TimeSeries;
addTimeSeries(tsOpts: PresentationOptions | ITimeSeriesOptions, addOpts?: PresentationOptions): TimeSeries {
if (addOpts === undefined) {
addOpts = tsOpts as PresentationOptions;
tsOpts = undefined;
}
let ts = tsOpts instanceof TimeSeries ? tsOpts : new TimeSeries(tsOpts as ITimeSeriesOptions);
this.smoothie.addTimeSeries(ts, seriesOptsParser(addOpts));
return ts;
}
removeTimeSeries(ts: TimeSeries) {
this.smoothie.removeTimeSeries(ts);
}
}
export { SmoothieComponent as default, TimeSeries, DefaultTooltip };