-
-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathplotly.component.ts
More file actions
305 lines (261 loc) · 9.1 KB
/
plotly.component.ts
File metadata and controls
305 lines (261 loc) · 9.1 KB
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
/* eslint-disable @angular-eslint/no-conflicting-lifecycle */
import {
Component,
ElementRef,
OnDestroy,
OnChanges,
OnInit,
SimpleChange,
SimpleChanges,
ViewChild,
DoCheck,
IterableDiffer,
IterableDiffers,
KeyValueDiffer,
KeyValueDiffers,
input,
output,
OutputEmitterRef,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { PlotlyService } from './plotly.service';
import { Plotly } from './plotly.interface';
// @dynamic
@Component({
selector: 'plotly-plot',
standalone: true,
imports: [CommonModule],
template: `<div #plot [attr.id]="divId()" [ngClass]="getClassName()" [ngStyle]="style()">
<ng-content></ng-content>
</div>`,
providers: [PlotlyService],
})
export class PlotlyComponent implements OnInit, OnChanges, OnDestroy, DoCheck {
protected defaultClassName = 'js-plotly-plot';
public plotlyInstance?: Plotly.PlotlyHTMLElement;
public resizeHandler?: (instance: Plotly.PlotlyHTMLElement) => void;
public layoutDiffer?: KeyValueDiffer<string, any>;
public dataDiffer?: IterableDiffer<Plotly.Data>;
@ViewChild('plot', { static: true }) plotEl!: ElementRef;
data = input<Plotly.Data[]>();
layout = input<Partial<Plotly.Layout>>();
config = input<Partial<Plotly.Config>>();
frames = input<Partial<Plotly.Config>[]>();
style = input<{ [key: string]: string }>();
divId = input<string>();
revision = input(0);
className = input<string | string[]>();
debug = input(false);
useResizeHandler = input(false);
updateOnLayoutChange = input(true);
updateOnDataChange = input(true);
updateOnlyWithRevision = input(false);
initialized = output<Plotly.Figure>();
update = output<Plotly.Figure>();
purge = output<Plotly.Figure>();
error = output<Error>();
afterExport = output();
afterPlot = output();
animated = output();
animatingFrame = output();
animationInterrupted = output();
autoSize = output();
beforeExport = output();
beforeHover = output();
buttonClicked = output();
/**
* @deprecated DEPRECATED: Reconsider using `(plotlyClick)` instead of `(click)` to avoid event conflict. Please check https://github.com/plotly/angular-plotly.js#FAQ
*/
click = output();
plotlyClick = output();
clickAnnotation = output();
deselect = output();
doubleClick = output();
framework = output();
hover = output();
legendClick = output();
legendDoubleClick = output();
/**
* @deprecated DEPRECATED: Event react is not list as an plotly.js event
*/
react = output();
relayout = output();
relayouting = output();
restyle = output();
redraw = output();
selected = output();
selecting = output();
sliderChange = output();
sliderEnd = output();
sliderStart = output();
sunburstclick = output();
transitioning = output();
transitionInterrupted = output();
unhover = output();
/**
* @deprecated DEPRECATED: Event treemapclick is not list as an plotly.js event
*/
treemapclick = output();
webglcontextlost = output();
public eventNames = ['afterExport', 'afterPlot', 'animated', 'animatingFrame', 'animationInterrupted', 'autoSize',
'beforeExport', 'beforeHover', 'buttonClicked', 'clickAnnotation', 'deselect', 'doubleClick', 'framework', 'hover',
'legendClick', 'legendDoubleClick', 'react', 'relayout', 'relayouting', 'restyle', 'redraw', 'selected', 'selecting', 'sliderChange',
'sliderEnd', 'sliderStart', 'sunburstclick', 'transitioning', 'transitionInterrupted', 'unhover', 'treemapclick', 'webglcontextlost'];
constructor(
public plotly: PlotlyService,
public iterableDiffers: IterableDiffers,
public keyValueDiffers: KeyValueDiffers,
) { }
ngOnInit(): void {
this.createPlot().then(() => {
const figure = this.createFigure();
this.initialized.emit(figure);
});
}
ngOnDestroy(): void {
if (typeof this.resizeHandler === 'function') {
this.getWindow().removeEventListener('resize', this.resizeHandler as any);
this.resizeHandler = undefined;
}
if (this.plotlyInstance) {
const figure = this.createFigure();
this.purge.emit(figure);
PlotlyService.remove(this.plotlyInstance);
}
}
ngOnChanges(changes: SimpleChanges): void {
let shouldUpdate = false;
const revision: SimpleChange = changes['revision'];
if (revision && !revision.isFirstChange()) {
shouldUpdate = true;
}
const debug: SimpleChange = changes['debug'];
if (debug && !debug.isFirstChange()) {
shouldUpdate = true;
}
if (shouldUpdate) {
this.updatePlot();
}
this.updateWindowResizeHandler();
}
ngDoCheck(): boolean | void {
if (this.updateOnlyWithRevision()) {
return false;
}
let shouldUpdate = false;
if (this.updateOnLayoutChange()) {
if (this.layoutDiffer) {
const layoutHasDiff = this.layoutDiffer.diff(this.layout()!);
if (layoutHasDiff) {
shouldUpdate = true;
}
} else if (this.layout()) {
this.layoutDiffer = this.keyValueDiffers.find(this.layout()).create();
} else {
this.layoutDiffer = undefined;
}
}
if (this.updateOnDataChange()) {
if (this.dataDiffer) {
const dataHasDiff = this.dataDiffer.diff(this.data());
if (dataHasDiff) {
shouldUpdate = true;
}
} else if (Array.isArray(this.data())) {
this.dataDiffer = this.iterableDiffers.find(this.data()).create(this.dataDifferTrackBy);
} else {
this.dataDiffer = undefined;
}
}
if (shouldUpdate && this.plotlyInstance) {
this.updatePlot();
}
}
getData(): Plotly.Data[] {
return this.data() ?? [];
}
getWindow(): any {
return window;
}
getClassName(): string {
let classes = [this.defaultClassName];
const className = this.className();
if (Array.isArray(className)) {
classes = classes.concat(className);
} else if (className) {
classes.push(className);
}
return classes.join(' ');
}
createPlot(): Promise<void> {
return this.plotly.newPlot(
this.plotEl.nativeElement,
this.getData(),
this.layout(),
this.config(),
this.frames()
).then(plotlyInstance => {
this.plotlyInstance = plotlyInstance;
this.getWindow().gd = this.debug ? plotlyInstance : undefined;
this.eventNames.forEach(name => {
const eventName = `plotly_${name.toLowerCase()}`;
const event = (this as any)[name] as OutputEmitterRef<any>;
plotlyInstance.on(eventName, (data: any) => event.emit(data));
});
plotlyInstance.on('plotly_click', (data: any) => {
this.plotlyClick.emit(data);
});
this.updateWindowResizeHandler();
}, err => {
console.error('Error while plotting:', err);
this.error.emit(err);
});
}
createFigure(): Plotly.Figure {
const p: any = this.plotlyInstance;
const figure: Plotly.Figure = {
data: p.data,
layout: p.layout,
frames: p._transitionData ? p._transitionData._frames : null
};
return figure;
}
updatePlot(): Promise<any> {
if (!this.plotlyInstance) {
const error = new Error(`Plotly component wasn't initialized`);
this.error.emit(error);
throw error;
}
const layout = { ...this.layout() };
return this.plotly.update(
this.plotlyInstance,
this.getData(),
layout,
this.config(),
this.frames()
).then(() => {
const figure = this.createFigure();
this.update.emit(figure);
}, err => {
console.error('Error while updating plot:', err);
this.error.emit(err);
});
}
updateWindowResizeHandler(): void {
if (this.useResizeHandler()) {
if (this.resizeHandler === undefined) {
this.resizeHandler = () => this.plotly.resize(this.plotlyInstance!);
this.getWindow().addEventListener('resize', this.resizeHandler as any);
}
} else {
if (typeof this.resizeHandler === 'function') {
this.getWindow().removeEventListener('resize', this.resizeHandler as any);
this.resizeHandler = undefined;
}
}
}
dataDifferTrackBy(_: number, item: any): unknown {
const obj = Object.assign({}, item, { uid: '' });
return JSON.stringify(obj);
}
}