Skip to content

Commit ac80b50

Browse files
committed
Send plots to client as SVG using svglite
1 parent e9ee538 commit ac80b50

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/webr_kernel.ts

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { IKernel } from '@jupyterlite/kernel';
33
import { ISignal, Signal } from '@lumino/signaling';
44
import { v4 as uuid } from 'uuid';
55
import { WebR } from '@georgestagg/webr';
6-
import { RObjData } from '@georgestagg/webr/dist/webR/robj';
6+
import { RObjData, RInteger } from '@georgestagg/webr/dist/webR/robj';
77

88
export namespace WebRKernel {
99
export interface IOptions extends IKernel.IOptions {}
@@ -37,6 +37,7 @@ export class WebRKernel implements IKernel {
3737
this.#webR.init(),
3838
this.#webR.installPackages(['svglite']),
3939
this.#webR.evalRCode('library(svglite)'),
40+
this.#webR.evalRCode('options(device=function(...){ pdf(...); dev.control("enable") })'),
4041
].reduce((p, x) => p.then(() => x), Promise.resolve());
4142
}
4243

@@ -121,6 +122,33 @@ export class WebRKernel implements IKernel {
121122
}
122123
}
123124
});
125+
126+
const dev = (await this.#webR.evalRCode('dev.cur()')).result as RInteger;
127+
const devNumber = await dev.toNumber();
128+
if (devNumber && devNumber > 1) {
129+
// A non-null graphics device is currently being used, let's copy it
130+
await this.#webR.evalRCode(`
131+
try({
132+
dev.copy(function(...) {
133+
svglite(width = 6.25, height = 5, ...)
134+
}, "/tmp/_webRplots.svg")
135+
dev.off()
136+
}, silent=TRUE)
137+
`);
138+
const plotData = await this.#webR.getFileData('/tmp/_webRplots.svg');
139+
console.log(plotData);
140+
this.sendExecuteResult(msg, {
141+
execution_count: this.#executionCounter,
142+
data: {
143+
'image/svg+xml': new TextDecoder().decode(plotData),
144+
},
145+
metadata: {
146+
'image/svg+xml': {
147+
isolated: true,
148+
},
149+
},
150+
});
151+
}
124152
if (status === 'ok') {
125153
this.sendExecuteReply(msg, {
126154
status: status,

0 commit comments

Comments
 (0)