-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathplotly-renderer.ts
252 lines (218 loc) · 6.82 KB
/
plotly-renderer.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { Widget } from "@lumino/widgets";
import { Message } from "@lumino/messaging";
import { IRenderMime } from "@jupyterlab/rendermime-interfaces";
import type PlotlyType from "plotly.js/dist/plotly";
import "../style/index.css";
/**
* The CSS class to add to the Plotly Widget.
*/
const CSS_CLASS = "jp-RenderedPlotly";
/**
* The CSS class for a Plotly icon.
*/
const CSS_ICON_CLASS = "jp-MaterialIcon jp-PlotlyIcon";
/**
* The MIME type for Plotly.
* The version of this follows the major version of Plotly.
*/
export const MIME_TYPE = "application/vnd.plotly.v1+json";
interface IPlotlySpec {
data: PlotlyType.Data;
layout: PlotlyType.Layout;
frames?: PlotlyType.Frame[];
}
export class RenderedPlotly extends Widget implements IRenderMime.IRenderer {
/**
* Create a new widget for rendering Plotly.
*/
constructor(options: IRenderMime.IRendererOptions) {
super();
this.addClass(CSS_CLASS);
this._mimeType = options.mimeType;
// Create image element
this._img_el = <HTMLImageElement>document.createElement("img");
this._img_el.className = "plot-img";
this.node.appendChild(this._img_el);
// Install image hover callback
this._img_el.addEventListener("mouseenter", (event) => {
this.createGraph(this._model);
});
}
/**
* Render Plotly into this widget's node.
*/
renderModel(model: IRenderMime.IMimeModel): Promise<void> {
if (this.hasGraphElement()) {
// We already have a graph, don't overwrite it
return Promise.resolve();
}
// Save off reference to model so that we can regenerate the plot later
this._model = model;
// Check for PNG data in mime bundle
const png_data = <string>model.data["image/png"];
if (png_data !== undefined && png_data !== null) {
// We have PNG data, use it
this.updateImage(png_data);
return Promise.resolve();
} else {
// Create a new graph
return this.createGraph(model);
}
}
private hasGraphElement() {
// Check for the presence of the .plot-container element that plotly.js
// places at the top of the figure structure
return this.node.querySelector(".plot-container") !== null;
}
private updateImage(png_data: string) {
this.hideGraph();
this._img_el.src = "data:image/png;base64," + <string>png_data;
this.showImage();
}
private hideGraph() {
// Hide the graph if there is one
let el = <HTMLDivElement>this.node.querySelector(".plot-container");
if (el !== null && el !== undefined) {
el.style.display = "none";
}
}
private showGraph() {
// Show the graph if there is one
let el = <HTMLDivElement>this.node.querySelector(".plot-container");
if (el !== null && el !== undefined) {
el.style.display = "block";
}
}
private hideImage() {
// Hide the image element
let el = <HTMLImageElement>this.node.querySelector(".plot-img");
if (el !== null && el !== undefined) {
el.style.display = "none";
}
}
private showImage() {
// Show the image element
let el = <HTMLImageElement>this.node.querySelector(".plot-img");
if (el !== null && el !== undefined) {
el.style.display = "block";
}
}
private createGraph(model: IRenderMime.IMimeModel): Promise<void> {
const { data, layout, frames, config } = model.data[this._mimeType] as
| any
| IPlotlySpec;
if (!layout.height) {
layout.height = 360;
}
// Load plotly asynchronously
const loadPlotly = async (): Promise<void> => {
if (RenderedPlotly.Plotly === null) {
RenderedPlotly.Plotly = await import("plotly.js/dist/plotly");
RenderedPlotly._resolveLoadingPlotly();
}
return RenderedPlotly.loadingPlotly;
};
return loadPlotly()
.then(() => RenderedPlotly.Plotly!.react(this.node, data, layout, config))
.then((plot) => {
this.showGraph();
this.hideImage();
this.update();
if (frames) {
RenderedPlotly.Plotly!.addFrames(this.node, frames);
}
if (this.node.offsetWidth > 0 && this.node.offsetHeight > 0) {
RenderedPlotly.Plotly!.toImage(plot, {
format: "png",
width: this.node.offsetWidth,
height: this.node.offsetHeight,
}).then((url: string) => {
const imageData = url.split(",")[1];
if (model.data["image/png"] !== imageData) {
model.setData({
data: {
...model.data,
"image/png": imageData,
},
});
}
});
}
// Handle webgl context lost events
(<PlotlyType.PlotlyHTMLElement>this.node).on(
"plotly_webglcontextlost",
() => {
const png_data = <string>model.data["image/png"];
if (png_data !== undefined && png_data !== null) {
// We have PNG data, use it
this.updateImage(png_data);
return Promise.resolve();
}
}
);
});
}
/**
* A message handler invoked on an `'after-show'` message.
*/
protected onAfterShow(msg: Message): void {
this.update();
}
/**
* A message handler invoked on a `'resize'` message.
*/
protected onResize(msg: Widget.ResizeMessage): void {
this.update();
}
/**
* A message handler invoked on an `'update-request'` message.
*/
protected onUpdateRequest(msg: Message): void {
if (RenderedPlotly.Plotly && this.isVisible && this.hasGraphElement()) {
RenderedPlotly.Plotly.redraw(this.node).then(() => {
RenderedPlotly.Plotly!.Plots.resize(this.node);
});
}
}
private _mimeType: string;
private _img_el: HTMLImageElement;
private _model: IRenderMime.IMimeModel;
private static Plotly: typeof PlotlyType | null = null;
private static _resolveLoadingPlotly: () => void;
private static loadingPlotly = new Promise<void>((resolve) => {
RenderedPlotly._resolveLoadingPlotly = resolve;
});
}
/**
* A mime renderer factory for Plotly data.
*/
export const rendererFactory: IRenderMime.IRendererFactory = {
safe: true,
mimeTypes: [MIME_TYPE],
createRenderer: (options) => new RenderedPlotly(options),
};
const extensions: IRenderMime.IExtension | IRenderMime.IExtension[] = [
{
id: "@jupyterlab/plotly-extension:factory",
rendererFactory,
rank: 0,
dataType: "json",
fileTypes: [
{
name: "plotly",
mimeTypes: [MIME_TYPE],
extensions: [".plotly", ".plotly.json"],
iconClass: CSS_ICON_CLASS,
},
],
documentWidgetFactoryOptions: {
name: "Plotly",
primaryFileType: "plotly",
fileTypes: ["plotly", "json"],
defaultFor: ["plotly"],
},
},
];
export default extensions;