all files / model/ ContainerSelection.js

85.53% Statements 130/152
84.21% Branches 64/76
77.42% Functions 24/31
87.16% Lines 129/148
9 statements, 4 functions, 4 branches Ignored     
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                                                      118×   118× 15× 15× 15× 15× 15× 15× 15× 15×           118× 118×   118× 118×   118×   118×                                       18×                         134×             334×       126×       20×                                                     110× 55×   110×           17× 16× 16× 16× 16×                     20× 20× 20× 20× 20×   20× 20× 18× 18×   20×       20× 20×   20×                                             13× 13× 12×     13×       10× 10× 10× 10×   10×     10×   10×       10×                                                     15× 15× 15× 15×                                                           130× 55×     75× 75× 75× 75×   70×   75×       75× 60×   75×                   15× 15×     29×   29× 13×               16×       29× 29× 27×   29×        
import { isNil } from '../util'
import Coordinate from './Coordinate'
import Selection from './Selection'
import PropertySelection from './PropertySelection'
 
/**
  A selection spanning multiple nodes.
 
  @class
  @extends PropertySelection
 
  @example
 
  ```js
  let containerSel = doc.createSelection({
    type: 'container',
    containerId: 'body',
    startPath: ['p1', 'content'],
    startOffset: 5,
    endPath: ['p3', 'content'],
    endOffset: 4,
  })
  ```
*/
class ContainerSelection extends Selection {
 
  constructor(containerId, startPath, startOffset, endPath, endOffset, reverse, surfaceId) {
    super()
 
    if (arguments.length === 1) {
      let data = arguments[0]
      containerId = data.containerId
      startPath = data.startPath
      startOffset = data.startOffset
      endPath = data.endPath
      endOffset = data.endOffset
      reverse = data.reverse
      surfaceId = data.surfaceId
    }
 
    /**
      @type {String}
    */
    this.containerId = containerId
    Iif (!this.containerId) throw new Error('Invalid arguments: `containerId` is mandatory')
 
    this.start = new Coordinate(startPath, startOffset)
    this.end = new Coordinate(isNil(endPath) ? startPath : endPath, isNil(endOffset) ? startOffset : endOffset)
 
    this.reverse = Boolean(reverse)
 
    this.surfaceId = surfaceId
  }
 
  /* istanbul ignore start */
 
  get startPath() {
    console.warn('DEPRECATED: use sel.start.path instead.')
    return this.start.path
  }
 
  get startOffset() {
    console.warn('DEPRECATED: use sel.start.offset instead.')
    return this.start.offset
  }
 
  get endPath() {
    console.warn('DEPRECATED: use sel.end.path instead.')
    return this.end.path
  }
 
  get endOffset() {
    console.warn('DEPRECATED: use sel.end.offset instead.')
    return this.end.offset
  }
 
  /* istanbul ignore end */
 
  toJSON() {
    return {
      type: 'container',
      containerId: this.containerId,
      startPath: this.start.path,
      startOffset: this.start.offset,
      endPath: this.end.path,
      endOffset: this.end.offset,
      reverse: this.reverse,
      surfaceId: this.surfaceId
    }
  }
 
  isContainerSelection() {
    return true
  }
 
  getType() {
    return 'container'
  }
 
  isNull() {
    return false
  }
 
  isCollapsed() {
    return this.start.equals(this.end)
  }
 
  isReverse() {
    return this.reverse
  }
 
  equals(other) {
    return (
      Selection.prototype.equals.call(this, other) &&
      this.containerId === other.containerId &&
      (this.start.equals(other.start) && this.end.equals(other.end))
    )
  }
 
  toString() {
    /* istanbul ignore next */
    return [
      "ContainerSelection(",
      this.containerId, ", ",
      JSON.stringify(this.start.path), ", ", this.start.offset,
      " -> ",
      JSON.stringify(this.end.path), ", ", this.end.offset,
      (this.reverse?", reverse":""),
      (this.surfaceId?(", "+this.surfaceId):""),
      ")"
    ].join('')
  }
 
  /**
    @return {model/Container} The container node instance for this selection.
  */
  getContainer() {
    if (!this._internal.container) {
      this._internal.container = this.getDocument().get(this.containerId)
    }
    return this._internal.container
  }
 
  isInsideOf(other, strict) {
    // Note: this gets called from PropertySelection.contains()
    // because this implementation can deal with mixed selection types.
    if (other.isNull()) return false
    strict = Boolean(strict)
    let r1 = this._range(this)
    let r2 = this._range(other)
    return (r2.start.isBefore(r1.start, strict) &&
      r1.end.isBefore(r2.end, strict))
  }
 
  contains(other, strict) {
    // Note: this gets called from PropertySelection.isInsideOf()
    // because this implementation can deal with mixed selection types.
    Iif (other.isNull()) return false
    strict = Boolean(strict)
    let r1 = this._range(this)
    let r2 = this._range(other)
    return (r1.start.isBefore(r2.start, strict) &&
      r2.end.isBefore(r1.end, strict))
  }
 
  containsNode(nodeId, strict) {
    const container = this.getContainer()
    Iif (!container.contains(nodeId)) return false
    const coor = new Coordinate([nodeId], 0)
    const address = container.getAddress(coor)
    const r = this._range(this)
    // console.log('ContainerSelection.containsNode()', address, 'is within', r.start, '->', r.end, '?')
    let contained = r.start.isBefore(address, strict)
    if (contained) {
      address.offset = 1
      contained = r.end.isAfter(address, strict)
    }
    return contained
  }
 
  overlaps(other) {
    let r1 = this._range(this)
    let r2 = this._range(other)
    // it overlaps if they are not disjunct
    return !(r1.end.isBefore(r2.start, false) ||
      r2.end.isBefore(r1.start, false))
  }
 
  isLeftAlignedWith(other) {
    let r1 = this._range(this)
    let r2 = this._range(other)
    return r1.start.isEqual(r2.start)
  }
 
  isRightAlignedWith(other) {
    let r1 = this._range(this)
    let r2 = this._range(other)
    return r1.end.isEqual(r2.end)
  }
 
  /**
    Collapse a selection to chosen direction.
 
    @param {String} direction either left of right
    @returns {PropertySelection}
  */
  collapse(direction) {
    let coor
    if (direction === 'left') {
      coor = this.start
    } else {
      coor = this.end
    }
    return _createNewSelection(this, coor, coor)
  }
 
  expand(other) {
    let r1 = this._range(this)
    let r2 = this._range(other)
    let start
    let end
 
    if (r1.start.isEqual(r2.start)) {
      start = new Coordinate(this.start.path, Math.min(this.start.offset, other.start.offset))
    } else if (r1.start.isAfter(r2.start)) {
      start = new Coordinate(other.start.path, other.start.offset)
    } else {
      start = this.start
    }
    Iif (r1.end.isEqual(r2.end)) {
      end = new Coordinate(this.end.path, Math.max(this.end.offset, other.end.offset))
    } else if (r1.end.isBefore(r2.end, false)) {
      end = new Coordinate(other.end.path, other.end.offset)
    } else {
      end = this.end
    }
 
    return _createNewSelection(this, start, end)
  }
 
  truncateWith(other) {
    Iif (other.isInsideOf(this, 'strict')) {
      // the other selection should overlap only on one side
      throw new Error('Can not truncate with a contained selections')
    }
    Iif (!this.overlaps(other)) {
      return this
    }
    let r1 = this._range(this)
    let r2 = this._range(other)
    let start, end
    if (r2.start.isBefore(r1.start, 'strict') && r2.end.isBefore(r1.end, 'strict')) {
      start = other.end
      end = this.end
    } else if (r1.start.isBefore(r2.start, 'strict') && r1.end.isBefore(r2.end, 'strict')) {
      start = this.start
      end = other.start
    } else if (r1.start.isEqual(r2.start)) {
      if (r2.end.isBefore(r1.end, 'strict')) {
        start = other.end
        end = this.end
      } else {
        // the other selection is larger which eliminates this one
        return Selection.nullSelection
      }
    } else if (r1.end.isEqual(r2.end)) {
      Eif (r1.start.isBefore(r2.start, 'strict')) {
        start = this.start
        end = other.start
      } else {
        // the other selection is larger which eliminates this one
        return Selection.nullSelection
      }
    } else Eif (this.isInsideOf(other)) {
      return Selection.nullSelection
    } else {
      throw new Error('Could not determine coordinates for truncate. Check input')
    }
    return _createNewSelection(this, start, end)
  }
 
  /**
    Get the node ids covered by this selection.
 
    @returns {String[]} an array of ids
  */
  getNodeIds() {
    const container = this.getContainer()
    const startPos = container.getPosition(this.start.path[0])
    const endPos = container.getPosition(this.end.path[0])
    return container.nodes.slice(startPos, endPos+1)
  }
 
  /**
    Splits a container selection into property selections.
 
    @returns {PropertySelection[]}
  */
  splitIntoPropertySelections() {
    let sels = []
    let fragments = this.getFragments()
    fragments.forEach(function(fragment) {
      if (fragment instanceof Selection.Fragment) {
        sels.push(
          new PropertySelection(fragment.path, fragment.startOffset,
            fragment.endOffset, false, this.containerId, this.surfaceId)
        )
      }
    }.bind(this))
    return sels
  }
 
  _clone() {
    return new ContainerSelection(this)
  }
 
  _range(sel) {
    // EXPERIMENTAL: caching the internal address based range
    // as we use it very often.
    // However, this is dangerous as this data can get invalid by a change
    if (sel._internal.addressRange) {
      return sel._internal.addressRange
    }
 
    let container = this.getContainer()
    let startAddress = container.getAddress(sel.start)
    let endAddress
    if (sel.isCollapsed()) {
      endAddress = startAddress
    } else {
      endAddress = container.getAddress(sel.end)
    }
    let addressRange = {
      start: startAddress,
      end: endAddress
    }
    if (sel._isContainerSelection) {
      sel._internal.addressRange = addressRange
    }
    return addressRange
  }
 
  get path() {
    throw new Error('ContainerSelection has no path property. Use startPath and endPath instead')
  }
 
}
 
ContainerSelection.prototype._isContainerSelection = true
 
ContainerSelection.fromJSON = function(properties) {
  let sel = new ContainerSelection(properties)
  return sel
}
 
function _createNewSelection(containerSel, start, end) {
  let newSel
 
  if (start === end) {
    newSel = new PropertySelection({
      path: start.path,
      startOffset: start.offset,
      endOffset: start.offset,
      containerId: containerSel.containerId,
      surfaceId: containerSel.surfaceId
    })
  } else {
    newSel = new ContainerSelection(containerSel.containerId,
    start.path, start.offset, end.path, end.offset, false, containerSel.surfaceId)
  }
  // we need to attach the new selection
  const doc = containerSel._internal.doc
  if (doc) {
    newSel.attach(doc)
  }
  return newSel
}
 
export default ContainerSelection