All files / Editor Editor.js

57.69% Statements 15/26
50% Branches 4/8
20% Functions 2/10
57.69% Lines 15/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                        1x   1x 1x 1x 1x   1x 1x       1x     1x       1x       1x       1x                                                 1x                       1x                   1x                  
import React, { useState, useRef } from 'react';
import PropTypes from 'prop-types';
 
import Loading from '../Loading';
 
import { monaco } from '../utils';
import { useMount, useUpdate } from '../utils/hooks';
 
import config from '../config';
import styles from './styles';
 
const Editor =
  ({ value, language, theme, options, editorDidMount, line, loading }) =>
{
  const [isLoading, setIsLoading] = useState(true);
  const editorRef = useRef();
  const monacoRef = useRef();
  const containerRef = useRef();
 
  useMount(_ => {
    monaco
      .init()
      .then(monaco => (monacoRef.current = monaco) && createEditor());
 
    return removeEditor;
  });
 
  useUpdate(_ => {
    editorRef.current.setValue(value);
  }, [value]);
 
  useUpdate(_ => {
    monacoRef.current.editor.setModelLanguage(editorRef.current.getModel(), language);
  }, [language]);
 
  useUpdate(_ => {
    editorRef.current.setScrollPosition({ scrollTop: line });
  }, [line]);
 
  useUpdate(_ => {
    monacoRef.current.editor.setTheme(theme);
  }, [theme]);
 
  function createEditor() {
    editorRef.current = monacoRef.current.editor.create(containerRef.current, {
      value,
      language,
      automaticLayout: true,
      ...options,
    });
 
    editorDidMount &&
    editorDidMount(editorRef.current.getValue.bind(editorRef.current), editorRef.current);
 
    monacoRef.current.editor.defineTheme('dark', config.theme['night-dark']);
    monacoRef.current.editor.setTheme(theme);
 
    setIsLoading(false);
  }
 
  function removeEditor() {
    editorRef.current.dispose();
  }
 
  return (
    <section style={styles.wrapper}>
      {isLoading && <Loading content={loading} />}
      <div
        ref={containerRef}
        label="monaco-editor"
        style={{ ...styles.fullWidth, ...(isLoading && styles.hide) }}
      />
    </section>
  );
};
 
Editor.propTypes = {
  value: PropTypes.string,
  language: PropTypes.string,
  options: PropTypes.object,
  editorDidMount: PropTypes.func,
  theme: PropTypes.string,
  line: PropTypes.number,
  loading: PropTypes.oneOfType([PropTypes.element, PropTypes.string]),
};
 
Editor.defaultProps = {
  language: 'javascript',
  value: '',
  options: {},
  editorDidMount: _ => {},
  loading: 'Loading...',
};
 
export default Editor;