lbry-desktop/ui/component/viewers/codeViewer.jsx

83 lines
2.2 KiB
React
Raw Normal View History

2018-07-27 02:24:00 +02:00
// @flow
2018-10-15 08:26:46 +02:00
import * as React from 'react';
2018-11-21 22:20:55 +01:00
import { openSnippetMenu, stopContextMenu } from 'util/context-menu';
2018-07-28 22:17:06 +02:00
// Addons
import 'codemirror/addon/selection/mark-selection';
2018-07-28 03:42:35 +02:00
// Syntax mode
import 'codemirror/mode/go/go';
import 'codemirror/mode/jsx/jsx';
import 'codemirror/mode/css/css';
2018-07-28 03:42:35 +02:00
import 'codemirror/mode/xml/xml';
import 'codemirror/mode/php/php';
import 'codemirror/mode/ruby/ruby';
import 'codemirror/mode/clike/clike';
import 'codemirror/mode/shell/shell';
import 'codemirror/mode/python/python';
import 'codemirror/mode/markdown/markdown';
import 'codemirror/mode/javascript/javascript';
2018-07-27 02:24:00 +02:00
type Props = {
2018-07-28 03:42:35 +02:00
theme: string,
value: ?string,
2018-07-28 03:42:35 +02:00
contentType: string,
2018-07-27 02:24:00 +02:00
};
class CodeViewer extends React.PureComponent<Props> {
constructor(props: Props) {
2018-07-27 02:24:00 +02:00
super(props);
this.codeMirror = null;
}
componentDidUpdate(prevProps: Props): * {
if (prevProps.theme === this.props.theme) return;
// This code is duplicated with componentDidMount
const theme = this.props.theme === 'dark' ? 'monokai' : 'default';
this.codeMirror.setOption('theme', theme);
}
2018-07-27 02:24:00 +02:00
componentDidMount() {
2019-03-27 05:40:02 +01:00
const me = this;
const { theme, contentType } = me.props;
2018-07-29 01:48:54 +02:00
// Init CodeMirror
2019-08-13 07:35:13 +02:00
import(
/* webpackChunkName: "codemirror" */
'codemirror/lib/codemirror'
).then(CodeMirror => {
2019-03-27 05:40:02 +01:00
me.codeMirror = CodeMirror.fromTextArea(me.textarea, {
// Auto detect syntax with file contentType
mode: contentType,
// Adaptive theme
2020-01-18 08:13:11 +01:00
theme: theme === 'dark' ? 'monokai' : 'default',
2019-03-27 05:40:02 +01:00
// Hide the cursor
readOnly: true,
// Styled text selection
styleSelectedText: true,
// Additional config opts
dragDrop: false,
lineNumbers: true,
lineWrapping: true,
});
// Add events
me.codeMirror.on('contextmenu', openSnippetMenu);
2018-07-27 02:24:00 +02:00
});
}
2018-10-15 08:26:46 +02:00
textarea: ?HTMLTextAreaElement;
codeMirror: any;
2018-07-27 02:24:00 +02:00
render() {
const { value } = this.props;
return (
2019-08-13 07:35:13 +02:00
<div className="file-render__content" onContextMenu={stopContextMenu}>
2018-10-15 08:26:46 +02:00
<textarea ref={textarea => (this.textarea = textarea)} disabled value={value} />
2018-07-27 02:24:00 +02:00
</div>
);
}
}
export default CodeViewer;