/
chart.ts
715 lines (640 loc) · 21.9 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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/**
* @license
* Copyright 2019 Dynatrace LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { SelectionModel } from '@angular/cdk/collections';
import { Platform } from '@angular/cdk/platform';
import {
AfterContentInit,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
ElementRef,
EventEmitter,
Inject,
InjectionToken,
Input,
NgZone,
OnChanges,
OnDestroy,
Optional,
Output,
QueryList,
Self,
SimpleChanges,
SkipSelf,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {
createInViewportStream,
DtViewportResizer,
isDefined,
} from '@dynatrace/barista-components/core';
import { DtTheme } from '@dynatrace/barista-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,
Subject,
Subscription,
} from 'rxjs';
import {
delay,
distinctUntilChanged,
filter,
map,
mapTo,
startWith,
switchMap,
take,
takeUntil,
withLatestFrom,
} 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 { getDtHeatfieldUnsupportedChartError } from './heatfield/chart-heatfield-errors';
import { applyHighchartsErrorHandler } from './highcharts/highcharts-errors';
import { configureLegendSymbols } from './highcharts/highcharts-legend-overrides';
import {
addTooltipEvents,
compareTooltipEventChanged,
DtHcTooltipEventPayload,
} 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';
import { DtChartTooltip } from './tooltip/chart-tooltip';
import { getPlotBackgroundInfo } from './utils';
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;
window.highchartsGlobalOptions = ((): void => {
setOptions(DT_CHART_DEFAULT_GLOBAL_OPTIONS);
})();
// Highcharts global options, set outside component so its not set every time a chart is created
// 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;
}
export interface DtChartSeriesVisibilityChangeEvent {
source: DtChart;
visible: boolean;
series: DtChartSeries;
}
/** Maps the states of a tooltip to numbers to handle them easier */
const enum TooltipStateType {
CLOSED,
OPENED,
UPDATED,
}
/** A class that holds the tooltip state along with the event data */
class TooltipState {
constructor(
public status: TooltipStateType,
public event?: DtChartTooltipEvent,
) {}
}
@Component({
selector: 'dt-chart',
styleUrls: ['./chart.scss'],
templateUrl: './chart.html',
exportAs: 'dtChart',
host: {
class: 'dt-chart',
'[class.dt-chart-selectable]': '_hasSelectionArea',
},
// 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
*
* @breaking-change Only emit `<DtChartTooltipEvent>` in 5.0.0 in case that no null will be emitted
*/
@Output()
readonly tooltipDataChange: EventEmitter<DtChartTooltipEvent | null> = new EventEmitter();
/** Eventemitter that fires every time a legend item is clicked and a series visibility changes */
@Output()
readonly seriesVisibilityChange = new EventEmitter<
DtChartSeriesVisibilityChangeEvent
>();
/** 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)
: {};
}
/**
* Reference to the container element.
*
* @breaking-change Make internal in 5.0.0
*/
@ViewChild('container', { static: true }) container: ElementRef<HTMLElement>;
/** @internal The chart tooltip reference */
@ContentChildren(DtChartTooltip) _tooltip: QueryList<DtChartTooltip>;
/** @internal List of Heatfield references */
@ContentChildren(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>();
/** @internal whether the chart is in the viewport or not */
_isInViewport$ = createInViewportStream(
this._elementRef,
CHART_INTERSECTION_THRESHOLD,
);
/** Deals with the selection logic. */
private _heatfieldSelectionModel: SelectionModel<DtChartHeatfield>;
/** @internal Emits the tooltip data when it changed */
_highChartsTooltipDataChanged$ = new Subject<DtChartTooltipEvent>();
/** @internal Emits when the tooltip should be opened with the provided data */
_highChartsTooltipOpened$ = new Subject<DtChartTooltipEvent>();
/** @internal Emits when the tooltip should be closed */
_highChartsTooltipClosed$ = new Subject<void>();
/** @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,
// @breaking-change 5.0.0 Remove platform param
// tslint:disable-next-line: no-any
_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()
// delay to postpone the reflow to the next change detection cycle
.pipe(
takeUntil(this._destroy$),
delay(0),
)
.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();
}
});
}
this._heatfieldActiveChanges
.pipe(takeUntil(this._destroy$))
.subscribe(event => {
this._onHeatfieldActivate(event.source);
});
// uses the ContentChild of the DtChartTooltip to toggle and update
// the tooltip according to the highcharts events.
this._handleTooltipChange();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.series || changes.options) {
this._update();
}
}
ngAfterViewInit(): void {
this._createHighchartsChart();
}
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;
}
if (this._heatfields.length) {
this._afterRender
.pipe(
withLatestFrom(this._plotBackground$),
filter(Boolean),
takeUntil(this._destroy$),
)
.subscribe(([_void, plotBackground]) => {
if (this._chartObject) {
const clientRect = getPlotBackgroundInfo(plotBackground);
this._checkHeatfieldSupport();
this._heatfields.forEach(heatfield => {
heatfield._initHeatfield(clientRect, this._chartObject!);
});
}
});
}
}
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,
);
this._highchartsOptions = highchartsOptions;
this._updateColorOptions();
this._updateChart();
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();
}
}
/** Handles the tooltips open and closing along with the updating of the data */
private _handleTooltipChange(): void {
this._highChartsTooltipClosed$
.pipe(
startWith(null),
switchMap(() =>
this._highChartsTooltipDataChanged$.asObservable().pipe(take(1)),
),
takeUntil(this._destroy$),
)
.subscribe((event: DtChartTooltipEvent) => {
this._highChartsTooltipOpened$.next(event);
});
const tooltipOpened$ = this._highChartsTooltipOpened$.pipe(
map(event => new TooltipState(TooltipStateType.OPENED, event)),
);
const tooltipClosed$ = this._highChartsTooltipOpened$.pipe(
// `switchMap` to close is used to last only for one cycle of
// open and closing the tooltip.
switchMap(() => this._highChartsTooltipClosed$.pipe(take(1))),
mapTo(new TooltipState(TooltipStateType.CLOSED)),
);
const tooltipUpdated$ = this._highChartsTooltipOpened$.pipe(
// use the `switchMap` to create an inner observable that the
// `distinctUntilChanged` restarts after it was closed and opened again.
// Only starts when a tooltip was opened and restarts after it was closed.
switchMap(() =>
this._highChartsTooltipDataChanged$.pipe(
distinctUntilChanged(compareTooltipEventChanged),
),
),
map(event => new TooltipState(TooltipStateType.UPDATED, event)),
);
this._isInViewport$
.pipe(
filter(Boolean),
switchMap(() => merge(tooltipOpened$, tooltipClosed$, tooltipUpdated$)),
withLatestFrom(this._plotBackground$),
takeUntil(this._destroy$),
)
.subscribe(([state, plotBackground]) => {
this._ngZone.run(() => {
const tooltip = this._tooltip.first;
if (!isDefined(tooltip) || !isDefined(plotBackground)) {
return;
}
const plotBackgroundInfo = getPlotBackgroundInfo(plotBackground!);
switch (state.status) {
case TooltipStateType.CLOSED:
tooltip._dismiss();
this.tooltipOpenChange.emit(false);
break;
case TooltipStateType.OPENED:
tooltip._createOverlay(
state.event!.data,
this,
plotBackgroundInfo,
);
this.tooltipOpenChange.emit(true);
break;
case TooltipStateType.UPDATED:
tooltip._updateOverlayContext(
state.event!.data,
this,
plotBackgroundInfo,
);
this.tooltipDataChange.emit();
break;
}
});
});
}
private _createHighchartsChart(): 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),
);
this._chartObject.series.forEach((series, index) => {
addHighchartsEvent(series, 'hide', () => {
if (this._currentSeries) {
this.seriesVisibilityChange.emit({
source: this,
visible: false,
series: this._currentSeries[index],
});
}
});
addHighchartsEvent(series, 'show', () => {
if (this._currentSeries) {
this.seriesVisibilityChange.emit({
source: this,
visible: true,
series: this._currentSeries[index],
});
}
});
});
addHighchartsEvent(this._chartObject, 'redraw', () => {
this._notifyAfterRender();
});
// adds event-listener to highcharts custom event for tooltip closed
addHighchartsEvent(this._chartObject, 'tooltipClosed', () => {
this._highChartsTooltipClosed$.next();
});
// 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) => {
this._highChartsTooltipDataChanged$.next({
data: (event as DtHcTooltipEventPayload).data,
chart: this._chartObject!,
});
});
this._notifyAfterRender();
}
private _notifyAfterRender(): void {
this._ngZone.runOutsideAngular(() => {
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;
}
/** Checks if a heatfield is supported with the chart options if not throw an error */
private _checkHeatfieldSupport(): void {
if (
this.options &&
this.options.xAxis &&
this.options.xAxis[0] &&
this.options.xAxis[0].categories
) {
throw getDtHeatfieldUnsupportedChartError();
}
}
/** 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(): void {
if (this._chartObject) {
this._chartObject.destroy();
}
this._createHighchartsChart();
this.updated.emit();
}
private _updateColorOptions(): void {
if (this._config.shouldUpdateColors) {
this._highchartsOptions = applyHighchartsColorOptions(
this._highchartsOptions,
this._theme,
);
}
}
}