all files / model/ EditorSession.js

63.73% Statements 181/284
55.17% Branches 64/116
54.69% Functions 35/64
63.67% Lines 177/278
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 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756                                            206×   206×   206× 206×     206×   206×   206×   206×           206×   206×     206×   206×   206× 206×   206×   206×   206×   206× 206×             206×   206×           206×       206× 206× 206× 206× 206× 206×   206×     206× 206×   206×     206×       206×     206×       206× 206× 206× 206×         206× 206×                             5406×       3166×                                       1126×       1126×                     205×               7591×       1793×       4840×               996×       1392×       333×                                                     387× 380×   387× 163× 163× 163×     387× 387×   387×                           763× 763×                                                                                                         168× 168× 166× 157×       166×                                                         32× 32×                                               1253×                                                                           852×                                 206×                                         206×       557× 557× 557×                                                                   157×   157× 157×       157× 157× 157× 157× 157×   157×     157×     157×       161×       161× 161× 161× 161× 161× 161×                                                                                                               557×     557× 557× 557×   557× 557×         557× 557× 557× 557×                         557× 3342×                 2517×   2517× 2517× 2517× 1693× 1693× 1693×   2517×     2517×     2517× 2517× 2517× 2517× 2517× 2517× 2517×   2517× 252×   2517×       2517× 2517× 2517× 824×   2517×                                                                                   3342× 3342×       2228× 2228× 5802×   5802× 5802× 2228× 3574× 2448× 835× 835× 835× 835× 673× 162× 76×     1126× 1126× 1126×           1481×       557× 1275×   557× 557×          
import DocumentChange from '../model/DocumentChange'
import MarkersManager from '../model/MarkersManager'
import Selection from '../model/Selection'
import SelectionState from '../model/SelectionState'
import ChangeHistory from '../model/ChangeHistory'
import SurfaceManager from '../packages/surface/SurfaceManager'
import Transaction from '../model/Transaction'
import CommandManager from '../ui/CommandManager'
import DragManager from '../ui/DragManager'
import GlobalEventHandler from '../ui/GlobalEventHandler'
import MacroManager from '../ui/MacroManager'
import KeyboardManager from '../ui/KeyboardManager'
import forEach from '../util/forEach'
import isPlainObject from '../util/isPlainObject'
import isFunction from '../util/isFunction'
import isString from '../util/isString'
import EventEmitter from '../util/EventEmitter'
import FileManager from './FileManager'
 
class EditorSession extends EventEmitter {
 
  constructor(doc, options) {
    super()
 
    options = options || {}
 
    this.document = doc
    Iif (!options.configurator) {
      throw new Error('No configurator provided.')
    }
    this.configurator = options.configurator
 
    this._transaction = new Transaction(doc, this)
 
    this._history = new ChangeHistory()
    // used for change accumulation (in a collab environment)
    this._currentChange = null
 
    // TODO: while it is good to have these selection
    // related derived state informations separated
    // it would feel better to have the selection itself
    // as a property of this session
    this._selectionState = new SelectionState(doc)
 
    this._commandStates = []
 
    // the session exposes these resources, and keeps track of changes
    this._resources = ['document', 'selection', 'commandStates']
    // flags to keep track which resources have changed since the last 'flow'
    this._dirtyFlags = {}
    // set during a change
    this._change = null
    this._info = null
 
    this._flowStages = ['update', 'pre-render', 'render', 'post-render', 'position', 'finalize']
    // to get something executed directly after a flow
    this._postponed = []
 
    this._observers = {}
 
    this._lang = options.lang || this.configurator.getDefaultLanguage()
    this._dir = options.dir || 'ltr'
 
    // Managers
    // --------
 
    // surface manager takes care of surfaces, keeps track of the currently focused surface
    // and makes sure the DOM selection is rendered properly at the end of a flow
    this.surfaceManager = new SurfaceManager(this)
    // this context is provided to commands, tools, etc.
    this._context = {
      editorSession: this,
      //legacy
      surfaceManager: this.surfaceManager,
    }
    // to expose custom context just provide optios.context
    Iif (options.context) {
      Object.assign(this._context, options.context)
    }
 
    let configurator = this.configurator
    let commands = configurator.getCommands()
    let dropHandlers = configurator.getDropHandlers()
    let macros = configurator.getMacros()
    let converterRegistry = configurator.getConverterRegistry()
    let editingBehavior = configurator.getEditingBehavior()
 
    this.fileManager = options.fileManager || new FileManager(this, configurator.getFileAdapters(), this._context)
 
    // Handling of saving
    this._hasUnsavedChanges = false
    this._isSaving = false
 
    Iif (options.saveHandler) {
      this.saveHandler = options.saveHandler
    } else {
      this.saveHandler = configurator.getSaveHandler()
    }
 
    // The command manager keeps the commandStates up-to-date
    this.commandManager = new CommandManager(this._context, commands)
    // The drag manager dispatches drag requests to registered drag handlers
    // TODO: after consolidating the API of this class, we probably need a less diverse context
    this.dragManager = new DragManager(dropHandlers, Object.assign({}, this._context, {
      commandManager: this.commandManager
    }))
    // The macro manager dispatches to macro detectors at the end of the flow
    this.macroManager = new MacroManager(this._context, macros)
    this.globalEventHandler = new GlobalEventHandler(this, this.surfaceManager)
    this.markersManager = new MarkersManager(this)
    this.keyboardManager = new KeyboardManager(this, configurator.getKeyboardShortcuts(), {
      context: this._context
    })
 
    // TODO: see how we want to expose these
    this.converterRegistry = converterRegistry
    this.editingBehavior = editingBehavior
  }
 
  dispose() {
    this._transaction.dispose()
    this.surfaceManager.dispose()
    this.fileManager.dispose()
    this.commandManager.dispose()
    this.dragManager.dispose()
    this.macroManager.dispose()
    this.globalEventHandler.dispose()
    this.markersManager.dispose()
  }
 
  hasChanged(resource) {
    return this._dirtyFlags[resource]
  }
 
  hasDocumentChanged() {
    return this.hasChanged('document')
  }
 
  hasSelectionChanged() {
    return this.hasChanged('selection')
  }
 
  hasCommandStatesChanged() {
    return this.hasChanged('commandStates')
  }
 
  hasLanguageChanged() {
    return this.hasChanged('lang')
  }
 
  hasTextDirectionChanged() {
    return this.hasChanged('dir')
  }
 
  get(resourceName) {
    switch(resourceName) {
      case 'document':
        return this.getDocument()
      case 'selection':
        return this.getSelection()
      case 'commandStates':
        return this.getCommandStates()
      case 'change':
        return this.getChange()
      default:
        throw new Error('Unknown resource: ' + resourceName)
    }
  }
 
  getConfigurator() {
    return this.configurator
  }
 
  getContext() {
    return this._context
  }
 
  getDocument() {
    return this.document
  }
 
  getSelection() {
    return this.getSelectionState().getSelection()
  }
 
  getSelectionState() {
    return this._selectionState
  }
 
  getCommandStates() {
    return this._commandStates
  }
 
  getChange() {
    return this._change
  }
 
  getChangeInfo() {
    return this._info
  }
 
  getFocusedSurface() {
    return this.surfaceManager.getFocusedSurface()
  }
 
  getSurface(surfaceId) {
    return this.surfaceManager.getSurface(surfaceId)
  }
 
  getLanguage() {
    return this._lang
  }
 
  getTextDirection() {
    return this._dir
  }
 
  canUndo() {
    return this._history.canUndo()
  }
 
  canRedo() {
    return this._history.canRedo()
  }
 
  executeCommand(...args) {
    this.commandManager.executeCommand(...args)
  }
 
  setSelection(sel) {
    // console.log('EditorSession.setSelection()', sel)
    if (sel && isPlainObject(sel)) {
      sel = this.getDocument().createSelection(sel)
    }
    if (sel && !sel.isNull() && !sel.surfaceId) {
      let fs = this.getFocusedSurface()
      Eif (fs) {
        sel.surfaceId = fs.id
      }
    }
    Eif (this._setSelection(sel)) {
      this.startFlow()
    }
    return sel
  }
 
  selectNode(nodeId) {
    let surface = this.getFocusedSurface()
    this.setSelection({
      type: 'node',
      nodeId: nodeId,
      containerId: surface.getContainerId(),
      surfaceId: surface.id
    })
  }
 
  setCommandStates(commandStates) {
    this._commandStates = commandStates
    this._setDirty('commandStates')
  }
 
  setLanguage(lang) {
    if (this._lang !== lang) {
      this._lang = lang
      this._setDirty('lang')
      this.startFlow()
    }
  }
 
  setTextDirection(dir) {
    if (this._dir !== dir) {
      this._dir = dir
      this._setDirty('dir')
      this.startFlow()
    }
  }
 
  createSelection() {
    const doc = this.getDocument()
    return doc.createSelection.apply(doc, arguments)
  }
 
  getCollaborators() {
    return null
  }
 
  /*
    Set saveHandler via API
 
    E.g. if saveHandler not available at construction
  */
  setSaveHandler(saveHandler) {
    this.saveHandler = saveHandler
  }
 
  /**
    Start a transaction to manipulate the document
 
    @param {function} transformation a function(tx) that performs actions on the transaction document tx
 
    @example
 
    ```js
    doc.transaction(function(tx, args) {
      tx.update(...)
      ...
      tx.setSelection(newSelection)
    })
    ```
  */
  transaction(transformation, info) {
    info = info || {}
    let change = this._transaction._recordChange(transformation, this.getSelection(), this.getFocusedSurface())
    if (change) {
      this._commit(change, info)
    } else {
      // if no changes, at least update the selection
      this._setSelection(this._transaction.getSelection())
      this.startFlow()
    }
    return change
  }
 
  undo() {
    this._undoRedo('undo')
  }
 
  redo() {
    this._undoRedo('redo')
  }
 
/* eslint-disable no-invalid-this*/
 
  on(...args) {
    let name = args[0]
    if (this._flowStages.indexOf(name) >= 0) {
      // remove the stage name from the args
      args.shift()
      let options = args[2] || {}
      let resource = options.resource
      if (resource) {
        delete options.resource
        args.unshift(resource)
      }
      this._registerObserver(name, args)
    } else {
      EventEmitter.prototype.on.apply(this, args)
    }
  }
 
  off(...args) {
    Eif (args.length === 1) {
      super.off(...args)
    } else {
      const stage = args[0]
      const method = args[1]
      const observer = args[2]
      this._deregisterObserver(stage, method, observer)
    }
  }
 
  /**
    Registers a hook for the `update` phase.
 
    During `update` data should be derived necessary for rendering.
 
    This is mainly used by extensions of the EditorSession to
    derive extra state information.
 
    @param {string} [resource] the name of the resource
    @param {Function} handler the function handler
    @param {Object} context owner of the handler
    @param {Object} [options] options for the resource handler
 
  */
  onUpdate(...args) {
    return this._registerObserver('update', args)
  }
 
  onPreRender(...args) {
    return this._registerObserver('pre-render', args)
  }
 
  /**
    Registers a hook for the 'render' phase.
 
    During `render`, components should be rerendered.
 
    @param {string} [resource] the name of the resource
    @param {Function} handler the function handler
    @param {Object} context owner of the handler
    @param {Object} [options] options for the resource handler
 
    @example
 
    This typically used by components that render node content.
 
    ```js
    class ImageComponent extends Component {
      didMount() {
        this.context.editorSession.onRender('document', this.rerender, this, {
          path: [this.props.node.id, 'src']
        })
      }
      dispose() {
        this.context.editorSession.off(this)
      }
      render($$) {
        ...
      }
    }
    ```
  */
  onRender(...args) {
    return this._registerObserver('render', args)
  }
 
  /**
    Registers a hook for the 'post-render' phase.
 
    ATM, this phase is used internally only, for recovering the DOM selection
    which typically gets destroyed due to rerendering
 
    @internal
 
    @param {string} [resource] the name of the resource
    @param {Function} handler the function handler
    @param {Object} context owner of the handler
    @param {Object} [options] options for the resource handler
  */
  onPostRender(...args) {
    return this._registerObserver('post-render', args)
  }
 
  /**
    Registers a hook for the 'position' phase.
 
    During `position`, components such as Overlays, for instance, should be positioned.
    At this stage, it is guaranteed that all content is rendered, and the DOM selection
    is set.
 
    @param {string} [resource] the name of the resource
    @param {Function} handler the function handler
    @param {Object} context owner of the handler
    @param {Object} [options] options for the resource handler
 
  */
  onPosition(...args) {
    return this._registerObserver('position', args)
  }
 
  onFinalize(...args) {
    return this._registerObserver('finalize', args)
  }
 
  _setSelection(sel) {
    let hasChanged = this.getSelectionState().setSelection(sel)
    Eif (hasChanged) this._setDirty('selection')
    return hasChanged
  }
 
  _undoRedo(which) {
    const doc = this.getDocument()
    var from, to
    if (which === 'redo') {
      from = this._history.undoneChanges
      to = this._history.doneChanges
    } else {
      from = this._history.doneChanges
      to = this._history.undoneChanges
    }
    var change = from.pop()
    Eif (change) {
      this._applyChange(change, {})
      // move change to the opposite change list (undo <-> redo)
      to.push(change.invert())
      // use selection from change
      let sel = change.after.selection
      Eif (sel) sel.attach(doc)
      this._setSelection(sel)
      // finally trigger the flow
      this.startFlow()
    } else {
      console.warn('No change can be %s.', (which === 'undo'? 'undone':'redone'))
    }
  }
 
  _transformLocalChangeHistory(externalChange) {
    // Transform the change history
    // Note: using a clone as the transform is done inplace
    // which is ok for the changes in the undo history, but not
    // for the external change
    var clone = {
      ops: externalChange.ops.map(function(op) { return op.clone(); })
    }
    DocumentChange.transformInplace(clone, this._history.doneChanges)
    DocumentChange.transformInplace(clone, this._history.undoneChanges)
  }
 
  _transformSelection(change) {
    var oldSelection = this.getSelection()
    var newSelection = DocumentChange.transformSelection(oldSelection, change)
    // console.log('Transformed selection', change, oldSelection.toString(), newSelection.toString())
    return newSelection
  }
 
  _commit(change, info) {
    this._commitChange(change, info)
    // TODO: Not sure this is the best place to mark the session dirty
    this._hasUnsavedChanges = true
    this.startFlow()
  }
 
  _commitChange(change, info) {
    change.timestamp = Date.now()
    this._transaction._document._skipNextDocumentChange = true
    this._applyChange(change, info)
    Eif (info['history'] !== false && !info['hidden']) {
      this._history.push(change.invert())
    }
    var newSelection = change.after.selection || Selection.nullSelection
    // HACK injecting the surfaceId here...
    // TODO: we should find out where the best place is to do this
    Iif (!newSelection.isNull() && !newSelection.surfaceId) {
      newSelection.surfaceId = change.after.surfaceId
    }
    this._setSelection(newSelection)
  }
 
  _applyChange(change, info) {
    Iif (!change) {
      console.error('FIXME: change is null.')
      return
    }
    const doc = this.getDocument()
    doc._apply(change)
    doc._notifyChangeListeners(change, info)
    this._setDirty('document')
    this._change = change
    this._info = info
  }
 
  /*
    Are there unsaved changes?
  */
  hasUnsavedChanges() {
    return this._hasUnsavedChanges
  }
 
  /*
    Save session / document
  */
  save() {
    var saveHandler = this.saveHandler
 
    if (this._hasUnsavedChanges && !this._isSaving) {
      this._isSaving = true
      // Pass saving logic to the user defined callback if available
      if (saveHandler) {
        let saveParams = {
          editorSession: this,
          fileManager: this.fileManager
        }
        return saveHandler.saveDocument(saveParams)
        .then(() => {
          this._hasUnsavedChanges = false
          // We update the selection, just so a selection update flow is
          // triggered (which will update the save tool)
          // TODO: model this kind of update more explicitly. It could be an 'update' to the
          // document resource (hasChanges was modified)
          this.setSelection(this.getSelection())
        })
        .catch((err) => {
          console.error('Error during save', err)
        }).then(() => { // finally
          this._isSaving = false
        })
      } else {
        console.error('Document saving is not handled at the moment. Make sure saveHandler instance provided to editorSession')
        return Promise.reject()
      }
    }
  }
 
  /*
    Starts the flow.
 
    This is necessary when changing resources managed by the session.
    To be able to change multiple resources at the same time,
    this is not done automatically, but needs to be called
    by the implementation.
 
    @internal
  */
  startFlow() {
    Iif (this._flowing) {
      throw new Error('Already in a flow. You need to postpone the update.')
    }
    this._flowing = true
    try {
      this.performFlow()
    } finally {
      this._resetFlow()
      this._flowing = false
    }
    // Note: postponing is ATM used only by Macros
    // HACK: to avoid having multiple flows at the same time
    // we are running this deferred
    const postponed = this._postponed
    const self = this
    this._postponed = []
    setTimeout(function() {
      postponed.forEach(function(fn) {
        fn(self)
      })
    }, 0)
  }
 
  /*
    Emits the phases in the correct order.
 
    @internal
  */
  performFlow() {
    this._flowStages.forEach((stage) => {
      this._notifyObservers(stage)
    })
  }
 
  postpone(fn) {
    this._postponed.push(fn)
  }
 
  _parseObserverArgs(args) {
    let params = { resource: null, handler: null, context: null, options: {} }
    // first can be a string
    let idx = 0
    let arg = args[idx]
    if (isString(arg)) {
      params.resource = arg
      idx++
      arg = args[idx]
    }
    Iif (!arg) {
      throw new Error('Provided handler function was nil.')
    }
    Iif (!isFunction(arg)) {
      throw new Error('Expecting a handler Function.')
    }
    params.handler = arg
    idx++
    arg = args[idx]
    Eif (arg) {
      params.context = arg
      idx++
      arg = args[idx]
    }
    if (arg) {
      params.options = arg
    }
    return params
  }
 
  _registerObserver(stage, args) {
    let observer = this._parseObserverArgs(args)
    let observers = this._observers[stage]
    if (!observers) {
      observers = this._observers[stage] = []
    }
    observers.push(observer)
  }
 
  _deregisterObserver(stage, method, observer) {
    let self = this // eslint-disable-line no-invalid-this
    if (arguments.length === 1) {
      // TODO: we should optimize this, as ATM this needs to traverse
      // a lot of registered listeners
      forEach(self._observers, (observers) => {
        for (let i = observers.length-1; i >=0 ; i--) {
          const o = observers[i]
          if (o.context === observer) {
            observers.splice(i, 1)
            o._deregistered = true
          }
        }
      })
    } else {
      let observers = self._observers[stage]
      // if no observers are registered, then this might not
      // be a deregistration for a stage, but a regular event
      if (!observers) {
        EventEmitter.prototype.off.apply(self, arguments)
      } else {
        for (let i = observers.length-1; i >= 0; i--) {
          let o = observers[i]
          if (o.handler === method && o.context === observer) {
            observers.splice(i, 1)
            o._deregistered = true
          }
        }
      }
    }
  }
 
  _notifyObservers(stage) {
    // TODO: this is not hierarchical anymore
    // i.e. probably we have to expect degradation of performance
    // with huuuge documents, as the number of listeners is
    // We could optimize this by 'compiling' a list of observers for
    // each configuration, maybe lazily
    // for now we accept this circumstance
    let _observers = this._observers[stage]
    if (!_observers) return
    // Make a copy so that iteration does not get confused, when listeners deregister
    // TODO: we could improve this by using a custom data structure that allows
    // manipulation during iteration
    let observers = _observers.slice()
    for (let i = 0; i < observers.length; i++) {
      let o = observers[i]
      // an observer might have been deregistered while this iteration was going on
      Iif (o._deregistered) continue
      if (!o.resource) {
        o.handler.call(o.context, this)
      } else if (o.resource === 'document') {
        if (!this.hasDocumentChanged()) continue
        const change = this.getChange()
        const info = this.getChangeInfo()
        const path = o.options.path
        if (!path) {
          o.handler.call(o.context, change, info, this)
        } else if (change.isAffected(path)) {
          o.handler.call(o.context, change, info, this)
        }
      } else {
        Iif (!this.hasChanged(o.resource)) continue
        const resource = this.get(o.resource)
        o.handler.call(o.context, resource, this)
      }
    }
  }
 
  _setDirty(resource) {
    this._dirtyFlags[resource] = true
  }
 
  _resetFlow() {
    Object.keys(this._dirtyFlags).forEach((resource) => {
      this._dirtyFlags[resource] = false
    })
    this._change = null
    this._info = null
  }
}
 
export default EditorSession