All files CodeMirrorCore.js

100% Statements 7/7
91.67% Branches 11/12
75% Functions 3/4
100% Lines 7/7
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                      2x               4x 4x                 1x               1x           2x 2x                            
import React from 'react'
import PropTypes from 'prop-types'
import { Controlled as ControlledCodeMirror } from 'react-codemirror2'
import { Button, Toolbar } from '@material-ui/core'
import { editorTypes } from './editorTypes'
 
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/xml/xml'
import 'codemirror/mode/sql/sql'
import 'codemirror/mode/javascript/javascript'
 
export const CodeMirrorCore = ({
  input: { value, onChange = () => {} } = {},
  meta: { valid, error },
  type,
  label,
  defaultValue = '',
  required = false
}) => {
  const { mode, format, parse, stringify } = editorTypes[type]
  return (
    <div>
      <span style={{ color: '#c4c4c4' }}>
        {label}
        {required ? ' * ' : ' '}
      </span>
      {valid ? null : <span style={{ color: '#ff3d3a' }}> ({error})</span>}
      {Boolean(format) && (
        <Toolbar disableGutters>
          <Button onClick={() => onChange(format(value))}>Format</Button>
        </Toolbar>
      )}
      <ControlledCodeMirror
        label={label}
        value={stringify(value || defaultValue)}
        options={{ mode, lineNumbers: true, lineWrapping: true }}
        onBeforeChange={(editor, data, valueFromEditor) => {
          onChange(parse(valueFromEditor))
        }}
      />
    </div>
  )
}
const valueType = PropTypes.oneOfType([PropTypes.string, PropTypes.array, PropTypes.object])
CodeMirrorCore.propTypes = {
  input: PropTypes.shape({
    value: valueType,
    onChange: PropTypes.func
  }),
  meta: PropTypes.shape({
    valid: PropTypes.bool.isRequired,
    error: PropTypes.string
  }).isRequired,
  type: PropTypes.oneOf(Object.keys(editorTypes)).isRequired,
  label: PropTypes.node.isRequired,
  defaultValue: valueType,
  required: PropTypes.bool
}