all files / ui/ ContainerEditor.js

47.18% Statements 67/142
32.71% Branches 35/107
63.64% Functions 14/22
48.2% Lines 67/139
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                                                            223× 223×   223×   223× 223×     223× 223× 223×       223×   223×   223×         191×     191×       229× 229×       223× 223× 223×                         306×   306× 306× 306× 306×     306×       306×   306× 925×       306× 306× 306×     306×       1076× 1076× 984×   92× 92× 92× 32×   60×           452× 452× 452×                                                                                                                                                                                                                                   18×             2258×       879×       803× 803×       497×                                           76×   76× 76× 76× 76× 76× 1116× 1116× 194× 194× 151× 151× 151× 151× 151×             151× 43× 43×                  
import { isString, keys } from '../util'
import { selectionHelpers, EditingBehavior } from '../model'
import Surface from './Surface'
import IsolatedNodeComponent from './IsolatedNodeComponent'
import RenderingEngine from './RenderingEngine'
 
/**
  Represents an editor for content rendered in a flow, such as a manuscript.
 
  @prop {String} name unique editor name
  @prop {String} containerId container id
 
  @example
 
  Create a full-fledged `ContainerEditor` for the `body` container of a document.
  Allow Strong and Emphasis annotations and to switch text types between paragraph
  and heading at level 1.
 
  ```js
  $$(ContainerEditor, {
    name: 'bodyEditor',
    containerId: 'body'
  })
  ```
*/
 
class ContainerEditor extends Surface {
 
  constructor(parent, props, el) {
    // default props derived from the given props
    props.containerId = props.containerId || props.node.id
    props.name = props.name || props.containerId || props.node.id
 
    super(parent, props, el)
 
    this.containerId = this.props.containerId
    Iif (!isString(this.containerId)) {
      throw new Error("Property 'containerId' is mandatory.")
    }
    let doc = this.getDocument()
    this.container = doc.get(this.containerId)
    Iif (!this.container) {
      throw new Error('Container with id ' + this.containerId + ' does not exist.')
    }
 
    this.textTypes = this.props.textTypes || []
 
    this.editingBehavior = this.context.editingBehavior || new EditingBehavior()
 
    this._deriveInternalState(this.props)
  }
 
  // Note: this component is self managed
  shouldRerender(newProps) {
    Iif (newProps.disabled !== this.props.disabled) return true
    // TODO: we should still detect when the document has changed,
    // see https://github.com/substance/substance/issues/543
    return false
  }
 
  willReceiveProps(newProps) {
    super.willReceiveProps.apply(this, arguments)
    this._deriveInternalState(newProps)
  }
 
  didMount() {
    super.didMount.apply(this, arguments)
    let editorSession = this.getEditorSession()
    editorSession.onUpdate('document', this._onContainerChanged, this, {
      path: [this.getContainerId(), 'nodes']
    })
 
  }
 
  dispose() {
    super.dispose.apply(this, arguments)
    let editorSession = this.getEditorSession()
    editorSession.off(this)
  }
 
  render($$) {
    let el = super.render($$)
 
    let doc = this.getDocument()
    let containerId = this.getContainerId()
    let containerNode = doc.get(containerId)
    Iif (!containerNode) {
      console.warn('No container node found for ', containerId)
    }
    el.addClass('sc-container-editor container-node ' + containerId)
      .attr("data-id", containerId)
 
    // native spellcheck
    el.attr('spellcheck', this.props.spellcheck === 'native')
 
    containerNode.getNodes().forEach(function(node) {
      el.append(this._renderNode($$, node))
    }.bind(this))
 
    // No editing if disabled by user or container is empty
    Eif (!this.props.disabled && !this.isEmpty()) {
      el.addClass('sm-enabled')
      el.setAttribute('contenteditable', true)
    }
 
    return el
  }
 
  _renderNode($$, node) {
    Iif (!node) throw new Error('Illegal argument')
    if (node.isText()) {
      return super.renderNode($$, node)
    } else {
      let componentRegistry = this.context.componentRegistry
      let ComponentClass = componentRegistry.get(node.type)
      if (ComponentClass.prototype._isCustomNodeComponent || ComponentClass.prototype._isIsolatedNodeComponent) {
        return $$(ComponentClass, { node: node }).ref(node.id)
      } else {
        return $$(IsolatedNodeComponent, { node: node }).ref(node.id)
      }
    }
  }
 
  _deriveInternalState(props) {
    let _state = this._state
    Eif (!props.hasOwnProperty('enabled') || props.enabled) {
      _state.enabled = true
    } else {
      _state.enabled = false
    }
  }
 
  _selectNextIsolatedNode(direction) {
    let selState = this.getEditorSession().getSelectionState()
    let node = (direction === 'left') ? selState.getPreviousNode() : selState.getNextNode()
    if (!node || !node.isIsolatedNode()) return false
    if (
      (direction === 'left' && selState.isFirst()) ||
      (direction === 'right' && selState.isLast())
    ) {
      this.getEditorSession().setSelection({
        type: 'node',
        nodeId: node.id,
        containerId: selState.getContainer().id,
        surfaceId: this.id
      })
      return true
    }
    return false
  }
 
  _handleLeftOrRightArrowKey(event) {
    event.stopPropagation()
    const doc = this.getDocument()
    const sel = this.getEditorSession().getSelection()
    const left = (event.keyCode === keys.LEFT)
    const right = !left
    const direction = left ? 'left' : 'right'
 
    if (sel && !sel.isNull()) {
      const container = doc.get(sel.containerId, 'strict')
 
      // Don't react if we are at the boundary of the document
      if (sel.isNodeSelection()) {
        let nodePos = container.getPosition(doc.get(sel.getNodeId()))
        if ((left && nodePos === 0) || (right && nodePos === container.length-1)) {
          event.preventDefault()
          return
        }
      }
 
      if (sel.isNodeSelection() && !event.shiftKey) {
        this.domSelection.collapse(direction)
      }
    }
 
    window.setTimeout(() => {
      this._updateModelSelection({ direction })
    })
  }
 
  _handleUpOrDownArrowKey(event) {
    event.stopPropagation()
    const doc = this.getDocument()
    const sel = this.getEditorSession().getSelection()
    const up = (event.keyCode === keys.UP)
    const down = !up
    const direction = up ? 'left' : 'right'
 
    if (sel && !sel.isNull()) {
      const container = doc.get(sel.containerId, 'strict')
      // Don't react if we are at the boundary of the document
      if (sel.isNodeSelection()) {
        let nodePos = container.getPosition(doc.get(sel.getNodeId()))
        if ((up && nodePos === 0) || (down && nodePos === container.length-1)) {
          event.preventDefault()
          return
        }
        // Unfortunately we need to navigate out of an isolated node
        // manually, as even Chrome on Win is not able to do it.
        let editorSession = this.getEditorSession()
        // TODO the following fixes the mentioned problem for
        // regular UP/DOWN (non expanding)
        // For SHIFT+DOWN it happens to work, and only SHIFT-UP when started as NodeSelection needs to be fixed
        if (!event.shiftKey) {
          event.preventDefault()
          if (up) {
            let prev = container.getChildAt(nodePos-1)
            selectionHelpers.setCursor(editorSession, prev, sel.containerId, 'after')
            return
          } else {
            let next = container.getChildAt(nodePos+1)
            selectionHelpers.setCursor(editorSession, next, sel.containerId, 'before')
            return
          }
        }
      }
    }
 
    window.setTimeout(() => {
      this._updateModelSelection({ direction })
    })
  }
 
  _handleTabKey(event) {
    const editorSession = this.getEditorSession()
    const sel = editorSession.getSelection()
    if (sel.isNodeSelection() && sel.isFull()) {
      const comp = this.refs[sel.getNodeId()]
      if (comp && selectionHelpers.stepIntoIsolatedNode(editorSession, comp)) {
        event.preventDefault()
        event.stopPropagation()
        return
      }
    }
    super._handleTabKey(event)
  }
 
  // Used by Clipboard
  isContainerEditor() {
    return true
  }
 
  /**
    Returns the containerId the editor is bound to
  */
  getContainerId() {
    return this.containerId
  }
 
  getContainer() {
    return this.getDocument().get(this.getContainerId())
  }
 
  isEmpty() {
    let containerNode = this.getContainer()
    return (containerNode && containerNode.nodes.length === 0)
  }
 
  isEditable() {
    return super.isEditable.call(this) && !this.isEmpty()
  }
 
  getTextTypes() {
    return this.textTypes || []
  }
 
  // Used by SwitchTextTypeTool
  // TODO: Filter by enabled commands for this Surface
  // TODO: rethink
  getTextCommands() {
    var textCommands = {}
    this.commandRegistry.each(function(cmd) {
      if (cmd.constructor.textTypeName) {
        textCommands[cmd.getName()] = cmd
      }
    });
    return textCommands
  }
 
  // called by flow when subscribed resources have been updated
  _onContainerChanged(change) {
    let doc = this.getDocument()
    // first update the container
    let renderContext = RenderingEngine.createContext(this)
    let $$ = renderContext.$$
    let container = this.getContainer()
    let path = container.getContentPath()
    for (let i = 0; i < change.ops.length; i++) {
      let op = change.ops[i]
      if (op.type === "update" && op.path[0] === path[0]) {
        let diff = op.diff
        if (diff.type === "insert") {
          let nodeId = diff.getValue()
          let node = doc.get(nodeId)
          let nodeEl
          Eif (node) {
            nodeEl = this._renderNode($$, node)
          } else {
            // node does not exist anymore
            // so we insert a stub element, so that the number of child
            // elements is consistent
            nodeEl = $$('div')
          }
          this.insertAt(diff.getOffset(), nodeEl)
        } else Eif (diff.type === "delete") {
          this.removeAt(diff.getOffset())
        }
      }
    }
  }
}
 
ContainerEditor.prototype._isContainerEditor = true
 
export default ContainerEditor