/
chart.ts
589 lines (534 loc) · 18.3 KB
/
chart.ts
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
import { SelectionModel } from '@angular/cdk/collections';
import { Platform } from '@angular/cdk/platform';
import {
AfterContentInit,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
ElementRef,
EventEmitter,
forwardRef,
Inject,
InjectionToken,
Input,
NgZone,
OnChanges,
OnDestroy,
Optional,
Output,
QueryList,
Self,
SimpleChanges,
SkipSelf,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import { DtViewportResizer } from '@dynatrace/angular-components/core';
import { DtTheme } from '@dynatrace/angular-components/theming';
// tslint:disable-next-line:no-duplicate-imports
import * as Highcharts from 'highcharts';
// tslint:disable-next-line:no-duplicate-imports
import {
addEvent as addHighchartsEvent,
chart,
ChartObject,
IndividualSeriesOptions,
Options as HighchartsOptions,
setOptions,
} from 'highcharts';
import { merge as lodashMerge } from 'lodash';
import {
BehaviorSubject,
defer,
merge,
Observable,
of,
Subject,
Subscription,
} from 'rxjs';
import {
delay,
distinctUntilChanged,
filter,
flatMap,
map,
switchMap,
take,
takeUntil,
} from 'rxjs/operators';
import {
DtChartConfig,
DT_CHART_CONFIG,
DT_CHART_DEFAULT_CONFIG,
} from './chart-config';
import { DT_CHART_DEFAULT_GLOBAL_OPTIONS } from './chart-options';
import {
DtChartHeatfield,
DtChartHeatfieldActiveChange,
} from './heatfield/chart-heatfield';
import { applyHighchartsErrorHandler } from './highcharts/highcharts-errors';
import { configureLegendSymbols } from './highcharts/highcharts-legend-overrides';
import {
addTooltipEvents,
DtHcTooltipEventPayload,
findHoveredSeriesIndex,
} from './highcharts/highcharts-tooltip-extensions';
import { DtChartTooltipEvent } from './highcharts/highcharts-tooltip-types';
import {
applyHighchartsColorOptions,
createHighchartOptions,
} from './highcharts/highcharts-util';
import { DtChartRange } from './range/range';
import { DtChartTimestamp } from './timestamp/timestamp';
const HIGHCHARTS_PLOT_BACKGROUND = '.highcharts-plot-background';
const CHART_INTERSECTION_THRESHOLD = 0.9;
export type DtChartOptions = HighchartsOptions & {
series?: undefined;
tooltip?: { shared: boolean };
interpolateGaps?: boolean;
};
export type DtChartSeries = IndividualSeriesOptions;
// tslint:disable-next-line:no-any
declare const window: any;
// tslint:disable-next-line:no-any
declare var require: any;
/* DANGER ZONE - this function needs to be self executing so uglify does not drop the call */
// tslint:disable-next-line:no-var-requires no-require-imports
window.highchartsMore = require('highcharts/highcharts-more')(Highcharts);
// Override Highcharts prototypes
// added to the window so uglify does not drop this from the bundle
window.configureLegendSymbols = configureLegendSymbols;
// Highcharts global options, set outside component so its not set every time a chart is created
setOptions(DT_CHART_DEFAULT_GLOBAL_OPTIONS);
// added to the window so uglify does not drop this from the bundle
window.highchartsTooltipEventsAdded = addTooltipEvents();
// add global Highcharts error handler for server side logging
applyHighchartsErrorHandler();
/** Injection token used to get the instance of the dt-chart instance */
export const DT_CHART_RESOLVER = new InjectionToken<() => DtChart>(
'dt-chart-resolver',
);
/**
* @internal
* Resolver similar to forward ref since we don't have the chart in the constructor necessarily (e.g. micro charts),
* we might only have it afterViewInit
*/
export type DtChartResolver = () => DtChart;
/**
* @internal
* Factory used to get the DtChartResolver
* this needs to be written as below without lambda expressions due to a compiler bug,
* see https://github.com/angular/angular/issues/23629 for further information
*/
export function DT_CHART_RESOVER_PROVIDER_FACTORY(c: DtChart): DtChartResolver {
const resolver = () => c;
return resolver;
}
@Component({
moduleId: module.id,
selector: 'dt-chart',
styleUrls: ['./chart.scss'],
templateUrl: './chart.html',
exportAs: 'dtChart',
host: {
class: 'dt-chart',
},
// disabled ViewEncapsulation because some html is generated by highcharts
// so it does not get the classes from angular
// tslint:disable-next-line: use-view-encapsulation
encapsulation: ViewEncapsulation.None,
preserveWhitespaces: false,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{
provide: DT_CHART_RESOLVER,
useFactory: DT_CHART_RESOVER_PROVIDER_FACTORY,
deps: [[new Self(), DtChart]],
},
],
})
export class DtChart
implements AfterViewInit, OnDestroy, OnChanges, AfterContentInit {
/** Options to configure the chart. */
@Input()
get options(): DtChartOptions {
return this._options;
}
set options(options: DtChartOptions) {
this._options = options;
this._changeDetectorRef.markForCheck();
}
/** Series of data points or a stream rendered in this chart */
@Input()
get series(): Observable<DtChartSeries[]> | DtChartSeries[] | undefined {
return this._series;
}
set series(
series: Observable<DtChartSeries[]> | DtChartSeries[] | undefined,
) {
if (this._dataSub) {
this._dataSub.unsubscribe();
this._dataSub = null;
}
if (series instanceof Observable) {
this._dataSub = series.subscribe((s: DtChartSeries[]) => {
this._currentSeries = s;
this._update();
});
} else {
this._currentSeries = series;
}
this._series = series;
this._changeDetectorRef.markForCheck();
}
/** The loading text of the loading distractor. */
@Input('loading-text') loadingText: string;
/** Eventemitter that fires every time the chart is updated */
@Output() readonly updated: EventEmitter<void> = new EventEmitter();
/** Eventemitter that fires every time the tooltip opens or closes */
@Output() readonly tooltipOpenChange: EventEmitter<
boolean
> = new EventEmitter();
/** Eventemitter that fires every time the data inside the chart tooltip changes */
@Output()
readonly tooltipDataChange: EventEmitter<DtChartTooltipEvent | null> = new EventEmitter();
/** returns an array of ids for the series data */
get seriesIds(): Array<string | undefined> | undefined {
return (
this._highchartsOptions.series &&
this._highchartsOptions.series.map((s: IndividualSeriesOptions) => s.id)
);
}
/**
* Returns the combined highcharts options for the chart
* combines series and options passed, merged with the defaultOptions
*/
get highchartsOptions(): HighchartsOptions {
// To make sure the consumer cannot modify the internal highcharts options
// (which could result in a broken state) the object will be cloned.
return this._highchartsOptions
? lodashMerge({}, this._highchartsOptions)
: {};
}
@ViewChild('container', { static: true }) container: ElementRef<HTMLElement>;
// tslint:disable-next-line: no-forward-ref
@ContentChildren(forwardRef(() => DtChartHeatfield)) _heatfields: QueryList<
DtChartHeatfield
>;
/** @internal Instance of the Chart range used by the selection area */
@ContentChild(DtChartRange, { static: false }) _range?: DtChartRange;
/** @internal Instance of the Chart timestamp used by the selection area */
@ContentChild(DtChartTimestamp, { static: false })
_timestamp?: DtChartTimestamp;
private _series?: Observable<DtChartSeries[]> | DtChartSeries[];
private _currentSeries?: IndividualSeriesOptions[];
private _options: DtChartOptions;
private _dataSub: Subscription | null = null;
private _highchartsOptions: HighchartsOptions;
private readonly _destroy$ = new Subject<void>();
private readonly _tooltipRefreshed: Subject<DtChartTooltipEvent | null> = new Subject();
private _isTooltipOpen = false;
/** @internal whether the chart is in the viewport or not */
_isInViewport$ = createInViewportStream(
this._elementRef,
this._platform.isBrowser,
CHART_INTERSECTION_THRESHOLD,
);
/** Deals with the selection logic. */
private _heatfieldSelectionModel: SelectionModel<DtChartHeatfield>;
/** @internal The offset of the plotBackground in relation to the chart container on the xAxis */
_plotBackgroundChartOffset = 0;
/** @internal stream that emits every time the plotBackground changes */
_plotBackground$ = new BehaviorSubject<SVGRectElement | null>(null);
/**
* @internal
* hold the state if there is a range or a timestamp if one of them is there we need a selection area
*/
_hasSelectionArea = false;
/** @internal Emits when highcharts finishes rendering. */
readonly _afterRender = new Subject<void>();
/** @internal The highcharts chart object */
_chartObject: ChartObject | null;
/** @internal Whether the loading distractor should be shown. */
get _isLoading(): boolean {
return (
this._highchartsOptions &&
(!this._highchartsOptions.series ||
!this._highchartsOptions.series.length)
);
}
private readonly _heatfieldActiveChanges: Observable<
DtChartHeatfieldActiveChange
> = defer(() => {
if (this._heatfields) {
return merge<DtChartHeatfieldActiveChange>(
...this._heatfields.map(heatfield => heatfield.activeChange),
);
}
return this._ngZone.onStable.asObservable().pipe(
take(1),
switchMap(() => this._heatfieldActiveChanges),
);
});
constructor(
private _changeDetectorRef: ChangeDetectorRef,
private _ngZone: NgZone,
@Optional() private _viewportResizer: DtViewportResizer,
@Optional() @SkipSelf() private _theme: DtTheme,
@Optional()
@SkipSelf()
@Inject(DT_CHART_CONFIG)
private _config: DtChartConfig,
private _platform: Platform,
/** @internal used for the selection area to calculate the bounding client rect */
public _elementRef: ElementRef,
) {
this._config = this._config || DT_CHART_DEFAULT_CONFIG;
if (this._viewportResizer) {
this._viewportResizer
.change()
.pipe(
takeUntil(this._destroy$),
delay(0),
) // delay to postpone the reflow to the next change detection cycle
.subscribe(() => {
if (this._chartObject) {
this._ngZone.runOutsideAngular(() => {
this._chartObject!.reflow();
});
}
});
}
if (this._theme) {
this._theme._stateChanges
.pipe(takeUntil(this._destroy$))
.subscribe(() => {
if (this._currentSeries && this._highchartsOptions) {
this._updateColorOptions();
this._updateChart(false);
}
});
}
this._heatfieldActiveChanges
.pipe(takeUntil(this._destroy$))
.subscribe(event => {
this._onHeatfieldActivate(event.source);
});
this._tooltipRefreshed
.pipe(
takeUntil(this._destroy$),
filter(Boolean),
map(ev => {
if (ev.data.points) {
// We need to clone the series here, because highcharts mutates the object and
// we therefore cannot create a compare function that compares the last with the next emission
ev.data.points = ev.data.points.map(p => ({
...p,
series: { ...p.series },
}));
}
return ev;
}),
distinctUntilChanged((a, b) => {
if (a && b) {
return (
a.data.x === b.data.x &&
a.data.y === b.data.y &&
findHoveredSeriesIndex(a) === findHoveredSeriesIndex(b)
);
}
return false;
}),
)
.subscribe(ev => {
this.tooltipDataChange.next(ev);
});
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.series || changes.options) {
this._update();
}
}
ngAfterViewInit(): void {
// Creating a new highcharts chart.
// This needs to be done outside the ngZone so the events, highcharts listens to, do not pollute our change detection.
this._chartObject = this._ngZone.runOutsideAngular(() =>
chart(this.container.nativeElement, this.highchartsOptions),
);
addHighchartsEvent(this._chartObject, 'redraw', () => {
this._notifyAfterRender();
});
this._notifyAfterRender();
// adds event-listener to highcharts custom event for tooltip closed
addHighchartsEvent(this._chartObject, 'tooltipClosed', () => {
this._isTooltipOpen = false;
this.tooltipOpenChange.emit(false);
this._tooltipRefreshed.next(null);
});
// Adds event-listener to highcharts custom event for tooltip refreshed closed */
// We cannot type the event param, because the types for highcharts are incorrect
// tslint:disable-next-line:no-any
addHighchartsEvent(this._chartObject, 'tooltipRefreshed', (event: any) => {
if (!this._isTooltipOpen) {
this._isTooltipOpen = true;
this.tooltipOpenChange.emit(true);
}
this._tooltipRefreshed.next({
data: (event as DtHcTooltipEventPayload).data,
chart: this._chartObject!,
});
});
// set the toPixels method on the timestamp and range to calculate a px value for an
// value on the xAxis alongside with the toValue function.
if (this._chartObject) {
const xAxis = this._chartObject.xAxis[0];
if (this._timestamp) {
this._timestamp._valueToPixels = xAxis.toPixels.bind(xAxis);
this._timestamp._pixelsToValue = xAxis.toValue.bind(xAxis);
this._timestamp._maxValue = xAxis.dataMax;
this._timestamp._minValue = xAxis.dataMin;
}
if (this._range) {
this._range._valueToPixels = xAxis.toPixels.bind(xAxis);
this._range._pixelsToValue = xAxis.toValue.bind(xAxis);
this._range._maxValue = xAxis.dataMax;
this._range._minValue = xAxis.dataMin;
}
}
}
ngAfterContentInit(): void {
this._heatfieldSelectionModel = new SelectionModel<DtChartHeatfield>();
this._heatfieldSelectionModel.changed
.pipe(takeUntil(this._destroy$))
.subscribe(event => {
event.added.forEach(heatfield => {
heatfield.active = true;
});
event.removed.forEach(heatfield => {
heatfield.active = false;
});
});
if (this._range || this._timestamp) {
this._hasSelectionArea = true;
}
}
ngOnDestroy(): void {
this._destroy$.next();
this._destroy$.complete();
if (this._chartObject) {
this._chartObject.destroy();
// Cleanup reference here so we don't trigger more things afterwards
this._chartObject = null;
}
if (this._dataSub) {
this._dataSub.unsubscribe();
}
this._afterRender.complete();
}
/** @internal Resets the pointer so Highcharts handles new mouse interactions correctly (e.g. after programmatic destruction of tooltips) */
_resetHighchartsPointer(): void {
this._ngZone.runOutsideAngular(() => {
// tslint:disable-next-line: no-any
(this._chartObject! as any).pointer.reset();
});
}
/** @internal Creates new highcharts options and applies it to the chart. */
_update(): void {
const highchartsOptions = createHighchartOptions(
this._options,
this._currentSeries,
);
// Check if x Axis type has changes (e.g. numeric -> category)
const xAxisHasChanged =
highchartsOptions.xAxis !== this.highchartsOptions.xAxis;
this._highchartsOptions = highchartsOptions;
this._updateColorOptions();
this._updateChart(xAxisHasChanged);
this._changeDetectorRef.markForCheck();
}
/** @internal toggles the tooltip and updates the chart with the new settings */
_toggleTooltip(enabled: boolean): void {
if (this._highchartsOptions.tooltip!.enabled !== enabled) {
this._highchartsOptions.tooltip!.enabled = enabled;
this._updateChart(false);
}
}
private _notifyAfterRender(): void {
this._afterRender.next();
const plotBackground = this.container.nativeElement.querySelector<
SVGRectElement
>(HIGHCHARTS_PLOT_BACKGROUND);
// set the offset of the plotBackground in relation to the chart
this._setPlotBackgroundOffset(plotBackground);
this._plotBackground$.next(plotBackground);
}
/** Calculates and sets the offset of the plot-background to the Chart container on the xAxis */
private _setPlotBackgroundOffset(
plotBackground: SVGRectElement | null,
): void {
this._plotBackgroundChartOffset = plotBackground
? plotBackground.getBoundingClientRect().left -
this.container.nativeElement.getBoundingClientRect().left
: 0;
}
/** Invoked when an heatfield is activated. */
private _onHeatfieldActivate(heatfield: DtChartHeatfield): void {
const wasActive = this._heatfieldSelectionModel.isSelected(heatfield);
if (heatfield.active) {
this._heatfieldSelectionModel.select(heatfield);
} else {
this._heatfieldSelectionModel.deselect(heatfield);
}
if (wasActive !== this._heatfieldSelectionModel.isSelected(heatfield)) {
this._changeDetectorRef.markForCheck();
}
}
/** Updates the chart with current options and series. */
private _updateChart(xAxisHasChanged: boolean): void {
if (this._chartObject) {
this._ngZone.runOutsideAngular(() => {
if (xAxisHasChanged) {
this._chartObject!.update({ series: [] }, false, true);
}
this._chartObject!.update({ ...this._highchartsOptions }, true, true);
});
this.updated.emit();
}
}
private _updateColorOptions(): void {
if (this._config.shouldUpdateColors) {
this._highchartsOptions = applyHighchartsColorOptions(
this._highchartsOptions,
this._theme,
);
}
}
}
/** Creates a cold stream that emits whenever the intersection of the nativeelement of the given elementRef changes */
function createInViewportStream(
elementRef: ElementRef,
isBrowser: boolean,
threshold: number | number[] = 1,
): Observable<boolean> {
return isBrowser && window && window.IntersectionObserver
? new Observable<IntersectionObserverEntry[]>(observer => {
const intersectionObserver = new IntersectionObserver(
entries => {
observer.next(entries);
},
{ threshold },
);
intersectionObserver.observe(elementRef.nativeElement);
return () => {
intersectionObserver.disconnect();
};
}).pipe(
flatMap(entries => entries),
map(entry => entry.isIntersecting),
distinctUntilChanged(),
)
: of(true);
}