All files split.tsx

98.63% Statements 216/219
90.53% Branches 86/95
96% Functions 24/25
98.54% Lines 202/205
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456  1x 1x 1x 1x 1x   1x 1x   1x 1x   1x   1x                                                                                               1x           27x 27x 243x       27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 54x 27x 27x 27x 27x 27x 27x     27x   27x 1x     27x   27x 27x   27x 27x   27x 27x   27x 27x 54x 4x   54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 2x     54x 432x 432x 270x 162x 2x     54x 54x 2x 4x       54x 2x       27x 1x     27x 1x     27x 27x 27x 27x 1x       12x 12x   12x   12x 1x     12x 1x     12x   26x 2x   26x 2x 2x         26x 2x   26x 2x   26x 2x   26x 2x     26x 208x 208x 2x     26x 2x   26x 26x   2x 2x 2x 2x 2x   26x 26x 26x 2x     26x 26x 26x 1x         12x 1x 1x 1x 1x 1x 1x   1x     12x 1x     12x 1x   12x 1x       1x 1x 1x     1x 8x 1x 1x 2x   1x       1x 1x 1x 1x 2x   1x       1x 7x 6x       1x 7x 1x       1x 2x 1x       1x 2x 1x       1x           1x 56x 56x 6x       1x   3x 3x 1x 1x       3x 3x 5x 5x       10x 5x 5x       1x 28x     1x 39x 39x 39x               1x                                                                                                     1x                                                             1x  
import {Selection, Annotation, Editor} from 'brace'
const ace = require('brace')
import * as React from 'react'
const PropTypes = require('prop-types')
const isEqual = require( 'lodash.isequal')
const get = require( 'lodash.get')
 
import { editorOptions, editorEvents } from './editorOptions'
const { Range } = ace.acequire('ace/range');
import { EditorProps, Marker, Command, AceOptions} from './types'
import 'brace/ext/split'
const { Split } = ace.acequire('ace/split');
 
class AceEditorClass {
  [index:string] : any
}
 
 
export interface SplitEditorProps {
    [index:string] : any
    name?: string
    style: any
    /** For available modes see https://github.com/thlorenz/brace/tree/master/mode */
    mode?: string
    /** For available themes see https://github.com/thlorenz/brace/tree/master/theme */
    theme?: string
    height?: string
    width?: string
    className?: string
    fontSize?: number
    showGutter?: boolean
    showPrintMargin?: boolean
    highlightActiveLine?: boolean
    focus?: boolean
    cursorStart?: number
    wrapEnabled?: boolean
    readOnly?: boolean
    minLines?: number
    maxLines?: number
    enableBasicAutocompletion?: boolean
    enableLiveAutocompletion?: boolean
    tabSize?: number
    value?: string[]
    defaultValue?: string[]
    scrollMargin?: number[]
    onLoad?: (editor: EditorProps) => void
    onBeforeLoad?: (ace: any) => void
    onChange?: (value: string[], event?: any) => void
    onSelection?: (selectedText: string, event?: any) => void
    onCopy?: (value: string) => void
    onPaste?: (value: string) => void
    onFocus?: () => void
    onBlur?: () => void
    onScroll?: (editor: EditorProps) => void
    editorProps?: EditorProps
    setOptions?: AceOptions
    keyboardHandler?: string
    commands?: Array<Command>
    annotations?: Array<Array<Annotation>>
    markers?: Array<Array<Marker>>
}
 
 
export default class SplitComponent extends React.Component<SplitEditorProps, undefined> {
  editor: AceEditorClass
  refEditor: HTMLElement
  [index:string]:any
  silent: boolean
  constructor(props: SplitEditorProps) {
    super(props);
    editorEvents.forEach(method => {
      this[method] = this[method].bind(this);
    });
  }
 
  componentDidMount() {
    const {
      className,
      onBeforeLoad,
      mode,
      focus,
      theme,
      fontSize,
      value,
      defaultValue,
      cursorStart,
      showGutter,
      wrapEnabled,
      showPrintMargin,
      scrollMargin = [ 0, 0, 0, 0],
      keyboardHandler,
      onLoad,
      commands,
      annotations,
      markers,
      splits,
    } = this.props;
 
    this.editor = ace.edit(this.refEditor);
 
    if (onBeforeLoad) {
      onBeforeLoad(ace);
    }
 
    const editorProps = Object.keys(this.props.editorProps);
 
    var split = new Split(this.editor.container,`ace/theme/${theme}`,splits)
    this.editor.env.split = split;
 
    this.splitEditor = split.getEditor(0);
    this.split = split
    // in a split scenario we don't want a print margin for the entire application
    this.editor.setShowPrintMargin(false);
    this.editor.renderer.setShowGutter(false);
    // get a list of possible options to avoid 'misspelled option errors'
    const availableOptions = this.splitEditor.$options;
    split.forEach((editor: AceEditorClass, index: number) => {
      for (let i = 0; i < editorProps.length; i++) {
        editor[editorProps[i]] = this.props.editorProps[editorProps[i]];
      }
      const defaultValueForEditor = get(defaultValue, index)
      const valueForEditor = get(value, index, '')
      editor.setTheme(`ace/theme/${theme}`);
      editor.renderer.setScrollMargin(scrollMargin[0], scrollMargin[1], scrollMargin[2], scrollMargin[3])
      editor.getSession().setMode(`ace/mode/${mode}`);
      editor.setFontSize(fontSize.toString());
      editor.renderer.setShowGutter(showGutter);
      editor.getSession().setUseWrapMode(wrapEnabled);
      editor.setShowPrintMargin(showPrintMargin);
      editor.on('focus', this.onFocus);
      editor.on('blur', this.onBlur);
      editor.on('copy', this.onCopy);
      editor.on('paste', this.onPaste);
      editor.on('change', this.onChange);
      editor.getSession().selection.on('changeSelection', this.onSelectionChange);
      editor.session.on('changeScrollTop', this.onScroll);
      editor.setValue(defaultValueForEditor === undefined ? valueForEditor : defaultValueForEditor, cursorStart);
      const newAnnotations = get(annotations, index, [])
      const newMarkers = get(markers, index, [])
      editor.getSession().setAnnotations(newAnnotations);
      if(newMarkers && newMarkers.length > 0){
        this.handleMarkers(newMarkers,editor);
      }
 
      for (let i = 0; i < editorOptions.length; i++) {
        const option = editorOptions[i];
        if (availableOptions.hasOwnProperty(option)) {
          editor.setOption(option, this.props[option]);
        } else if (this.props[option]) {
          console.warn(`ReaceAce: editor option ${option} was activated but not found. Did you need to import a related tool or did you possibly mispell the option?`)
        }
      }
      this.handleOptions(this.props, editor);
      if (Array.isArray(commands)) {
        commands.forEach((command) => {
          editor.commands.addCommand(command);
        });
      }
 
      if (keyboardHandler) {
        editor.setKeyboardHandler('ace/keyboard/' + keyboardHandler);
      }
    })
 
    if (className) {
      this.refEditor.className += ' ' + className;
    }
 
    if (focus) {
      this.splitEditor.focus();
    }
 
    const sp = this.editor.env.split;
    sp.setOrientation( this.props.orientation === 'below' ? sp.BELOW : sp.BESIDE);
    sp.resize(true)
    if (onLoad) {
      onLoad(sp);
    }
  }
 
  componentWillReceiveProps(nextProps: SplitEditorProps) {
    const oldProps = this.props;
 
    const split = this.editor.env.split
 
    if (nextProps.splits !== oldProps.splits) {
      split.setSplits(nextProps.splits)
    }
 
    if (nextProps.orientation !== oldProps.orientation) {
      split.setOrientation( nextProps.orientation === 'below' ? split.BELOW : split.BESIDE);
    }
 
    split.forEach((editor: Editor, index: number) => {
 
      if (nextProps.mode !== oldProps.mode) {
        editor.getSession().setMode('ace/mode/' + nextProps.mode);
      }
      if (nextProps.keyboardHandler !== oldProps.keyboardHandler) {
        Eif (nextProps.keyboardHandler) {
          editor.setKeyboardHandler('ace/keyboard/' + nextProps.keyboardHandler);
        } else {
          editor.setKeyboardHandler(null);
        }
      }
      if (nextProps.fontSize !== oldProps.fontSize) {
        editor.setFontSize(nextProps.fontSize.toString());
      }
      if (nextProps.wrapEnabled !== oldProps.wrapEnabled) {
        editor.getSession().setUseWrapMode(nextProps.wrapEnabled);
      }
      if (nextProps.showPrintMargin !== oldProps.showPrintMargin) {
        editor.setShowPrintMargin(nextProps.showPrintMargin);
      }
      if (nextProps.showGutter !== oldProps.showGutter) {
        editor.renderer.setShowGutter(nextProps.showGutter);
      }
 
      for (let i = 0; i < editorOptions.length; i++) {
        const option = editorOptions[i];
        if (nextProps[option] !== oldProps[option]) {
          editor.setOption(option, nextProps[option]);
        }
      }
      if (!isEqual(nextProps.setOptions, oldProps.setOptions)) {
        this.handleOptions(nextProps, editor);
      }
      const nextValue = get(nextProps.value, index, '')
      if (editor.getValue() !== nextValue) {
        // editor.setValue is a synchronous function call, change event is emitted before setValue return.
        this.silent = true;
        const pos = editor.session.selection
        editor.setValue(nextValue, nextProps.cursorStart);
        editor.session.selection = pos
        this.silent = false;
      }
      const newAnnotations = get(nextProps.annotations, index, [])
      const oldAnnotations = get(oldProps.annotations, index, [])
      if (!isEqual(newAnnotations, oldAnnotations)) {
        editor.getSession().setAnnotations(newAnnotations);
      }
 
      const newMarkers = get(nextProps.markers, index, [])
      const oldMarkers = get(oldProps.markers, index, [])
      if (!isEqual(newMarkers, oldMarkers) && (newMarkers && newMarkers.length > 0)) {
        this.handleMarkers(newMarkers, editor);
      }
 
    })
 
    if (nextProps.className !== oldProps.className) {
      let appliedClasses = this.refEditor.className;
      let appliedClassesArray = appliedClasses.trim().split(' ');
      let oldClassesArray = oldProps.className.trim().split(' ');
      oldClassesArray.forEach((oldClass: string) => {
        let index = appliedClassesArray.indexOf(oldClass);
        appliedClassesArray.splice(index, 1);
      });
      this.refEditor.className = ' ' + nextProps.className + ' ' + appliedClassesArray.join(' ');
    }
 
    if (nextProps.theme !== oldProps.theme) {
      split.setTheme('ace/theme/' + nextProps.theme);
    }
 
    if (nextProps.focus && !oldProps.focus) {
      this.splitEditor.focus();
    }
    if(nextProps.height !== this.props.height || nextProps.width !== this.props.width){
      this.editor.resize();
    }
  }
 
  componentWillUnmount() {
    this.editor.destroy();
    this.editor = null;
  }
 
  onChange(event: Event) {
    if (this.props.onChange && !this.silent) {
      let value: string[] = []
      this.editor.env.split.forEach((editor: Editor) => {
        value.push(editor.getValue())
      })
      this.props.onChange(value, event);
    }
  }
 
  onSelectionChange(event: Event) {
    Eif (this.props.onSelectionChange) {
      let value: Selection[] = []
      this.editor.env.split.forEach((editor: Editor) => {
        value.push(editor.getSelection())
      })
      this.props.onSelectionChange(value, event);
    }
  }
 
  onFocus() {
    if (this.props.onFocus) {
      this.props.onFocus();
    }
  }
 
  onBlur() {
    if (this.props.onBlur) {
      this.props.onBlur();
    }
  }
 
  onCopy(text: string) {
    if (this.props.onCopy) {
      this.props.onCopy(text);
    }
  }
 
  onPaste(text: string) {
    if (this.props.onPaste) {
      this.props.onPaste(text);
    }
  }
 
  onScroll() {
    if (this.props.onScroll) {
      this.props.onScroll(this.editor);
    }
  }
 
  handleOptions(props: SplitEditorProps, editor: AceEditorClass) {
    const setOptions = Object.keys(props.setOptions);
    for (let y = 0; y < setOptions.length; y++) {
      editor.setOption(setOptions[y], props.setOptions[setOptions[y]]);
    }
  }
 
  handleMarkers(markers: Marker[], editor: AceEditorClass) {
    // remove foreground markers
    let currentMarkers = editor.getSession().getMarkers(true);
    for (const i in currentMarkers) {
      Eif (currentMarkers.hasOwnProperty(i)) {
        editor.getSession().removeMarker(currentMarkers[i].id);
      }
    }
    // remove background markers
    currentMarkers = editor.getSession().getMarkers(false);
    for (const i in currentMarkers) {
      Eif (currentMarkers.hasOwnProperty(i)) {
        editor.getSession().removeMarker(currentMarkers[i].id);
      }
    }
    // add new markers
    markers.forEach(({ startRow, startCol, endRow, endCol, className, type, inFront = false }) => {
      const range = new Range(startRow, startCol, endRow, endCol);
      editor.getSession().addMarker(range, className, type, inFront);
    });
  }
 
  updateRef(item: HTMLElement) {
    this.refEditor = item;
  }
 
  render() {
    const { name, width, height, style } = this.props;
    const divStyle = { width, height, ...style };
    return (
      <div ref={this.updateRef}
        id={name}
        style={divStyle}
      >
      </div>
    );
  }
  public static propTypes: SplitEditorProps = {
    mode: PropTypes.string,
    splits: PropTypes.number,
    orientation: PropTypes.string,
    focus: PropTypes.bool,
    theme: PropTypes.string,
    name: PropTypes.string,
    className: PropTypes.string,
    height: PropTypes.string,
    width: PropTypes.string,
    fontSize: PropTypes.oneOfType([
      PropTypes.number,
      PropTypes.string,
    ]),
    showGutter: PropTypes.bool,
    onChange: PropTypes.func,
    onCopy: PropTypes.func,
    onPaste: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    onScroll: PropTypes.func,
    value: PropTypes.arrayOf(PropTypes.string),
    defaultValue: PropTypes.arrayOf(PropTypes.string),
    onLoad: PropTypes.func,
    onSelectionChange: PropTypes.func,
    onBeforeLoad: PropTypes.func,
    minLines: PropTypes.number,
    maxLines: PropTypes.number,
    readOnly: PropTypes.bool,
    highlightActiveLine: PropTypes.bool,
    tabSize: PropTypes.number,
    showPrintMargin: PropTypes.bool,
    cursorStart: PropTypes.number,
    editorProps: PropTypes.object,
    setOptions: PropTypes.object,
    style: PropTypes.object,
    scrollMargin: PropTypes.array,
    annotations: PropTypes.array,
    markers: PropTypes.array,
    keyboardHandler: PropTypes.string,
    wrapEnabled: PropTypes.bool,
    enableBasicAutocompletion: PropTypes.oneOfType([
      PropTypes.bool,
      PropTypes.array,
    ]),
    enableLiveAutocompletion: PropTypes.oneOfType([
      PropTypes.bool,
      PropTypes.array,
    ]),
    commands: PropTypes.array,
  };
  public static defaultProps: Partial<SplitEditorProps> = {
    name: 'brace-editor',
    focus: false,
    orientation: 'beside',
    splits: 2,
    mode: '',
    theme: '',
    height: '500px',
    width: '500px',
    value: [],
    fontSize: 12,
    showGutter: true,
    onChange: null,
    onPaste: null,
    onLoad: null,
    onScroll: null,
    minLines: null,
    maxLines: null,
    readOnly: false,
    highlightActiveLine: true,
    showPrintMargin: true,
    tabSize: 4,
    cursorStart: 1,
    editorProps: {},
    style: {},
    scrollMargin: [ 0, 0, 0, 0],
    setOptions: {},
    wrapEnabled: false,
    enableBasicAutocompletion: false,
    enableLiveAutocompletion: false,
  };
}