-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathjuniper.js
282 lines (268 loc) · 9.85 KB
/
juniper.js
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
import React, { useEffect } from 'react'
import PropTypes from 'prop-types'
import CodeMirror from '@uiw/react-codemirror'
import { createTheme } from '@uiw/codemirror-themes'
import { tags as t } from '@lezer/highlight'
import { python } from '@codemirror/lang-python'
import { Kernel, ServerConnection } from '@jupyterlab/services'
import { window } from 'browser-monads'
import classes from '../styles/code.module.sass'
const spacyTheme = createTheme({
theme: 'dark',
settings: {
background: 'var(--color-front)',
foreground: 'var(--color-subtle-on-dark)',
caret: 'var(--color-theme-dark)',
selection: 'var(--color-theme-dark)',
selectionMatch: 'var(--color-theme-dark)',
gutterBackground: 'var(--color-front)',
gutterForeground: 'var(--color-subtle-on-dark)',
fontFamily: 'var(--font-code)',
},
styles: [
{ tag: t.comment, color: 'var(--syntax-comment)' },
{ tag: t.variableName, color: 'var(--color-subtle-on-dark)' },
{ tag: [t.string, t.special(t.brace)], color: '#fff' },
{ tag: t.number, color: 'var(--syntax-number)' },
{ tag: t.string, color: 'var(--syntax-selector)' },
{ tag: t.bool, color: 'var(--syntax-keyword)' },
{ tag: t.keyword, color: 'var(--syntax-keyword)' },
{ tag: t.operator, color: 'var(--syntax-operator)' },
],
})
export default class Juniper extends React.Component {
state = {
kernel: null,
renderers: null,
fromStorage: null,
output: null,
code: this.props.children,
}
log(logFunction) {
if (this.props.debug) {
logFunction()
}
}
/**
* Request a binder, e.g. from mybinder.org
* @param {string} repo - Repository name in the format 'user/repo'.
* @param {string} branch - The repository branch, e.g. 'master'.
* @param {string} url - The binder reployment URL, including 'http(s)'.
* @returns {Promise} - Resolved with Binder settings, rejected with Error.
*/
requestBinder(repo, branch, url) {
const binderUrl = `${url}/build/gh/${repo}/${branch}`
this.log(() => console.info('building', { binderUrl }))
return new Promise((resolve, reject) => {
const es = new EventSource(binderUrl)
es.onerror = (err) => {
es.close()
this.log(() => console.error('failed', err))
reject(new Error(err))
}
let phase = null
es.onmessage = ({ data }) => {
const msg = JSON.parse(data)
if (msg.phase && msg.phase !== phase) {
phase = msg.phase.toLowerCase()
this.log(() => console.info(phase === 'ready' ? 'server-ready' : phase))
}
if (msg.phase === 'failed') {
es.close()
reject(new Error(msg))
} else if (msg.phase === 'ready') {
es.close()
const settings = {
baseUrl: msg.url,
wsUrl: `ws${msg.url.slice(4)}`,
token: msg.token,
}
resolve(settings)
}
}
})
}
/**
* Request kernel and estabish a server connection via the JupyerLab service
* @param {object} settings - The server settings.
* @returns {Promise} - A promise that's resolved with the kernel.
*/
requestKernel(settings) {
if (this.props.useStorage) {
const timestamp = new Date().getTime() + this.props.storageExpire * 60 * 1000
const json = JSON.stringify({ settings, timestamp })
window.localStorage.setItem(this.props.storageKey, json)
}
const serverSettings = ServerConnection.makeSettings(settings)
return Kernel.startNew({ type: this.props.kernelType, serverSettings }).then((kernel) => {
this.log(() => console.info('ready'))
return kernel
})
}
/**
* Get a kernel by requesting a binder or from localStorage / user settings
* @returns {Promise}
*/
getKernel() {
if (this.props.useStorage) {
const stored = window.localStorage.getItem(this.props.storageKey)
if (stored) {
this.setState({ fromStorage: true })
const { settings, timestamp } = JSON.parse(stored)
if (timestamp && new Date().getTime() < timestamp) {
return this.requestKernel(settings)
}
window.localStorage.removeItem(this.props.storageKey)
}
}
if (this.props.useBinder) {
return this.requestBinder(this.props.repo, this.props.branch, this.props.url).then(
(settings) => this.requestKernel(settings)
)
}
return this.requestKernel(this.props.serverSettings)
}
/**
* Render the kernel response in a JupyterLab output area
* @param {OutputArea} outputArea - The cell's output area.
* @param {string} code - The code to execute.
*/
async renderResponse(kernel) {
if (this.state.code === null || this.state.code === '') {
this.state.output = 'No code entered'
return
}
const response = kernel.requestExecute({
code: this.state.code,
})
this.state.output = this.props.msgLoading
response.handleMsg = (message) => {
if (message.content && message.content.name === 'stdout') {
this.setState({
output: message.content.text,
})
}
}
}
/**
* Process request to execute the code
* @param {OutputArea} - outputArea - The cell's output area.
* @param {string} code - The code to execute.
*/
runCode() {
this.log(() => console.info('executing'))
if (this.state.kernel) {
if (this.props.isolateCells) {
this.state.kernel
.restart()
.then(() => this.renderResponse(this.state.kernel))
.catch((err) => {
this.log(() => console.error('faileder', err))
this.setState({ kernel: null })
this.setState({ output: this.props.msgError })
})
return
}
this.renderResponse(this.state.kernel)
return
}
this.log(() => console.info('requesting kernel'))
const url = this.props.url.split('//')[1]
const action = !this.state.fromStorage ? 'Launching' : 'Reconnecting to'
this.setState({ output: `${action} Docker container on ${url}...` })
this.getKernel()
.then((kernel) => {
this.setState({ kernel })
this.renderResponse(kernel)
})
.catch((err) => {
this.log(() => console.error('failed', err))
this.setState({ kernel: null })
if (this.props.useStorage) {
this.setState({ fromStorage: false })
window.localStorage.removeItem(this.props.storageKey)
}
this.setState({ output: this.props.msgError })
})
}
render() {
return (
<div className={this.props.classNames.cell}>
{this.state.code && (
<CodeMirror
value={this.state.code}
extensions={[python()]}
theme={spacyTheme}
basicSetup={{
lineNumbers: false,
foldGutter: false,
highlightActiveLine: false,
highlightSelectionMatches: false,
}}
className={classes['juniper-input']}
onChange={(value) => {
this.setState({ code: value })
}}
/>
)}
<button className={this.props.classNames.button} onClick={() => this.runCode()}>
{this.props.msgButton}
</button>
{this.state.output !== null && (
<pre
className={`${this.props.classNames.output} ${classes['juniper-input']} ${classes.wrap}`}
>
{this.state.output}
</pre>
)}
</div>
)
}
}
Juniper.defaultProps = {
children: '',
branch: 'master',
url: 'https://mybinder.org',
serverSettings: {},
kernelType: 'python3',
lang: 'python',
theme: 'default',
isolateCells: true,
useBinder: true,
storageKey: 'juniper',
useStorage: true,
storageExpire: 60,
debug: false,
msgButton: 'run',
msgLoading: 'Loading...',
msgError: 'Connecting failed. Please reload and try again.',
classNames: {
cell: 'juniper-cell',
input: 'juniper-input',
button: 'juniper-button',
output: 'juniper-output',
},
}
Juniper.propTypes = {
children: PropTypes.string,
repo: PropTypes.string.isRequired,
branch: PropTypes.string,
url: PropTypes.string,
serverSettings: PropTypes.object,
kernelType: PropTypes.string,
lang: PropTypes.string,
theme: PropTypes.string,
isolateCells: PropTypes.bool,
useBinder: PropTypes.bool,
useStorage: PropTypes.bool,
storageExpire: PropTypes.number,
msgButton: PropTypes.string,
msgLoading: PropTypes.string,
msgError: PropTypes.string,
classNames: PropTypes.shape({
cell: PropTypes.string,
input: PropTypes.string,
button: PropTypes.string,
output: PropTypes.string,
}),
}