All files / src/ui BlockEditor.js

74.86% Statements 274/366
68.27% Branches 71/104
69.92% Functions 93/133
75.48% Lines 234/310

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 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 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 6791x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x     1x                       8800x 8801x 8800x 8800x                         6248x           8800x       8800x             14981x     14981x     14981x 14981x 14981x 14981x 14981x 14981x                                                                                                       1x 1x       1x                                                                         1298x 119x 118x     118x                                 212x 212x 188x   188x                   142x 146x                 122x 3x 3x 3x 3x 3x 119x 3x 3x 3x 3x 3x           116x 116x 116x 116x   116x 116x   116x             118x 118x 118x   118x 118x   118x 118x 118x 118x 118x 118x   118x 118x 118x 118x 1x   118x 118x         118x 18x     118x 118x       118x 118x 118x           118x     118x                                                 234x 118x 118x       2x 1x 11x 12x   6x 6x     1x           3x   4x 7x 2x 2x     3x   8x   3x 1x       9x   8x 8x 8x   7x   8x       1x 1x                 152x   41x     41x 41x     25x                     118x 2596x 20x       118x       12x 12x         12x 12x 12x         12x 12x 12x 12x 12x 12x 12x     7x     2x     35x                               9x 9x 9x 5x 5x 3x 2x     4x     13x 13x 13x   13x 9x 9x     13x   13x           14x 14x 14x 14x 13x 13x 1x   12x 14x 14x 14x 14x 8x   12x 8x 1x   12x                     1x 1x 1x 1x   1x 1x 1x                 116x 116x 116x 116x   82x 82x 34x                                                     96x 96x 96x                           160x 160x       29x       118x     118x 118x 118x   118x 118x 118x 118x 118x 118x 118x 118x     20820x           20938x 20938x 20938x 20938x 20938x           20938x 20938x 20938x   20938x                     9x                 20938x   20938x   16702x 15048x   16702x   20938x       54402x         118x   118x 118x 169x           92x     1x  
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import 'codemirror/addon/search/search';
import 'codemirror/addon/search/searchcursor';
import classNames from 'classnames';
import PropTypes from 'prop-types/prop-types';
import './Editor.less';
import {connect} from 'react-redux';
import SHARED from '../shared';
import NodeEditable from '../components/NodeEditable';
import {activateByNid, setCursor, OverwriteTarget} from '../actions';
import {commitChanges} from '../edits/commitChanges';
import {speculateChanges, getTempCM} from '../edits/speculateChanges';
import {pos} from '../types';
import DragAndDropEditor from './DragAndDropEditor';
import {poscmp, say, resetNodeCounter, minpos, maxpos,
  validateRanges, BlockError} from '../utils';
import BlockComponent from '../components/BlockComponent';
import { defaultKeyMap, keyDown } from '../keymap';
import {store} from '../store';
 
// CodeMirror APIs that we need to disallow
const unsupportedAPIs = ['indentLine', 'toggleOverwrite', 'setExtending',
  'getExtending', 'findPosH', 'findPosV', 'setOption',
  'addOverlay', 'removeOverlay', 'undoSelection', 'redoSelection',
  'charCoords', 'coordsChar', 'cursorCoords', 'startOperation',
  'endOperation', 'operation', 'addKeyMap', 'removeKeyMap', 
  //'on', 'off',
  'extendSelection', 'extendSelections', 'extendSelectionsBy'];
 
// TODO(Oak): this should really be a new file, but for convenience we will put it
// here for now
 
class ToplevelBlock extends BlockComponent {
  constructor(props) {
    super(props);
    this.container = document.createElement('span');
    this.container.classList.add('react-container');
  }
 
  static propTypes = {
    node: PropTypes.object.isRequired,
  }
 
  // by default, let's render a placeholder
  state = { renderPlaceholder: this.props.incrementalRendering };
 
  // we need to trigger a render if the node was moved or resized at the
  // top-level, in order to re-mark the node and put the DOM in the new marker
  shouldComponentUpdate(nextProps, nextState) {
    return poscmp(this.props.node.from, nextProps.node.from) !== 0 // moved
      ||   poscmp(this.props.node.to,   nextProps.node.to  ) !== 0 // resized
      ||   super.shouldComponentUpdate(nextProps, nextState)       // changed
      ||   !document.contains(this.mark.replacedWith);             // removed from DOM
  }
 
  componentWillUnmount() { this.mark.clear(); }
 
  // once the placeholder has mounted, wait 250ms and render
  componentDidMount() {
    Eif(!this.props.incrementalRendering) return; // bail if incremental is off
    window.requestAnimationFrame( () => {
      setTimeout(() => this.setState({ renderPlaceholder: false }), 50);
    });
  }
 
  render() {
    const {node} = this.props;
 
    // set elt to a cheap placeholder, OR render the entire rootNode
    const elt = this.state.renderPlaceholder? (<div/>) : node.reactElement();
 
    // if any prior block markers are in this range, clear them
    const {from, to} = node.srcRange(); // includes the node's comment, if any
    SHARED.cm.findMarks(from, to).filter(m=>m.BLOCK_NODE_ID).forEach(m => m.clear());
    this.mark = SHARED.cm.markText(from, to, {replacedWith: this.container});
    this.mark.BLOCK_NODE_ID = node.id;
    node.mark = this.mark;
    return ReactDOM.createPortal(elt, this.container);
  }
}
 
class ToplevelBlockEditableCore extends Component {
 
  static propTypes = {
    quarantine: PropTypes.array.isRequired,
    onDisableEditable: PropTypes.func.isRequired,
    onChange: PropTypes.func.isRequired,
  }
 
  constructor(props) {
    super(props);
    const [start, end] = this.props.quarantine;
    this.container = document.createElement('span');
    this.container.classList.add('react-container');
    // CM treats 0-width ranges differently than other ranges, so check
    if(poscmp(start, end) === 0) {
      this.marker = SHARED.cm.setBookmark(start, {widget: this.container});
    } else {
      this.marker = SHARED.cm.markText(start, end, {replacedWith: this.container});
    }
  }
 
  componentWillUnmount() {
    this.marker.clear();
  }
 
  render() {
    const {onDisableEditable, onChange, quarantine} = this.props;
    const [start, end, value] = quarantine;
    const props = {
      tabIndex          : '-1',
      role              : 'text box',
      'aria-setsize'    : '1',
      'aria-posinset'   : '1',
      'aria-level'      : '1',
    };
    return ReactDOM.createPortal(
      <NodeEditable target={new OverwriteTarget(start, end)}
                    value={value}
                    onChange={onChange}
                    contentEditableProps={props}
                    isInsertion={true}
                    extraClasses={[]}
                    onDisableEditable={onDisableEditable} />,
      this.container
    );
  }
}
 
const mapStateToProps2 = ({quarantine}) => ({quarantine});
const mapDispatchToProps2 = dispatch => ({
  onDisableEditable: () => dispatch({type: 'DISABLE_QUARANTINE'}),
  onChange: text => dispatch({type: 'CHANGE_QUARANTINE', text}),
});
const ToplevelBlockEditable = connect(mapStateToProps2, mapDispatchToProps2)(ToplevelBlockEditableCore);
 
class BlockEditor extends Component {
  static propTypes = {
    value: PropTypes.string.isRequired,
    options: PropTypes.object,
    cmOptions: PropTypes.object,
    keyMap: PropTypes.object,
    language: PropTypes.string.isRequired,
    parser: PropTypes.object.isRequired,
    setAST: PropTypes.func.isRequired,
    setCursor: PropTypes.func.isRequired,
    setQuarantine: PropTypes.func.isRequired,
    setAnnouncer: PropTypes.func.isRequired,
    clearFocus: PropTypes.func.isRequired,
    activateByNid: PropTypes.func.isRequired,
    search: PropTypes.shape({
      onSearch: PropTypes.func.isRequired,
      search: PropTypes.func.isRequired,
      setCursor: PropTypes.func.isRequired,
      setCM: PropTypes.func.isRequired,
    }),
    onBeforeChange: PropTypes.func,
    onMount:PropTypes.func.isRequired,
    hasQuarantine: PropTypes.bool.isRequired,
    api: PropTypes.object,
    passedAST: PropTypes.object,
    showDialog: PropTypes.func.isRequired,
    closeDialog: PropTypes.func.isRequired,
 
    // this is actually required, but it's buggy
    // see https://github.com/facebook/react/issues/3163
    ast: PropTypes.object,
    dispatch: PropTypes.func.isRequired,
    cur: pos
  }
 
  constructor(props) {
    super(props);
    this.mouseUsed = false;
 
    // stick the keyDown handler in the store
    store.onKeyDown = this.handleKeyDown;
  }
 
  static defaultProps = {
    options: {},
    keyMap : defaultKeyMap,
    search: {
      search: () => null,
      onSearch: () => {},
      setCursor: () => {},
    },
    api: {}
  }
 
  // Anything that didn't come from cmb itself must be speculatively
  // checked. NOTE: this only checks the *first change* in a changeset!
  handleBeforeChange = (cm, change) => {
    let notFromCMB = (origin) => origin && origin.startsWith("cmb:");
    if (!notFromCMB(change.origin)) {
      let {successful, newAST} = speculateChanges([change]);
      // Successful! Let's save all the hard work we did to build the new AST
      Eif (successful) { this.newAST = newAST; }
      // Error! Cancel the change
      else {
        change.cancel();
        throw new BlockError("An invalid change was rejected", "Invalid Edit", change);
      }
    }
  }
 
  handleChanges = (cm, changes) => {
    this.props.dispatch((dispatch, getState) => {
      if (!changes.every(c => c.origin && c.origin.startsWith("cmb:"))) {
        // These changes did not originate from us. However, they've all
        // passed the `handleBeforeChange` function, so they must be valid edits.
        // (There's almost certainly just one edit here; I (Justin) am not
        // convinced this will always work if there is more than one edit here.)
        // Since the edit(s) is valid, commit it without calling speculateChanges.
 
        // Turn undo and redo into cmb actions, update the focusStack, and
        // provide a focusHint
        if (changes[0].origin === "undo") {
          for (let c of changes) c.origin = "cmb:undo";
          const {oldFocusNId, _newFocusNId} = getState().actionFocus;
          const focusHint = (newAST) => newAST.getNodeByNId(oldFocusNId);
          commitChanges(changes, true, focusHint, this.newAST);
          dispatch({type: 'UNDO'});
        } else if (changes[0].origin === "redo") {
          for (let c of changes) c.origin = "cmb:redo";
          const {_oldFocusNId, newFocusNId} = getState().actionFocus;
          const focusHint = (newAST) => newAST.getNodeByNId(newFocusNId);
          commitChanges(changes, true, focusHint, this.newAST);
          dispatch({type: 'REDO'});
        } else {
          // This (valid) changeset is coming from outside of the editor, but we
          // don't know anything else about it. Apply the change, set the focusHint
          // to the top of the tree (-1), and provide an astHint so we don't need
          // to reparse and rebuild the tree
          let annt = '';
          for (let i = changes.length - 1; i >= 0; i--) {
            annt = annt + changes[i].origin;
            Iif (i !== 0) annt = ' and ' + annt;
          }
          Iif (annt === '') annt = 'change';
          getState().undoableAction = annt; //?
          //console.log('BlockEditor.js calling commitChanges', changes)
          commitChanges(changes, false, -1, this.newAST);
        }
      }
    });
  }
 
  handleEditorDidMount = ed => {
    const wrapper = ed.getWrapperElement();
    wrapper.setAttribute('role', 'tree');
    wrapper.setAttribute('aria-label', 'Block Editor');
 
    const scroller = ed.getScrollerElement();
    scroller.setAttribute('role', 'presentation');
 
    const announcements = document.createElement('span');
    announcements.setAttribute('role', 'log');
    announcements.setAttribute('aria-live', 'assertive');
    wrapper.appendChild(announcements);
    ed.on('beforeChange', this.handleBeforeChange);
    ed.on('changes', this.handleChanges);
 
    SHARED.cm = ed;
    var ast = this.props.passedAST;
    this.props.setAST(ast);
    if (this.props.options.collapseAll) {
      this.props.dispatch({type: 'COLLAPSE_ALL'});
    }
    this.props.setAnnouncer(announcements);
    say("Block Mode Enabled", 500);
 
    // if we have nodes, default to the first one. Note that does NOT
    // activate a node; only when the editor is focused, the focused node will be
    // active
    if (ast.rootNodes.length > 0) {
      this.props.dispatch({type: 'SET_FOCUS', focusId: ast.rootNodes[0].id});
    }
    // a tree element should know how many roots it has
    wrapper.setAttribute('aria-setsize', ast.rootNodes.length);
    this.props.search.setCM(ed);
 
    // once the DOM has loaded, reconstitute any marks and render them
    // see https://stackoverflow.com/questions/26556436/react-after-render-code/28748160#28748160
    window.requestAnimationFrame( () => setTimeout(() => {
      this.markMap = new Map();
      SHARED.recordedMarks.forEach((m, k) => {
        let node = this.props.ast.getNodeByNId(k);
        this.markText(node.from, node.to, m.options);
      });
    }, 0));
 
    this.props.onMount(ed);
 
    // export methods to the object interface
    Object.assign(this.props.api, this.buildAPI(ed));
  }
 
  executeAction(action) {
    // convert code to AST
    if(action.type == "SET_AST") {
      SHARED.cm.setValue(action.code);
      action.ast = this.props.ast;
      delete action.code;
    }
    // convert nid to node id, and use activate to generate the action
    if(action.type == "SET_FOCUS") {
      // NOTE(Emmanuel): the following line is probably dead code
      action.focusId = this.props.ast.getNodeByNId(action.nid).id;
      //console.log('XXX BlockEditor:311 calling activateByNid');
      this.props.activateByNid(action.nid, {allowMove: true});
      delete action.nid;
      return;
    }
    // ignore set announcer
    if(action.type == "SET_ANNOUNCER"){ return; }
    this.props.dispatch(action);
  }
 
  buildAPI(ed) {
    let withState = (func) => this.props.dispatch((_, getState) => func(getState()));
    const cm = SHARED.cm;
    const api = {
      /*****************************************************************
      * CM APIs WE WANT TO OVERRIDE
      */
      'findMarks':  (from, to) => this.findMarks(from, to),
      'findMarksAt': (pos) => this.findMarksAt(pos),
      'getAllMarks': () => this.getAllMarks(),
      'markText': (from, to, opts) => this.markText(from, to, opts),
      // Something is selected if CM has a selection OR a block is selected
      'somethingSelected': () => withState(({selections}) =>
        Boolean(SHARED.cm.somethingSelected() || selections.length)),
      // CMB has focus if CM has focus OR a block is active
      'hasFocus': () =>
        cm.hasFocus() || Boolean(document.activeElement.id.match(/block-node/)),
      'extendSelection': (from, to, opts) => this.extendSelections([from], opts, to),
      'extendSelections': (heads, opts) => this.extendSelections(heads, opts),
      'extendSelectionsBy': (f, opts) =>
        this.extendSelections(this.listSelections().map(f), opts),
      'getSelections': (sep) =>
        this.listSelections().map(s => SHARED.cm.getRange(s.anchor, s.head, sep)),
      'getSelection': (sep) =>
        this.listSelections().map(s => SHARED.cm.getRange(s.anchor, s.head, sep)).join(sep),
      'listSelections' : () => this.listSelections(),
      'replaceRange': (text, from, to, origin) => withState(({ast}) => {
        validateRanges([{anchor:from, head:to}], ast);
        SHARED.cm.replaceRange(text, from, to, origin);
      }),
      'setSelections': (ranges, primary, opts) => this.setSelections(ranges, primary, opts),
      'setSelection': (anchor, head=anchor, opts) =>
        this.setSelections([{anchor: anchor, head: head}], null, opts),
      'addSelection': (anchor, head) =>
        this.setSelections([{anchor: anchor, head: head}], null, null, false),
      'replaceSelections': (rStrings, select) => this.replaceSelections(rStrings, select),
      'replaceSelection': (rString, select) =>
        this.replaceSelections(Array(this.listSelections().length).fill(rString), select),
      // If a node is active, return the start. Otherwise return the cursor as-is
      'getCursor': (where) => this.getCursor(where),
      // If the cursor falls in a node, activate it. Otherwise set the cursor as-is
      'setCursor': (cur) => withState(({ast}) => {
        const node = ast.getNodeContaining(cur);
        if(node) {
          //console.log('XXX BlockEditor:365 calling activateByNid');
          this.props.activateByNid(node.nid, {record: false, allowMove: true});
        }
        this.props.setCursor(ed, cur);
      }),
      // As long as widget isn't defined, we're good to go
      'setBookmark': (pos, opts) => {
        Eif(opts.widget) {
          throw new BlockError("setBookmark() with a widget is not supported in Block Mode", "API Error");
        }
        SHARED.cm.setBookmark(pos, opts);
      },
 
      /*****************************************************************
      * APIs THAT ARE UNIQUE TO CODEMIRROR-BLOCKS
      */
      'getAst':
        () => withState((state) => state.ast),
      'getFocusedNode':
        () => withState(({focusId, ast}) => {
          // was returning null instead of undefined, but
          // activation-test.js expects latter
          let x = focusId ? ast.getNodeById(focusId) : undefined;
          return x;
        }),
      'getSelectedNodes':
        () => withState(({selections, ast}) => selections.map(id => ast.getNodeById(id))),
 
      /*****************************************************************
      * APIs FOR TESTING
      */
      'getQuarantine': () => withState(({quarantine}) => quarantine),
      'setQuarantine': (q) => this.props.setQuarantine(q),
      'resetNodeCounter': () => resetNodeCounter(),
      'executeAction' : (action) => this.executeAction(action),
    };
    // show which APIs are unsupported
    unsupportedAPIs.forEach(f =>
      api[f] = () => {
        throw BlockError(
          `The CM API '${f}' is not supported in the block editor`,
          'API Error');
      });
    return api;
  }
 
  markText(from, to, options) {
    let node = this.props.ast.getNodeAt(from, to);
    Iif(!node) {
      throw new BlockError(
        'Could not create TextMarker: there is no AST node at [',from, to,']',
        'API Error');
    }
    let supportedOptions = ['css','className','title'];
    for (let opt in options) {
      Iif (!supportedOptions.includes(opt))
        throw new BlockError(
          `markText: option "${opt}" is not supported in block mode`,
          `API Error`);
    }
    let mark = SHARED.cm.markText(from, to, options); // keep CM in sync
    mark._clear = mark.clear;
    mark.clear = () => { mark._clear(); this.props.dispatch({type: 'CLEAR_MARK', id: node.id}); };
    mark.find = () => { let {from, to} = this.props.ast.getNodeById(node.id); return {from, to}; };
    mark.options = options;
    this.props.dispatch({type: 'ADD_MARK', id: node.id, mark: mark});
    return mark;
  }
  findMarks(from, to) {
    return SHARED.cm.findMarks(from, to).filter(m => !m.BLOCK_NODE_ID);
  }
  findMarksAt(pos) {
    return SHARED.cm.findMarksAt(pos).filter(m => !m.BLOCK_NODE_ID);
  }
  getAllMarks() {
    return SHARED.cm.getAllMarks().filter(m => !m.BLOCK_NODE_ID);
  }
  // clear all non-block marks
  _clearMarks() {
    this.getAllMarks().map(m => m.clear());
  }
  // disallow widget option
  setBookmark(pos, options) {
    if(options.widget) {
      throw new BlockError(
        `setBookmark: option 'widget' is not supported in block mode`,
        `API Error`);
    }
    return SHARED.cm.setBookmark(pos, options);
  }
  getCursor(where="from") {
    const dispatch = this.props.dispatch;
    const {focusId, ast} = dispatch((_, getState) => getState());
    if(focusId && document.activeElement.id.match(/block-node/)) {
      const node = ast.getNodeById(focusId);
      if(where == "from") return node.from;
      if(where == "to") return node.to;
      else throw new BlockError(
        `getCursor() with ${where} is not supported on a focused block`,
        `API Error`);
    } else { return SHARED.cm.getCursor(where); }
  }
  listSelections() {
    const dispatch = this.props.dispatch;
    const {selections, ast} = dispatch((_, getState) => getState());
    let tmpCM = getTempCM();
    // write all the ranges for all selected nodes
    selections.forEach(id => {
      const node = ast.getNodeById(id);
      tmpCM.addSelection(node.from, node.to);
    });
    // write all the existing selection ranges
    SHARED.cm.listSelections().map(s => tmpCM.addSelection(s.anchor, s.head));
    // return all the selections
    return tmpCM.listSelections();
  }
  getSelections(sep) {
    return this.listSelections().map(s => SHARED.cm.getRange(s.from, s.to, sep));
  }
  setSelections(ranges, primary, options, replace=true) {
    const dispatch = this.props.dispatch;
    const {ast} = dispatch((_, getState) => getState());
    let tmpCM = getTempCM();
    tmpCM.setSelections(ranges, primary, options);
    const textRanges = [], nodes = [];
    try { validateRanges(ranges, ast); }
    catch(e) { throw BlockError(e, "API Error"); }
    // process the selection ranges into an array of ranges and nodes
    tmpCM.listSelections().forEach(({anchor, head}) => {
      const c1 = minpos(anchor, head);
      const c2 = maxpos(anchor, head);
      const node = ast.getNodeAt(c1, c2);
      if(node) { nodes.push(node.id); }
      else textRanges.push({anchor: anchor, head: head});
    });
    if(textRanges.length) {
      if(replace) SHARED.cm.setSelections(textRanges, primary, options);
      else SHARED.cm.addSelection(textRanges[0].anchor, textRanges[0].head);
    }
    dispatch({ type: 'SET_SELECTIONS', selections: nodes });
  }
  extendSelections(heads, opts, to=false) {
    let tmpCM = getTempCM();
    tmpCM.setSelections(this.listSelections());
    if(to) { tmpCM.extendSelections(heads, opts); }
    else { tmpCM.extendSelection(heads[0], to, opts); }
    // if one of the ranges is invalid, setSelections will raise an error
    this.setSelections(tmpCM.listSelections(), null, opts);
  }
  replaceSelections(replacements, select=false) {
    let tmpCM = getTempCM();
    tmpCM.setSelections(this.listSelections());
    tmpCM.replaceSelections(replacements, select);
    SHARED.cm.setValue(tmpCM.getValue());
    // if one of the ranges is invalid, setSelections will raise an error
    Iif(select == "around") { this.setSelections(tmpCM.listSelections()); }
    Iif(select == "start")  { this.props.setCursor(tmpCM.listSelections().pop().head); }
    else { this.props.setCursor(tmpCM.listSelections().pop().anchor); }
  }
 
  handleEditorWillUnmount = ed => {
    ed.off('beforeChange', this.handleBeforeChange);
    ed.off('changes', this.handleChanges);
  }
 
  handleTopLevelFocus = (ed, _) => {
    const {dispatch} = this.props;
    dispatch((_, getState) => {
      const {cur} = getState();
      if (!this.mouseUsed && (cur === null)) {
        // NOTE(Oak): use setTimeout so that the CM cursor will not blink
        setTimeout(() => this.props.activateByNid(null, {allowMove: true}), 0);
        this.mouseUsed = false;
      } else Iif(this.mouseUsed && (cur === null)) {
        // if it was a click, get the cursor from CM
        setTimeout(() => this.props.setCursor(ed, ed.getCursor()));
        this.mouseUsed = false;
      }
    });
  }
 
  handleTopLevelMouseDown = () => {
    this.mouseUsed = true;
    setTimeout(() => this.mouseUsed = false, 200);
  }
 
  handleTopLevelKeyPress = (ed, e) => {
    const text = e.key;
    // let CM handle kbd shortcuts or whitespace insertion
    if (e.ctrlKey || e.metaKey || text.match(/\s+/)) return;
    e.preventDefault();
    const start = SHARED.cm.getCursor(true);
    const end   = SHARED.cm.getCursor(false);
    this.props.setQuarantine(start, end, text);
  }
 
  // called from both CM *and* Node components
  // each is responsible for passing 'this' as the environment
  // store showDialog in the environment, and pass the keyMap
  handleKeyDown = (e, env) => {
    env.showDialog = this.props.showDialog;
    env.toolbarRef = this.props.toolbarRef;
    return keyDown(e, env, this.props.keyMap);
  }
 
  handleTopLevelPaste = (ed, e) => {
    e.preventDefault();
    const text = e.clipboardData.getData('text/plain');
    const start = SHARED.cm.getCursor(true);
    const end = SHARED.cm.getCursor(false);
    this.props.setQuarantine(start, end, text);
  }
 
  // this change was introduced during the switch from onCursor to onCursorActivity
  // if there are selections, pass null. otherwise pass the cursor
  handleTopLevelCursorActivity = (ed, _) => {
    let cur = (ed.getSelection().length > 0)? null : ed.getCursor();
    this.props.setCursor(ed, cur);
  }
 
  componentWillUnmount() {
    SHARED.buffer.remove();
  }
 
  componentDidMount() {
    const { parser, options, search } = this.props;
 
    // TODO: pass these with a React Context or something sensible like that.
    SHARED.parser = parser;
    SHARED.options= options;
    SHARED.search = search;
    // create a hidden buffer, for use with copy/cut/paste
    const clipboardBuffer = document.createElement('textarea');
    clipboardBuffer.ariaHidden    = true;
    clipboardBuffer.tabIndex      = -1;
    clipboardBuffer.style.opacity =  0;
    clipboardBuffer.style.height  = '1px';
    SHARED.buffer = clipboardBuffer;
    document.body.appendChild(SHARED.buffer);
    this.afterDOMUpdate();
  }
 
  componentDidUpdate() { this.afterDOMUpdate(); }
 
  // NOTE(Emmanuel): use requestAnimationFrame to make sure that cm.refresh() is called
  // after the DOM has completely finished updating.
  // see https://stackoverflow.com/questions/26556436/react-after-render-code/28748160#28748160
  afterDOMUpdate() {
    window.requestAnimationFrame(() => setTimeout( () => {
      const {dispatch} = this.props;
      dispatch((_, getState) => {
        const {quarantine} = getState();
        Eif(!quarantine) SHARED.cm.refresh(); // don't refresh mid-quarantine
      });
    }, 0));
  }
 
  render() {
    const classes = [];
    Eif (this.props.language) {
      classes.push(`blocks-language-${this.props.language}`);
    }
    return (
      <>
        <DragAndDropEditor
          options={this.props.cmOptions}
          className={classNames(classes)}
          value={this.props.value}
          onBeforeChange={this.props.onBeforeChange}
          onKeyPress={this.handleTopLevelKeyPress}
          onMouseDown={this.handleTopLevelMouseDown}
          onFocus={this.handleTopLevelFocus}
          onPaste={this.handleTopLevelPaste}
          onKeyDown={(_, e) => this.handleKeyDown(e, this)}
          onCursorActivity={this.handleTopLevelCursorActivity}
          editorDidMount={this.handleEditorDidMount} />
        {this.renderPortals()}
      </>
    );
  }
 
  renderPortals = () => {
    const incrementalRendering = this.props.options.incrementalRendering;
    let portals;
    if (SHARED.cm && this.props.ast) {
      // Render all the top-level nodes
      portals = this.props.ast.rootNodes.map(r =>
        <ToplevelBlock key={r.id} node={r} incrementalRendering={incrementalRendering} />
      );
      Iif (this.props.hasQuarantine) portals.push(<ToplevelBlockEditable key="-1" />);
    }
    return portals;
  }
}
 
const mapStateToProps = ({ast, cur, quarantine}) => ({
  ast,
  cur,
  hasQuarantine: !!quarantine
});
const mapDispatchToProps = dispatch => ({
  dispatch,
  setAST: ast => dispatch({type: 'SET_AST', ast}),
  setAnnouncer: announcer => dispatch({type: 'SET_ANNOUNCER', announcer}),
  setCursor: (_, cur) => dispatch(setCursor(cur)),
  clearFocus: () => {
    //console.log('BlockEditor:671 calling SET_FOCUS with focusId null');
    return dispatch({type: 'SET_FOCUS', focusId: null});
  },
  setQuarantine: (start, end, text) => dispatch({type: 'SET_QUARANTINE', start, end, text}),
  activateByNid: (nid, options) => dispatch(activateByNid(nid, options))
});
 
export default connect(mapStateToProps, mapDispatchToProps)(BlockEditor);