all files / ui/ DragManager.js

9.63% Statements 21/218
4.44% Branches 4/90
6.9% Functions 2/29
10% Lines 21/210
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                  206×   206×   206× 206× 206×   205× 205×   205× 205×                       206×                     206× 168× 168×   168× 168× 168× 168×                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 206× 206× 206×                                                                                                                                                          
import { DefaultDOMElement } from '../dom'
import { EventEmitter, platform, getDOMRangeFromEvent, isMouseInsideDOMSelection } from '../util'
import { operationHelpers } from '../model'
import Component from './Component'
import DragAndDropHandler from './DragAndDropHandler'
 
class DragManager extends EventEmitter {
 
  constructor(customDropHandlers, context) {
    super()
 
    this.context = context
 
    let dropAssetHandlers = []
    let moveInlineHandlers = []
    customDropHandlers.forEach((h) => {
      // legacy: default type = 'asset'
      let type = h.type || 'drop-asset'
      switch (type) {
        case 'drop-asset': {
          dropAssetHandlers.push(h)
          break
        }
        case 'move-inline': {
          moveInlineHandlers.push(h)
          break
        }
        default:
          console.warn('Unknown type of drop handler.', h)
      }
    })
 
    // TODO: This could live in the configurator at some point
    this.dropHandlers = [
      // source is a PropertySelection, target is a property
      new MoveInline(moveInlineHandlers),
      // source is a NodeSelection, target is a container position
      new MoveBlockNode(),
      // drop external files
      new InsertNodes(dropAssetHandlers, this.context),
      // dynamic custom handler, activated via custom dropzone
      // not via configuration
      new CustomHandler(),
    ]
    if (platform.inBrowser) {
      this.el = DefaultDOMElement.wrapNativeElement(document)
      this.el.on('dragstart', this.onDragStart, this)
      // this.el.on('dragend', this.onDragEnd, this)
      this.el.on('drop', this.onDragEnd, this)
      this.el.on('dragenter', this.onDragEnter, this)
      this.el.on('dragexit', this.onDragExit, this)
      this.el.on('mousedown', this.onMousedown, this)
    }
  }
 
  dispose() {
    if (this.el) {
      this.el.off(this)
    }
  }
 
  onDragStart(e) {
    // console.log('#### DragManager.onDragStart')
    this._initDrag(e, { external: false })
    // Ensure we have a small dragIcon, so dragged content does not eat up
    // all screen space.
    var img = document.createElement("img")
    img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
    e.dataTransfer.setDragImage(img, 0, 0)
    // TODO: the following might probably not work in FF as it disallows setting the drag data
    // Note: setData('text/html', ... ) is necessary so that the browser shows
    // the target caret while dragging, the content must be allowed to drop inline
    // console.log('#### dragState.mode', )
    // TODO: at this point we should do it similar as in Clipboard
    // i.e. copy the selection and export it to HTML
    if (this.dragState.mode === 'inline') {
      e.dataTransfer.setData('text/html', img.outerHTML)
    } else {
      // otherwise we clear the data trying to make the caret
      // invisible this way
      e.dataTransfer.setData('text/html', '<div></div>')
    }
    // console.log('####', this.dragState)
  }
 
  /*
    When drag starts externally, e.g. draggin a file into the workspace
  */
  onDragEnter(e) {
    if (!this.dragState) {
      // console.log('onDragEnter(e)', e)
      this._initDrag(e, {external: true})
    }
  }
 
  onDragEnd(event) {
    if (event.__reserved__) return
    // console.log('onDragEnd', event)
    if (this.dragState) {
      event.stopPropagation()
      event.preventDefault()
      // HACK: there is no way to know if Dropzones wants to
      // extend state, as it can only do it on drop
      this._onDragEnd(event)
    }
  }
 
  onDragExit(e) {
    if (platform.isFF) {
      // FF fires this quite rapidly
    } else {
      // TODO: OTOH, we need to find out if this
      // is really necessary in the other browsers
      // console.log('onDragExit', e)
      this._onDragEnd(e)
    }
  }
 
  extendDragState(extState) {
    Object.assign(this.dragState, extState)
  }
 
  // used to at least reset on the next mousedown
  // TODO: figure out if we could make this only 'once'
  onMousedown(event) {
    if (this.dragState) {
      this.dragState = null
      this._onDragEnd(event)
    }
  }
 
  _onDragEnd(event) {
    if (!this.dragState) {
      // TODO: There are cases where _onDragEnd is called manually via
      // handleDrop and another time via the native dragend event. check
      // why this happens and how it can be avoided
      console.warn('Not in a valid drag state.')
    } else {
      this._handleDrop(event)
    }
    this.emit('drag:finished')
    this.dragState = null
  }
 
  /*
    Called by Dropzones component after drop received
  */
  _handleDrop(e) {
    let dragState = this.dragState
    let i, handler
    let match = false
    dragState.event = e
    dragState.data = this._getData(e)
    // Run through drop handlers and call the first that matches
    for (i = 0; i < this.dropHandlers.length && !match; i++) {
      handler = this.dropHandlers[i]
      match = handler.match(dragState)
    }
    if (match) {
      let editorSession = this.context.editorSession
      editorSession.transaction((tx) => {
        handler.drop(tx, dragState)
      })
    } else {
      console.error('No drop handler could be found.')
    }
  }
 
  /*
    Initializes dragState, which encapsulate state through the whole
    drag + drop operation.
 
    ATTENTION: This can not be debugged properly in Chrome
  */
  _initDrag(event, options) {
    // TODO: we need to figure out how to enable dragging cursors
    // e.g., when dragging an inline node containing an img, it looks
    // nice, showing the target caret and a dragging cursor.
    // Doing the same just with text content does show the forbidden symbol
 
    // console.log('_initDrag')
    let sel = this._getSelection()
    let dragState = Object.assign({ startEvent: event }, options)
    this.dragState = dragState
 
    // external drag
    // Note: we only consider drops on the block-level or with custom dropzones
    if (dragState.external) {
      dragState.selectionDrag = false
      dragState.sourceSelection = null
      dragState.scrollPanes = this._getSurfacesGroupedByScrollPane()
      this.emit('drag:started', dragState)
      return
    }
 
    // Note: selection drags are always without drop-zones,
    // but using the native cursor
    let isSelectionDrag = (
      (sel.isPropertySelection() || sel.isContainerSelection()) &&
      isMouseInsideDOMSelection(event)
    )
    if (isSelectionDrag) {
      // TODO: we do not support dragging of ContainerSelection yet
      if (sel.isContainerSelection()) {
        console.warn('Dragging of ContainerSelection is not supported yet.')
        return _stop()
      }
      // console.log('DragManager: starting a selection drag', sel.toString())
      dragState.inline = true
      dragState.selectionDrag = true
      dragState.sourceSelection = sel
      // TODO: should we emit for dropzones?
      return
    }
    let comp = Component.unwrap(event.target)
    if (!comp) return _stop()
    let isolatedNodeComponent
    if (comp._isInlineNodeComponent) {
      isolatedNodeComponent = comp
      dragState.inline = true
      dragState.sourceNode = comp.props.node
    } else {
      isolatedNodeComponent = comp.context.isolatedNodeComponent
    }
    if (!isolatedNodeComponent) return _stop()
    let surface = isolatedNodeComponent.context.surface
    // dragging an InlineNode
    if(isolatedNodeComponent._isInlineNodeComponent) {
      let inlineNode = isolatedNodeComponent.props.node
      dragState.inline = true
      dragState.selectionDrag = true
      dragState.sourceSelection = {
        type: 'property',
        path: inlineNode.start.path,
        startOffset: inlineNode.start.offset,
        endOffset: inlineNode.end.offset,
        containerId: surface.getContainerId(),
        surfaceId: surface.id
      }
      return
    }
    // dragging an IsolatedNode
    // console.log('DragManager: started dragging a node or from external')
    dragState.selectionDrag = false
    dragState.nodeDrag = true
    dragState.sourceSelection = {
      type: 'node',
      nodeId: isolatedNodeComponent.props.node.id,
      containerId: surface.getContainerId(),
      surfaceId: surface.id
    }
    // We store the scrollPanes in dragState so the Dropzones component
    // can use it to compute dropzones per scrollpane for each contained
    // surface
    dragState.scrollPanes = this._getSurfacesGroupedByScrollPane()
    // console.log('... emitting dragstart for Dropzones')
    this.emit('drag:started', dragState)
 
    function _stop() {
      // console.log('.... NOPE')
      event.preventDefault()
      event.stopPropagation()
    }
  }
 
  _getSurfacesGroupedByScrollPane() {
    // We need to determine all ContainerEditors and their scrollPanes; those have the drop
    // zones attached
    let surfaces = this.context.surfaceManager.getSurfaces()
    let scrollPanes = {}
    surfaces.forEach((surface) => {
      // Skip for everything but container editors
      if (!surface.isContainerEditor()) return
      let scrollPane = surface.context.scrollPane
      let scrollPaneName = scrollPane.getName()
      let surfaceName = surface.getName()
      if (!scrollPanes[scrollPaneName]) {
        let surfaces = {}
        surfaces[surfaceName] = surface
        scrollPanes[scrollPaneName] = { scrollPane, surfaces }
      } else {
        scrollPanes[scrollPaneName].surfaces[surfaceName] = surface
      }
    })
    return scrollPanes
  }
 
  _getSelection() {
    return this.context.editorSession.getSelection()
  }
 
  _getComponents(targetEl) {
    let res = []
    let curr = targetEl
    while (curr) {
      let comp = Component.getComponentForDOMElement(curr)
      if (comp) {
        res.unshift(comp)
        if(comp._isSurface) {
          return res
        }
      }
      curr = curr.parentNode
    }
    return null
  }
 
  _getIsolatedNodeOrContainerChild(targetEl) {
    let parent, current
    current = targetEl
    parent = current.parentNode
    while(parent) {
      if (parent._comp && parent._comp._isContainerEditor) {
        return current._comp
      } else if (current._comp && current._comp._isIsolatedNode) {
        return current._comp
      }
      current = parent
      parent = current.parentNode
    }
  }
 
  /*
    Following best practice from Mozilla for URI extraction
 
    See: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Recommended_Drag_Types#link
  */
  _extractUris(dataTransfer) {
    let uris = []
    let rawUriList = dataTransfer.getData('text/uri-list')
    if (rawUriList) {
      uris = rawUriList.split('\n').filter(function(item) {
        return !item.startsWith('#')
      })
    }
    return uris
  }
 
  /*
    Extracts information from e.dataTransfer (files, uris, text, html)
  */
  _getData(e) {
    let dataTransfer = e.dataTransfer
    if (dataTransfer) {
      return {
        files: Array.prototype.slice.call(dataTransfer.files),
        uris: this._extractUris(dataTransfer),
        text: dataTransfer.getData('text/plain'),
        html: dataTransfer.getData('text/html')
      }
    }
  }
}
 
/*
  Moves a selected node to a new location.
 
  Used as a drop handler for internal drags with NodeSelections.
*/
class MoveBlockNode extends DragAndDropHandler {
 
  match(dragState) {
    let {insertPos} = dragState.dropParams
    // - sourceSeletion must be a NodeSelection
    return (!dragState.external && dragState.nodeDrag &&
      dragState.dropType === 'place' && insertPos >= 0
    )
  }
 
  drop(tx, dragState) {
    // - remember current selection (node that is dragged)
    // - delete current selection (removes node from original position)
    // - determine node selection based on given insertPos
    // - paste node at new insert position
    let { insertPos } = dragState.dropParams
    tx.setSelection(dragState.sourceSelection)
    let copy = tx.copySelection()
    // just clear, but don't merge or don't insert a new node
    tx.deleteSelection({ clear: true })
    let containerId = dragState.targetSurface.getContainerId()
    let surfaceId = dragState.targetSurface.getName()
    let container = tx.get(containerId)
    let targetNode = container.nodes[insertPos]
    let insertMode = 'before'
    if (!targetNode) {
      targetNode = container.nodes[insertPos-1]
      insertMode = 'after'
    }
    tx.setSelection({
      type: 'node',
      nodeId: targetNode,
      mode: insertMode,
      containerId: containerId,
      surfaceId: surfaceId
    })
    tx.paste(copy)
  }
}
 
class MoveInline extends DragAndDropHandler {
 
  match(dragState) {
    return !dragState.external && dragState.inline
  }
 
  drop(tx, dragState) {
    let event = dragState.event
    let sourceSel = dragState.sourceSelection
    let wrange = getDOMRangeFromEvent(event)
    if (!wrange) return
    let comp = Component.unwrap(event.target)
    if (!comp) return
    let domSelection = comp.context.domSelection
    if (!domSelection) return
    let range = domSelection.mapDOMRange(wrange)
    if (!range) return
    let targetSel = tx.getDocument()._createSelectionFromRange(range)
 
    // TODO: iterate custom move-inline handlers
    tx.selection = sourceSel
    let snippet = tx.copySelection()
    tx.deleteSelection()
    tx.selection = operationHelpers.transformSelection(targetSel, tx)
    tx.paste(snippet)
  }
}
 
class InsertNodes extends DragAndDropHandler {
  constructor(assetHandlers, context) {
    super()
    this.assetHandlers = assetHandlers
    this.context = context
  }
 
  match(dragState) {
    return dragState.dropType === 'place' && dragState.external
  }
 
  drop(tx, dragState) {
    let { insertPos } = dragState.dropParams
    let files = dragState.data.files
    let uris = dragState.data.uris
    let containerId = dragState.targetSurface.getContainerId()
    let surfaceId = dragState.targetSurface.id
    let container = tx.get(containerId)
    let targetNode = container.nodes[insertPos]
    let insertMode = 'before'
    if (!targetNode) {
      targetNode = container.nodes[insertPos-1]
      insertMode = 'after'
    }
    tx.setSelection({
      type: 'node',
      nodeId: targetNode,
      mode: insertMode,
      containerId: containerId,
      surfaceId: surfaceId
    })
    if (files.length > 0) {
      files.forEach((file) => {
        this._callHandlers(tx, {
          file: file,
          type: 'file'
        })
      })
    } else if (uris.length > 0) {
      uris.forEach((uri) => {
        this._callHandlers(tx, {
          uri: uri,
          type: 'uri'
        })
      })
    } else {
      console.info('TODO: implement html/text drop here')
    }
  }
 
  _callHandlers(tx, params) {
    let i, handler;
    for (i = 0; i < this.assetHandlers.length; i++) {
      handler = this.assetHandlers[i]
 
      let match = handler.match(params, this.context)
      if (match) {
        handler.drop(tx, params, this.context)
        break
      }
    }
  }
}
 
/*
  Built-in handler that calls a custom handler, specified
  on the component (e.g. see ImageComponent).
*/
class CustomHandler extends DragAndDropHandler {
 
  match(dragState) {
    return dragState.dropType === 'custom'
  }
 
  drop(tx, dragState) {
    // Delegate handling to component which set up the custom dropzone
    dragState.component.handleDrop(tx, dragState)
  }
}
 
export default DragManager