all files / ui/ DOMSelection.js

61.11% Statements 110/180
60.83% Branches 73/120
61.11% Functions 11/18
64.12% Lines 109/170
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                                            205× 205× 167×       205×                                                                                                       271× 271× 271× 271× 271×   271× 271× 270×   270×           270×   270× 270× 270× 270× 270× 270×           273× 273× 273× 273×       273×   273×       273× 273× 244× 244×   243× 204×   39× 39×         29× 29× 29×       29× 29× 29× 29×                               272× 272×       283× 283×                                 283× 283× 282×     283×                                                                                                                                                                                                                     10×   10× 10×   10× 10×             10×                               10×                                                          
import { DefaultDOMElement } from '../dom'
import { platform } from '../util'
import { Coordinate, Range } from '../model'
import Component from './Component'
import TextPropertyComponent from './TextPropertyComponent'
import IsolatedNodeComponent from './IsolatedNodeComponent'
 
const DEBUG = false
 
/*
  A class that maps DOM selections to model selections.
 
  There are some difficulties with mapping model selections:
  1. DOM selections can not model discontinuous selections.
  2. Not all positions reachable via ContentEditable can be mapped to model selections. For instance,
     there are extra positions before and after non-editable child elements.
  3. Some native cursor behaviors need to be overidden.
 
  @param {Editor} Editor component
 */
class DOMSelection {
 
  constructor(editor) {
    this.editor = editor
    if (platform.inBrowser) {
      this.wRange = window.document.createRange()
    }
    // keeping the last DOM and Model coordinates
    // TODO: why are we doing this?
    this.state = { dom: null, model: null }
  }
 
  /**
    Create a model selection by mapping the current DOM selection
    to model coordinates.
 
    @param {object} options
      - `direction`: `left` or `right`; a hint for disambiguations, used by Surface during cursor navigation.
    @returns {model/Selection}
  */
  getSelection(options) {
    // HACK: ignore this if not Browser (e.g. when running the test suite in node)
    Iif (!platform.inBrowser) return
    let range = this.mapDOMSelection(options)
    let doc = this.editor.getDocument()
    // TODO: consolidate
    return doc._createSelectionFromRange(range)
  }
 
  getSelectionForDOMRange(wrange) {
    let range = this.mapDOMRange(wrange)
    let doc = this.editor.getDocument()
    return doc._createSelectionFromRange(range)
  }
 
  /*
    Maps the current DOM selection to a model range.
 
    @param {object} [options]
      - `direction`: `left` or `right`; a hint for disambiguations, used by Surface during cursor navigation.
    @returns {model/Range}
  */
  mapDOMSelection(options) {
    let wSel = window.getSelection()
    let state = this.state
    let range
    // Use this log whenever the mapping goes wrong to analyze what
    // is actually being provided by the browser
    Iif (DEBUG) console.info('DOM->Model: ', wSel.anchorNode, wSel.anchorOffset, wSel.focusNode, wSel.focusOffset);
    Iif (wSel.rangeCount === 0) return _null()
    let anchorNode = DefaultDOMElement.wrapNativeElement(wSel.anchorNode)
    if (wSel.isCollapsed) {
      let coor = this._getCoordinate(anchorNode, wSel.anchorOffset, options)
      Iif (!coor) return _null()
      range = _createRange({
        start: coor,
        end: coor
      })
    }
    else {
      let focusNode = DefaultDOMElement.wrapNativeElement(wSel.focusNode)
      range = this._getRange(anchorNode, wSel.anchorOffset, focusNode, wSel.focusOffset, options)
    }
    Iif (DEBUG) console.info('DOM->Model: range ', range ? range.toString() : null)
    state.model = range
    return range
 
    function _null() {
      state.dom = null
      state.model = null
      return null
    }
  }
 
  /**
    Transfer a given model selection into the DOM.
 
    @param {model/Selection} sel
  */
  setSelection(sel) {
    // HACK: ignore this if not Browser (e.g. when running the test suite in node)
    Iif (!platform.inBrowser) return
    let state = this.state
    let wSel = window.getSelection()
    let wRange = this.wRange
    Iif (!sel || sel.isNull()) return this.clear()
    // console.log('### DOMSelection: setting selection', sel.toString());
    let {start, end} = this.mapModelToDOMCoordinates(sel)
    if (!start) return this.clear()
    if (sel.isReverse()) {
      [start, end] = [end, start]
    }
    state.dom = {
      anchorNode: start.container,
      anchorOffset: start.offset,
      focusNode: end.container,
      focusOffset: end.offset
    }
    _set(state.dom)
 
    function _set({anchorNode, anchorOffset, focusNode, focusOffset}) {
      wSel.removeAllRanges()
      wRange.setStart(anchorNode, anchorOffset)
      wRange.setEnd(anchorNode, anchorOffset)
      wSel.addRange(wRange)
      Eif (focusNode !== anchorOffset || focusOffset !== anchorOffset) {
        wSel.extend(focusNode, focusOffset)
      }
    }
  }
 
  mapModelToDOMCoordinates(sel) {
    Iif (DEBUG) console.info('Model->DOM: sel =', sel.toString());
    let rootEl
    let surface = this.editor.surfaceManager.getSurface(sel.surfaceId)
    Iif (!surface) {
      console.warn('Selection should have "surfaceId" set.')
      rootEl = this.editor.el
    } else {
      rootEl = surface.el
    }
    Iif (sel.isNull() || sel.isCustomSelection()) {
      return {}
    }
 
    let start, end
    if (sel.isPropertySelection() || sel.isContainerSelection()) {
      start = this._getDOMCoordinate(rootEl, sel.start)
      if (!start) {
        console.warn('FIXME: selection seems to be invalid.')
        return {}
      }
      if (sel.isCollapsed()) {
        end = start
      } else {
        end = this._getDOMCoordinate(rootEl, sel.end)
        Iif (!end) {
          console.warn('FIXME: selection seems to be invalid.')
          return {}
        }
      }
    } else Eif (sel.isNodeSelection()) {
      let comp = Component.unwrap(rootEl.find('*[data-id="'+sel.getNodeId()+'"]'))
      Iif (!comp) {
        console.error('Could not find component with id', sel.getNodeId())
        return {}
      }
      Eif (comp._isIsolatedNodeComponent) {
        let coors = IsolatedNodeComponent.getDOMCoordinates(comp, sel)
        start = coors.start
        end = coors.end
        // Note: ATM we do not render collapsed NodeSelections differently
        // if (sel.isAfter()) start = end
        // else if (sel.isBefore()) end = start
      } else {
        let _nodeEl = comp.el
        start = {
          container: _nodeEl.getNativeElement(),
          offset: 0
        }
        end = {
          container: _nodeEl.getNativeElement(),
          offset: _nodeEl.getChildCount()
        }
      }
    }
    Iif (DEBUG) console.info('Model->DOM:', start.container, start.offset, end.container, end.offset, 'isReverse?', sel.isReverse());
    return {start,end}
  }
 
  _getDOMCoordinate(rootEl, coor) {
    let comp, domCoor = null
    Iif (coor.isNodeCoordinate()) {
      comp = Component.unwrap(rootEl.find('*[data-id="'+coor.getNodeId()+'"]'))
      if (comp) {
        if (comp._isIsolatedNodeComponent) {
          domCoor = IsolatedNodeComponent.getDOMCoordinate(comp, coor)
        } else {
          let domOffset = 0
          if (coor.offset > 0) {
            domOffset = comp.getChildCount()
          }
          domCoor = {
            container: comp.getNativeElement(),
            offset: domOffset
          }
        }
      }
    } else {
      comp = Component.unwrap(rootEl.find('.sc-text-property[data-path="'+coor.path.join('.')+'"]'))
      if (comp) {
        domCoor = comp.getDOMCoordinate(coor.offset)
      }
    }
    return domCoor
  }
 
  /*
    Map a DOM range to a model range.
 
    @param {Range} range
    @returns {model/Range}
  */
  mapDOMRange(wRange, options) {
    return this._getRange(
      DefaultDOMElement.wrapNativeElement(wRange.startContainer),
      wRange.startOffset,
      DefaultDOMElement.wrapNativeElement(wRange.endContainer),
      wRange.endOffset, options)
  }
 
  /*
    Clear the DOM selection.
  */
  clear() {
    window.getSelection().removeAllRanges()
    this.state.dom = null
    this.state.model = null
  }
 
  collapse(dir) {
    let wSel = window.getSelection()
    let wRange
    if (wSel.rangeCount > 0) {
      wRange = wSel.getRangeAt(0)
      wRange.collapse(dir === 'left')
      wSel.removeAllRanges()
      wSel.addRange(wRange)
    }
  }
 
  select(el) {
    let wSel = window.getSelection()
    let wRange = window.document.createRange()
    wRange.selectNode(el.getNativeElement())
    wSel.removeAllRanges()
    wSel.addRange(wRange)
  }
 
  extend(el, offset) {
    let wSel = window.getSelection()
    wSel.extend(el.getNativeElement(), offset)
  }
 
  setCursor(el, offset) {
    let wSel = window.getSelection()
    let wRange = window.document.createRange()
    wRange.setStart(el.getNativeElement(), offset)
    wSel.removeAllRanges()
    wSel.addRange(wRange)
  }
 
  /*
    Extract a model range from given DOM elements.
 
    @param {Node} anchorNode
    @param {number} anchorOffset
    @param {Node} focusNode
    @param {number} focusOffset
    @returns {model/Range}
  */
  _getRange(anchorNode, anchorOffset, focusNode, focusOffset, options = {}) {
    let isReverse = DefaultDOMElement.isReverse(anchorNode, anchorOffset, focusNode, focusOffset)
    let isCollapsed = (anchorNode === focusNode && anchorOffset === focusOffset)
    let start, end
    Iif (isCollapsed) {
      start = end = this._getCoordinate(anchorNode, anchorOffset, options)
    } else {
      start = this._getCoordinate(anchorNode, anchorOffset, { direction: isReverse ? 'right' : 'left' })
      end = this._getCoordinate(focusNode, focusOffset, options)
    }
    Eif (start && end) {
      return _createRange({ start, end, isReverse })
    } else {
      return null
    }
  }
 
  /*
    Map a DOM coordinate to a model coordinate.
 
    @param {Node} node
    @param {number} offset
    @param {object} options
    @param {object} [options]
      - `direction`: `left` or `right`; a hint for disambiguation.
    @returns {model/Coordinate}
 
    @info
 
    `options.direction` can be used to control the result when this function is called
    after cursor navigation. The root problem is that we are using ContentEditable on
    Container level (as opposed to TextProperty level). The native ContentEditable allows
    cursor positions which do not make sense in the model sense.
 
    For example,
 
    ```
    <div contenteditable=true>
      <p data-path="p1.content">foo</p>
      <img>
      <p data-path="p1.content">bar</p>
    </div>
    ```
    would allow to set the cursor directly before or after the image, which
    we want to prevent, as it is not a valid insert position for text.
    Instead, if we find the DOM selection in such a situation, then we map it to the
    closest valid model address. And this depends on the direction of movement.
    Moving `left` would provide the previous address, `right` would provide the next address.
    The default direction is `right`.
  */
  _getCoordinate(nodeEl, offset, options={}) {
    let coor = null
    // this deals with a cursor in a TextProperty
    Eif (!coor) {
      coor = TextPropertyComponent.getCoordinate(this.editor.el, nodeEl, offset)
    }
    let comp = Component.unwrap(nodeEl)
    if (!coor && comp) {
      // let IsolatedNodeComponent figure out where the selection is
      Iif (comp.context.isolatedNodeComponent) {
        coor = IsolatedNodeComponent.getCoordinate(nodeEl, options)
      }
    }
    // Edge-cases: These handlers are hacked so that the case is covered,
    // not solved 'elegantly'
    if (!coor) {
      // as in #354: sometimes anchor or focus is the surface itself
      Iif (comp && comp._isContainerEditor) {
        let childIdx = (offset === 0) ? 0 : offset-1
        let isBefore = (offset === 0)
        let container = comp.getContainer()
        let childNode = container.getNodeAt(childIdx)
        let childComp = comp.getChildAt(childIdx)
        coor = new Coordinate([childNode.id], isBefore?0:1 )
        coor._comp = childComp
      }
      // sometimes anchor or focus is a Node component with TextPropertyComponents as children (all TextNode Components)
      else Eif (nodeEl.isElementNode() && nodeEl.getChildCount() > 0) {
        let child = (offset > 0) ? nodeEl.getChildAt(offset-1) : nodeEl.firstChild
        let prop
        let childComp = Component.unwrap(child)
        Eif (childComp && childComp._isTextPropertyComponent) {
          prop = child
        }
        // let prop = last(child.findAll('data-path'))
        Eif (prop) {
          coor = TextPropertyComponent.getCoordinate(nodeEl, prop, (offset > 0) ? prop.getChildCount() : 0)
        }
      }
    }
    return coor
  }
 
}
 
/*
 Helper for creating a model range correctly
 as for model/Range start should be before end.
 
 In contrast to that, DOM selections are described with anchor and focus coordinates,
 i.e. bearing the information of direction implicitly.
 To simplify the implementation we treat anchor and focus equally
 and only at the end exploit the fact deriving an isReverse flag
 and bringing start and end in the correct order.
*/
function _createRange({start, end, isReverse}) {
  Iif (isReverse) {
    [start, end] = [end, start]
  }
  Iif (!start._comp || !end._comp) {
    console.error('FIXME: getCoordinate() should provide a component instance')
    return null
  }
  let surface = start._comp.context.surface
  Iif (!surface) {
    console.error('FIXME: Editable components should have their surface in the context')
    return null
  }
  Iif (surface !== end._comp.context.surface) {
    console.error('Coordinates are within two different surfaces. Can not create a selection.')
    return null
  }
  return new Range(start, end, isReverse, surface.getContainerId(), surface.id)
}
 
export default DOMSelection