forked from Joeyonng/react-jupyter-notebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSource.js
executable file
·248 lines (227 loc) · 7.22 KB
/
Source.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
import React, { useCallback, useState, useMemo } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Timer from './Timer';
import RunBtn from './RunBtn';
import MessengerProxy from './MessengerProxy.js';
import './scss/Source.scss';
/* Code-cell Styling */
import TextEditor from './TextEditor';
import { languages } from 'prismjs/components/prism-core';
/* Markdown Styling */
import 'katex/dist/katex.min.css';
import RemarkGFM from 'remark-gfm';
import RemarkMath from 'remark-math';
import RehypeKatex from 'rehype-katex';
import ReactMarkdown from 'react-markdown';
function Source(props) {
// Parse cell
const { cellIndex } = props;
const cell = useSelector((state) => state.notebook.data.cells[cellIndex]);
const { cell_type: cellType, metadata, source } = cell;
const { jupyter } = metadata;
// Hooks
const dispatch = useDispatch();
const [codeStatus, setCodeStatus] = useState(-1);
const [showMarkdown, setShowMarkdown] = useState(
source.length > 0 && cellType === 'markdown' ? true : false
);
// Prep the messenger
const kernelMessenger = useMemo(() => new MessengerProxy(), []);
function toggleLang() {
// Stop any on-going execution
let signalStatus = true;
if (codeStatus > 0) signalStatus = kernelMessenger.signalKernel(2);
if (signalStatus) {
setCodeStatus(-1);
updateCell({
output: [],
cell_type: cellType === 'code' ? 'markdown' : 'code',
});
}
}
function preProcessMarkdown(text) {
const fixMath = (text) => {
// '$$' has to be in a separate new line to be rendered as a block math equation.
const re = /\n?\s*\$\$\s*\n?/g;
return text.replaceAll(re, '\n$$$\n');
};
const trimWhitespace = (text) => {
// Whitespace on the beginning of lines must be removed for HTML
let res = '',
lines = text.split('\n');
for (let line of lines) {
res += line.trim() + '\n';
}
return res;
};
let res = text;
const pipeline = [fixMath, trimWhitespace];
pipeline.forEach((pipe) => (res = pipe(res)));
return res;
}
// Memoized runner functions
// Functions can be passed into children, so these prevent needless rerenders
const updateCell = useCallback(
(newCell) => {
dispatch({
type: 'notebook/updateCell',
payload: { index: cellIndex, cell: newCell },
});
},
[dispatch, cellIndex]
);
const parseResponse = useCallback(
(msg) => {
// Check is used to prevent running code & change of cell type race condition
if (cellType !== 'markdown') {
// Messages expected (in order of occurrence)
const msgType = msg.header.msg_type,
msgContent = msg.content;
switch (msgType) {
case 'status':
// Kernel status (usually busy or idle -> first and last messages)
let kernelBusy = msgContent.execution_state === 'busy';
if (kernelBusy) {
// Clear the output only when we get response from the kernel
updateCell({ outputs: [] });
setCodeStatus(2);
} else {
// End of output
setCodeStatus(0);
}
break;
case 'execute_input':
// Post-run execution count (usually second message)
updateCell({ execution_count: msgContent.execution_count });
break;
case 'error':
setCodeStatus(-2);
// Fall through
case 'stream':
case 'display_data':
case 'execute_result':
// Execution Results - add to outputs array (third to second last message)
const output = {
...msgContent,
output_type: msgType,
};
dispatch({
type: 'notebook/addOutput',
payload: { index: cellIndex, output },
});
break;
case 'shutdown_reply':
updateCell({ output: [] });
setCodeStatus(-2);
break;
default:
}
}
},
[cellIndex, cellType, dispatch, updateCell]
);
const run = useCallback(
(code) => {
if (codeStatus <= 0) {
// Reset source but keep output for now - will be reset later
updateCell({ execution_count: null });
kernelMessenger
.runCode(code, parseResponse)
.then(() => {})
.catch((e) => console.error(e));
} else {
// Stop execution
kernelMessenger
.signalKernel(2)
.then(() => setCodeStatus(-2))
.catch(() => {});
}
},
[codeStatus, kernelMessenger, parseResponse, updateCell]
);
const runCallback = useCallback(() => {
// Set run-callback and execution count based on cell-type
if (cellType === 'code') {
run(source);
} else {
setShowMarkdown(true);
}
}, [cellType, run, source]);
const updateContent = useCallback(
(code) => updateCell({ source: code.split(/^/m) }),
[updateCell]
);
const keyCallback = useCallback(
(e) => {
// If shift-enter - call the callback
if (e.shiftKey && e.which === 13) {
runCallback();
e.preventDefault();
e.stopPropagation();
}
},
[runCallback]
);
// Build either editor or rendered markdown view
let cellContent;
const shown = jupyter && jupyter.source_hidden ? 0 : 1,
mergedCode = source.join(''),
{ execution_count: executionCount } = cell,
{ editable } = metadata;
if (!showMarkdown) {
cellContent = (
<div className="cell-content source-code">
{/* Actual code cell */}
<TextEditor
className="source-code-main"
defaultValue={mergedCode}
onChange={updateContent}
// onKeyDown={keyCallback}
disabled={!(editable === undefined || editable) ? true : false}
highlightType={cellType === 'code' ? languages.py : undefined}
/>
{/* Run time and Language switcher */}
<div className="cell-status">
<Timer status={codeStatus} />
<button className="block-btn cell-type-btn" onClick={toggleLang}>
{cellType}
</button>
</div>
</div>
);
} else {
const newSource = preProcessMarkdown(mergedCode);
const reenableEditing = () => setShowMarkdown(false);
cellContent = (
<div
className="cell-content source-markdown"
onDoubleClick={() => reenableEditing()}
>
<ReactMarkdown
remarkPlugins={[RemarkGFM, RemarkMath]}
rehypePlugins={[RehypeKatex]}
>
{newSource}
</ReactMarkdown>
</div>
);
}
// TODO: Look into TextEditor & RunBtn for un-needed renders
return shown === 0 ? (
<div className="source-hidden" />
) : (
<div className="cell-row" tabIndex="0" onKeyDown={keyCallback}>
{/* Left side of the code editor */}
<RunBtn
codeStatus={codeStatus}
runCallback={runCallback}
showMarkdown={showMarkdown}
isMarkdownCell={cellType === 'markdown'}
executionCount={executionCount !== null ? executionCount : ' '}
/>
{/* Code itself (or markdown) */}
{cellContent}
</div>
);
}
export default React.memo(Source);