chart.component.ts 6 KB
Newer Older
Léonard Treille's avatar
Léonard Treille committed
1
2
3
4
5
6
7
8
9
10
11
12
13
import { Component, OnInit, ElementRef, Input, OnChanges, SimpleChanges, Optional, Inject, OnDestroy, HostListener, ViewChild, AfterViewInit, HostBinding } from '@angular/core';
import * as d3 from 'd3';
import { Subject, fromEvent, merge } from 'rxjs';
import { debounceTime, takeUntil, tap } from 'rxjs/operators';
import { Dataset, ChartType, ChartContext, Point } from './chart.model';

@Component({
	selector: 'app-chart',
	template: `
		<div class="chart-tooltip" #tooltip *ngIf="tooltipVisible && !tooltipDisabled" [ngStyle]="{'top.px': tooltipTopPosition, 'left.px': tooltipLeftPosition}" [class.fixed]="tooltipFixed">
			<span class="x">{{ tooltipXValue }}</span><br>
			<span class="y">{{ tooltipYValue }}</span>
		</div>
Léonard Treille's avatar
Léonard Treille committed
14
15
16
		<div class="loader-wrapper">
			<mat-spinner mode="indeterminate" diameter="64" *ngIf="dataset.options.ghost && !dataset.options.unavailable"></mat-spinner>
		</div>
17
18
		<p class="empty-message" *ngIf="dataset?.options?.empty">Aucune donnée</p>
		<p class="unavailable-message" *ngIf="dataset?.options?.unavailable">Données non disponibles</p>
Léonard Treille's avatar
Léonard Treille committed
19
20
	`,
	styles: [
Léonard Treille's avatar
Léonard Treille committed
21
22
		':host {display: block; position: relative;}',
		'.loader-wrapper { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }'
Léonard Treille's avatar
Léonard Treille committed
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
	]
})
export class ChartComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {

	@Input() dataset: Dataset;
	@Input() type = 'scatter-graph';
	@Input() tooltipDisabled = false;
	@Input() tooltipOnClick = false;
	@Input() tooltipOnHover = false;

	tooltipXValue: string;
	tooltipYValue: string;
	tooltipTopPosition: number;
	tooltipLeftPosition: number;
	tooltipVisible = false;
	tooltipFixed = false;

	@ViewChild('tooltip') tooltip: ElementRef<HTMLElement>;

	private chart: d3.Selection;
	private chartTypes: ChartType[];
	private unsubscriber = new Subject<void>();
	private changes$ = new Subject<void>();
	private _context: ChartContext;

	constructor(
		private host: ElementRef,
		@Optional() @Inject('ChartType') chartTypes: ChartType[]
	) {
		this.chartTypes = chartTypes || [];
		merge(
			fromEvent(window, 'resize').pipe(
				debounceTime(300),
				tap(() => {
					this._context = this.context;
				})
			),
			this.changes$
		).pipe(takeUntil(this.unsubscriber)).subscribe(() => {
			if (this.chart) {
				this.update();
			}
		});
	}
	ngAfterViewInit(): void {
		if (!this.chart) {
			this.initChart();
		}
		// For unknown reasons, the width and height may be changed, so we avoid this behavior by freezing the context.
		this._context = this.context;
		this.changes$.next();
	}

	ngOnInit(): void { }

	ngOnDestroy(): void {
		this.unsubscriber.next();
		this.unsubscriber.complete();
	}

	ngOnChanges(changes: SimpleChanges) {
		if (changes.type && changes.type.previousValue) {
			const previousType = this.chartTypes.find(t => t.type === changes.type.previousValue);
			const width = this.width;
			const height = this.height;
			previousType.destroy({ height, width, chart: this.chart });
		}
		if (changes.dataset) {
			this.changes$.next();
		}
	}

	update() {
		this.chartType.udpate(this.dataset, this.context);
	}

	private get context(): ChartContext {
		if (this._context) {
			return this._context;
		}
		return { height: this.height, width: this.width, chart: this.chart };
	}

	private get width(): number {
		return (this.host.nativeElement as HTMLElement).getBoundingClientRect().width;
	}
	private get height(): number {
		return (this.host.nativeElement as HTMLElement).getBoundingClientRect().height;
	}

	private initChart() {
		this.chart = d3.select(this.host.nativeElement)
			.append('svg')
			.attr('width', '100%')
			.attr('height', '100%');
	}

	private get chartType(): ChartType {
		return this.chartTypes.find(t => t.type === this.type);
	}

	@HostListener('click', ['$event'])
	onClick(event: MouseEvent) {
		if (this.tooltipOnClick && (event.target as SVGElement).classList.contains('clickable')) {
			this.tooltipFixed = true;
			this.tooltipVisible = true;
			const rect = (event.target as SVGElement).getBoundingClientRect();
			this.tooltipTopPosition = rect.top;
			this.tooltipLeftPosition = rect.left + rect.width / 2;
			const point: Point = JSON.parse((event.target as SVGElement).getAttribute('data-point'));
			const xFormatter = this.dataset.axis && this.dataset.axis.x && this.dataset.axis.x.tooltipFormatter || ((value, _point, dataset) => value);
			const yFormatter = this.dataset.axis && this.dataset.axis.y && this.dataset.axis.y.tooltipFormatter || ((value, _point, dataset) => value);
			this.tooltipXValue = xFormatter(point.x, point, this.dataset);
			this.tooltipYValue = yFormatter(point.y, point, this.dataset);
		}
		else {
			this.tooltipVisible = false;
		}
	}

	@HostListener('mousemove', ['$event'])
	onMouseMove(event: MouseEvent) {
		if (!this.tooltipOnHover) {
			return;
		}
		if (this.chart) {
			this.chartType.globalMouseUpdate(this.dataset, this.context, event);
		}
		if (!this.tooltipDisabled && this.tooltip && this.chartType.scaleX && this.chartType.scaleY) {
			const rect = this.tooltip.nativeElement.getBoundingClientRect();
			const padding = this.chartType.padding;
			let x = event.offsetX + padding;
			let y = event.offsetY + padding;
			if (event.offsetX + rect.width + padding * 2 > this.width) {
				x = event.offsetX - rect.width - padding;
			}
			if (event.offsetY + rect.height + padding * 2 > this.height) {
				y = event.offsetY - rect.height - padding;
			}
			this.tooltipTopPosition = y;
			this.tooltipLeftPosition = x;
			const xFormatter = this.dataset.axis && this.dataset.axis.x && this.dataset.axis.x.tooltipFormatter || ((value) => value);
			const yFormatter = this.dataset.axis && this.dataset.axis.y && this.dataset.axis.y.tooltipFormatter || ((value) => value);
			this.tooltipXValue = xFormatter(this.chartType.scaleX.invert(event.offsetX));
			this.tooltipYValue = yFormatter(this.chartType.scaleY.invert(event.offsetY));
		}
	}

	@HostListener('mouseenter')
	onMouseEnter() {
		if (this.tooltipOnHover) {
			this.tooltipVisible = true;
		}
	}

	@HostListener('mouseleave')
	onMouseLeave() {
		if (this.tooltipOnHover) {
			this.tooltipVisible = false;
		}
	}

}