All files / src/components Node.jsx

86.02% Statements 80/93
78.33% Branches 47/60
96% Functions 24/25
89.16% Lines 74/83

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 2631x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x                 2x 2x   221166x                                                               24574x             6545x   439x         4x           54x 54x 54x 54x   54x       3x 3x 3x 3x                                   32x 21x 21x         4x 4x 4x     4x     2x 2x       2x         5x 5x 4x 4x   1x         31127x 31127x 31127x                             31119x   31119x 31119x 31119x   31119x                           31119x         31119x   6x                                   31113x 31113x 31113x   31113x     62226x                         87x           31113x 23490x   31113x 31113x 31113x         1x           127162x             24574x   14x 8x 3x 75x 4x     1x  
import React  from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types/prop-types';
import {ASTNode} from '../ast';
import {drop, delete_, copy, paste, activateByNid, setCursor,
        InsertTarget, ReplaceNodeTarget, OverwriteTarget} from '../actions';
import NodeEditable from './NodeEditable';
import BlockComponent from './BlockComponent';
import {NodeContext, DropTargetContext, findAdjacentDropTargetId} from './DropTarget';
import {isErrorFree} from '../store';
import SHARED from '../shared';
import {DragNodeSource, DropNodeTarget} from '../dnd';
import classNames from 'classnames';
import {store} from '../store';
 
// TODO(Oak): make sure that all use of node.<something> is valid
// since it might be cached and outdated
// EVEN BETTER: is it possible to just pass an id?
 
@DragNodeSource
@DropNodeTarget(function(monitor) {
  const node = store.getState().ast.getNodeById(this.props.node.id);
  return drop(monitor.getItem(), new ReplaceNodeTarget(node));
})
class Node extends BlockComponent {
  static contextType = DropTargetContext;
 
  static defaultProps = {
    children: null,
    normallyEditable: false,
    expandable: true,
  }
 
  static propTypes = {
    node: PropTypes.instanceOf(ASTNode).isRequired,
    children: PropTypes.node,
 
    connectDragSource: PropTypes.func.isRequired,
    isDragging: PropTypes.bool.isRequired,
    connectDropTarget: PropTypes.func.isRequired,
    isOver: PropTypes.bool.isRequired,
    inToolbar: PropTypes.bool,
 
    normallyEditable: PropTypes.bool,
 
    isSelected: PropTypes.bool.isRequired,
    expandable: PropTypes.bool,
    textMarker: PropTypes.object,
 
    activateByNid: PropTypes.func.isRequired,
  }
 
  state = {editable: false, value: null}
 
  componentDidMount() {
    // For testing
    this.props.node.isEditable = () => this.state.editable;
  }
 
  // if its a top level node (ie - it has a CM mark on the node) AND
  // its isCollapsed property has changed, call mark.changed() to
  // tell CodeMirror that the widget's height may have changed
  componentDidUpdate(prevProps) {
    if(this.props.node.mark && 
        (prevProps.isCollapsed ^ this.props.isCollapsed)) {
      this.props.node.mark.changed();
    }
  }
 
  handleChange = (value) => {
    this.setState({value});
  }
 
  // nid can be stale!! Always obtain a fresh copy of the node
  // from getState() before calling activateByNid
  handleMouseDown = e => {
    Eif(!this.props.inToolbar) e.stopPropagation(); // prevent ancestors to steal focus
    Iif (!isErrorFree()) return; // TODO(Oak): is this the best way?
    const {ast} = store.getState();
    const currentNode = ast.getNodeById(this.props.node.id);  
    //console.log('XXX Node:84 calling activateByNid');
    this.props.activateByNid(currentNode.nid, {allowMove: false});
  }
 
  handleClick = e => {
    const { inToolbar, isCollapsed, normallyEditable } = this.props;
    e.stopPropagation();
    Iif(inToolbar) return;
    if(normallyEditable) this.handleMakeEditable();
  }
 
  handleDoubleClick = e => {
    const {
      inToolbar, isCollapsed, normallyEditable,
      collapse, uncollapse, node
    } = this.props;
    e.stopPropagation();
    if(inToolbar) return;
    if(isCollapsed) {
      uncollapse(node.id);
    } else {
      collapse(node.id);
    }
  }
 
  handleMouseDragRelated = e => {
    if (e.type === 'dragstart') {
      let dt = new DataTransfer();
      dt.setData('text/plain', e.target.innerText);
    }
  }
 
  handleMakeEditable = () => {
    Iif (!isErrorFree() || this.props.inToolbar) return;
    this.setState({editable: true});
    SHARED.cm.refresh(); // is this needed?
  };
 
  handleDisableEditable = () => this.setState({editable: false});
 
  setLeft() {
    const dropTargetId = findAdjacentDropTargetId(this.props.node, true);
    Iif (dropTargetId) {
      this.props.setEditable(dropTargetId, true);
      return true;
    } else {
      return false;
    }
  }
 
  setRight() {
    const dropTargetId = findAdjacentDropTargetId(this.props.node, false);
    if (dropTargetId) {
      this.props.setEditable(dropTargetId, true);
      return true;
    } else {
      return false;
    }
  }
 
  isLocked() {
    Eif (SHARED.options?.renderOptions) {
      const lockedList = SHARED.options.renderOptions.lockNodesOfType;
      return lockedList.includes(this.props.node.type);
    }
    return false;
  }
 
  render() {
    const {
      isSelected,
      isCollapsed,
      expandable,
      textMarker,
      children,
      inToolbar,
      node,
      ...passingProps
    } = this.props;
 
    let comment = node.options.comment;
    if(comment) comment.id = `block-node-${node.id}-comment`;
    const locked = this.isLocked();
 
    const props = {
      id                : `block-node-${node.id}`,
      tabIndex          : "-1",
      'aria-selected'   : isSelected,
      'aria-label'      : node.options['aria-label']+',' ,
      'aria-labelledby' : `block-node-${node.id} ${comment ? comment.id : ''}`,
      'aria-disabled'   : locked ? "true" : undefined,
      'aria-expanded'   : (expandable && !locked) ? !isCollapsed : undefined,
      'aria-setsize'    : node["aria-setsize"],
      'aria-posinset'   : node["aria-posinset"],
      'aria-level'      : node.level,
      'aria-multiselectable' : "true"
    };
 
    const classes = [
      {'blocks-locked': locked},
      `blocks-${node.type}`
    ];
 
    if (this.state.editable) {
      // TODO: combine passingProps and contentEditableProps
      return (
        <NodeEditable {...passingProps}
                      onDisableEditable={this.handleDisableEditable}
                      extraClasses={classes}
                      isInsertion={false}
                      target={new ReplaceNodeTarget(node)}
                      value={this.state.value}
                      onChange={this.handleChange}
                      onDragStart={this.handleMouseDragRelated}
                      onDragEnd={this.handleMouseDragRelated}
                      onDrop={this.handleMouseDragRelated}
                      contentEditableProps={props} />
      );
    } else {
      const {
        connectDragSource, isDragging,
        connectDropTarget, isOver,
        connectDragPreview
      } = this.props;
      classes.push({'blocks-over-target': isOver, 'blocks-node': true});
      if(textMarker?.options.className) classes.push(textMarker.options.className);
      let result = (
        <span
          {...props}
          className     = {classNames(classes)}
          ref           = {el => node.element = el}
          role          = {inToolbar? "listitem" : "treeitem"}
          style={{
            opacity: isDragging ? 0.5 : 1,
            cssText : textMarker? textMarker.options.css : null,
          }}
          title         = {textMarker? textMarker.options.title : null}
          onMouseDown   = {this.handleMouseDown}
          onClick       = {this.handleClick}
          onDoubleClick = {this.handleDoubleClick}
          onDragStart   = {this.handleMouseDragRelated}
          onDragEnd     = {this.handleMouseDragRelated}
          onDrop        = {this.handleMouseDragRelated}
          onKeyDown     = {e => store.onKeyDown(e, this)}
          >
          {children}
          {comment && comment.reactElement()}
        </span>
      );
      if (this.props.normallyEditable) {
        result = connectDropTarget(result);
      }
      result = connectDragPreview(connectDragSource(result), {offsetX: 1, offsetY: 1});
      result = (<NodeContext.Provider value={{node: this.props.node}}>{result}</NodeContext.Provider>);
      return result;
    }
  }
}
 
const mapStateToProps = (
  {selections, collapsedList, markedMap},
  {node}
  // be careful here. Only node's id is accurate. Use getNodeById
  // to access accurate info
) => {
  return {
    isSelected: selections.includes(node.id),
    isCollapsed: collapsedList.includes(node.id),
    textMarker: markedMap.get(node.id)
  };
};
 
const mapDispatchToProps = dispatch => ({
  dispatch,
  collapse: id => dispatch({type: 'COLLAPSE', id}),
  uncollapse: id => dispatch({type: 'UNCOLLAPSE', id}),
  setCursor: cur => dispatch(setCursor(cur)),
  activateByNid: (nid, options) => dispatch(activateByNid(nid, options)),
  setEditable: (id, bool) => dispatch({type: 'SET_EDITABLE', id, bool}),
});
 
export default connect(mapStateToProps, mapDispatchToProps)(Node);