forked from Joeyonng/react-jupyter-notebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JupyterViewer.js
executable file
·102 lines (89 loc) · 2.62 KB
/
JupyterViewer.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
import React, { useCallback, useEffect } from 'react';
import { Provider, useDispatch, useSelector } from 'react-redux';
import store from './redux/store';
import PropTypes from 'prop-types';
import Block from './Block';
import BlockBtn from './BlockBtn';
import { genCellName, addCell } from './Helpers';
import MessengerProxy from './MessengerProxy';
import './scss/JupyterViewer.scss';
function JupyterViewer(props) {
const { rawIpynb, messenger } = props;
const dispatch = useDispatch();
const cells = useSelector((state) => state.notebook.data.cells);
const clickCellIndex = useSelector((state) => state.notebook.clickCellIndex);
// Update clicked cell
const updateCellIndex = useCallback(
(i) => {
dispatch({
type: 'notebook/setClickedCell',
payload: i,
});
},
[dispatch]
);
// Update cells (from raw)
useEffect(() => {
const loadCells = (ipynb) => {
return { ...ipynb, cells: ipynb.cells.map((cell) => genCellName(cell)) };
};
const processed = loadCells(rawIpynb);
// Reset cell index
updateCellIndex(-1);
// Load the store with the needed props
dispatch({ type: 'notebook/setData', payload: processed });
}, [dispatch, updateCellIndex, rawIpynb]);
// Update Kernel Messenger
useEffect(() => {
// Initialize the singleton
const kernelMessenger = new MessengerProxy();
kernelMessenger.messenger = messenger;
}, [messenger]);
return (
<div className="jupyter-viewer">
{cells.map((cell, index) => {
return (
<div
key={cell.metadata.name}
className="block"
onMouseDown={() => {
if (clickCellIndex.current !== index) updateCellIndex(index);
}}
>
{!('cell_type' in cell) ? null : <Block cellIndex={index} />}
</div>
);
})}
<div className="add-buttons">
<BlockBtn
text="+ Code"
callback={() => addCell(dispatch, cells.length, 'code')}
/>
<BlockBtn
text="+ Markdown"
callback={() => addCell(dispatch, cells.length, 'markdown')}
/>
</div>
</div>
);
}
function getIpynb(){
/*
Returns the jupyter notebook data from the store
*/
const state = store.getState();
return state.notebook.data;
}
const ReduxWrap = React.memo((props) => (
<Provider store={store}>
<JupyterViewer {...props} />{' '}
</Provider>
));
JupyterViewer.defaultProps = {
rawIpynb: { cells: [] },
};
JupyterViewer.propTypes = {
rawIpynb: PropTypes.object,
messenger: PropTypes.object,
};
export { ReduxWrap as JupyterViewer, getIpynb };