async function output(code, div0, throwOnError) {
function escape(str) {
const escapeRE = /</g;
return str.replace(escapeRE, '<');
}
function appendMIME(content, div) {
for (const mime in content.data) {
switch (mime) {
case 'text/plain': {
const result = content.data['text/plain'];
div.appendChild(html`<pre>${escape(result)}`);
div.value = result;
break;
}
case 'text/html': {
const result = html`<div>${content.data['text/html']}`;
div.appendChild(result);
div.value = result;
break;
}
case 'image/svg+xml': {
const image = html`<img src="data:${mime},${encodeURIComponent(
content.data[mime]
)}">`;
div.appendChild(image);
break;
}
case 'image/png':
case 'image/jpeg': {
const image = html`<img src="data:${mime};base64,${content.data[mime]}">`;
div.appendChild(image);
break;
}
default: {
div.appendChild(
html`<pre style="max-height: 500px; overflow-y: auto;">${escape(
JSON.stringify(content)
)}`
);
div.value = content;
}
}
}
}
const future = session.kernel.requestExecute({ code }, true);
const div = div0 || html``;
let errored;
future.onIOPub = msg => {
console.log(msg);
switch (msg.msg_type) {
case 'execute_input': {
div.value = undefined;
break;
}
case 'execute_result': {
appendMIME(msg.content, div);
break;
}
case 'stream': {
if (msg.content.name === 'stdout') {
div.appendChild(
html`<pre style="max-height: 500px; overflow-y: auto;">${escape(
msg.content.text
)}`
);
div.value = msg.content.text;
} else {
div.appendChild(
html`<pre style="max-height: 500px; overflow-y: auto;">${escape(
JSON.stringify(msg.content)
)}`
);
div.value = msg.content;
}
break;
}
case 'display_data': {
appendMIME(msg.content, div);
break;
}
case 'error': {
if (throwOnError) {
errored = msg.content;
}
// firefox with 75ch drops characters to the next line randomly...
div.appendChild(
html`<pre style="width: 75ch; white-space: pre-wrap; word-break: break-all;">${msg.content.traceback.map(
s => {
return ansi_up.ansi_to_html(s);
}
)}`
);
div.value = msg.content;
// div.appendChild(
// html`<pre style="color:red;">${
// msg.content.ename
// }: ${msg.content.evalue.replace('<', '<')}`
// );
break;
}
default: {
//
// div.value = msg;
}
}
};
await future.done;
if (errored)
throw new Error(
`${errored.ename}: ${errored.evalue}, traceback: ${errored.traceback}`
);
return div;
}