all files / model/data/ Data.js

55.35% Statements 88/159
47.78% Branches 43/90
85% Functions 17/20
56.86% Lines 87/153
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                                      1067×   1067× 1067× 1067× 1067× 1067×   1067×       1067× 1067×                 6064×                   30941× 30941×                 30941×       30941× 30941× 30941× 25785× 5156×   5156× 5156× 5156× 33× 33×   5156× 5146×   30931×                 3836×                 5297× 5297×     5297×     5297×     5297×   5297×         5297×   5289×     5297×                   175× 175× 175× 175×   175×         175×   173×     175×                     420× 420× 420×             420×     420×   420×       420× 420×                                                                                                                                                                             1321×   212×             212×               1109×   1102×           1102×                             1321×                                                                         3407×     3407× 3407× 3407×                   4259×                 5892× 5892× 18762× 8166×     8166×                                     10× 10×           420× 420× 420× 452× 452×   420× 420× 420×        
import isArray from '../../util/isArray'
import isString from '../../util/isString'
import EventEmitter from '../../util/EventEmitter'
import forEach from '../../util/forEach'
import NodeFactory from './NodeFactory'
 
/*
  A data storage implemention that supports data defined via a {@link Schema},
  and incremental updates which are backed by a OT library.
 
  It forms the underlying implementation for {@link Document}.
 */
class Data extends EventEmitter {
 
  /**
    @param {Schema} schema
    @param {Object} [options]
  */
  constructor(schema, options) {
    super()
 
    options = options || {}
    this.schema = schema
    this.nodes = {}
    this.indexes = {}
    this.options = options || {}
 
    this.nodeFactory = options.nodeFactory || new NodeFactory(schema.nodeRegistry)
 
    // Sometimes necessary to resolve issues with updating indexes in presence
    // of cyclic dependencies
    this.__QUEUE_INDEXING__ = false
    this.queue = []
  }
 
  /**
    Check if this storage contains a node with given id.
 
    @returns {bool} `true` if a node with id exists, `false` otherwise.
   */
  contains(id) {
    return Boolean(this.nodes[id])
  }
 
  /**
    Get a node or value via path.
 
    @param {String|String[]} path node id or path to property.
    @returns {Node|Object|Primitive|undefined} a Node instance, a value or undefined if not found.
   */
  get(path, strict) {
    let result = this._get(path)
    Iif (strict && result === undefined) {
      if (isString(path)) {
        throw new Error("Could not find node with id '"+path+"'.")
      } else if (!this.contains(path[0])) {
        throw new Error("Could not find node with id '"+path[0]+"'.")
      } else {
        throw new Error("Property for path '"+path+"' us undefined.")
      }
    }
    return result
  }
 
  _get(path) {
    Iif (!path) return undefined
    let result
    if (isString(path)) {
      result = this.nodes[path]
    } else Iif (path.length === 1) {
      result = this.nodes[path[0]]
    } else Eif (path.length > 1) {
      let context = this.nodes[path[0]]
      for (let i = 1; i < path.length-1; i++) {
        Iif (!context) return undefined
        context = context[path[i]]
      }
      if (!context) return undefined
      result = context[path[path.length-1]]
    }
    return result
  }
 
  /**
    Get the internal storage for nodes.
 
    @return The internal node storage.
   */
  getNodes() {
    return this.nodes
  }
 
  /**
    Create a node from the given data.
 
    @return {Node} The created node.
   */
  create(nodeData) {
    var node = this.nodeFactory.create(nodeData.type, nodeData)
    Iif (!node) {
      throw new Error('Illegal argument: could not create node for data:', nodeData)
    }
    Iif (this.contains(node.id)) {
      throw new Error("Node already exists: " + node.id)
    }
    Iif (!node.id || !node.type) {
      throw new Error("Node id and type are mandatory.")
    }
    this.nodes[node.id] = node
 
    var change = {
      type: 'create',
      node: node
    }
 
    if (this.__QUEUE_INDEXING__) {
      this.queue.push(change)
    } else {
      this._updateIndexes(change)
    }
 
    return node
  }
 
  /**
    Delete the node with given id.
 
    @param {String} nodeId
    @returns {Node} The deleted node.
   */
  delete(nodeId) {
    var node = this.nodes[nodeId]
    Iif (!node) return
    node.dispose()
    delete this.nodes[nodeId]
 
    var change = {
      type: 'delete',
      node: node,
    }
 
    if (this.__QUEUE_INDEXING__) {
      this.queue.push(change)
    } else {
      this._updateIndexes(change)
    }
 
    return node
  }
 
  /**
    Set a property to a new value.
 
    @param {Array} property path
    @param {Object} newValue
    @returns {Node} The deleted node.
   */
  set(path, newValue) {
    let node = this.get(path[0])
    let oldValue = this._set(path, newValue)
    var change = {
      type: 'set',
      node: node,
      path: path,
      newValue: newValue,
      oldValue: oldValue
    }
    Iif (this.__QUEUE_INDEXING__) {
      this.queue.push(change)
    } else {
      this._updateIndexes(change)
    }
    return oldValue
  }
 
  _set(path, newValue) {
    let oldValue = _setValue(this.nodes, path, newValue)
    return oldValue
  }
 
  /**
    Update a property incrementally.
 
    @param {Array} property path
    @param {Object} diff
    @returns {any} The value before applying the update.
  */
  update(path, diff) {
    var realPath = this.getRealPath(path)
    if (!realPath) {
      console.error('Could not resolve path', path)
      return
    }
    let node = this.get(realPath[0])
    let oldValue = this._get(realPath)
    let newValue
    if (diff.isOperation) {
      newValue = diff.apply(oldValue)
    } else {
      diff = this._normalizeDiff(oldValue, diff)
      if (isString(oldValue)) {
        switch (diff.type) {
          case 'delete': {
            newValue = oldValue.split('').splice(diff.start, diff.end-diff.start).join('')
            break
          }
          case 'insert': {
            newValue = [oldValue.substring(0, diff.start), diff.text, oldValue.substring(diff.start)].join('')
            break
          }
          default:
            throw new Error('Unknown diff type')
        }
      } else if (isArray(oldValue)) {
        newValue = oldValue.slice(0)
        switch (diff.type) {
          case 'delete': {
            newValue.splice(diff.pos, 1)
            break
          }
          case 'insert': {
            newValue.splice(diff.pos, 0, diff.value)
            break
          }
          default:
            throw new Error('Unknown diff type')
        }
      } else if (oldValue._isCoordinate) {
        switch (diff.type) {
          case 'shift': {
            // ATTENTION: in this case we do not want to create a new value
            oldValue = { path: oldValue.path, offset: oldValue.offset }
            newValue = oldValue
            newValue.offset += diff.value
            break
          }
          default:
            throw new Error('Unknown diff type')
        }
      } else {
        throw new Error('Diff is not supported:', JSON.stringify(diff))
      }
    }
    this._set(realPath, newValue)
 
    var change = {
      type: 'update',
      node: node,
      path: realPath,
      newValue: newValue,
      oldValue: oldValue
    }
 
    if (this.__QUEUE_INDEXING__) {
      this.queue.push(change)
    } else {
      this._updateIndexes(change)
    }
 
    return oldValue
  }
 
  // normalize to support legacy formats
  _normalizeDiff(value, diff) {
    if (isString(value)) {
      // legacy
      Iif (diff['delete']) {
        console.warn('DEPRECATED: use doc.update(path, {type:"delete", start:s, end: e}) instead')
        diff = {
          type: 'delete',
          start: diff['delete'].start,
          end: diff['delete'].end
        }
      } else Iif (diff['insert']) {
        console.warn('DEPRECATED: use doc.update(path, {type:"insert", start:s, text: t}) instead')
        diff = {
          type: 'insert',
          start: diff['insert'].offset,
          text: diff['insert'].value
        }
      }
    } else if (isArray(value)) {
      // legacy
      Iif (diff['delete']) {
        console.warn('DEPRECATED: use doc.update(path, {type:"delete", pos:1}) instead')
        diff = {
          type: 'delete',
          pos: diff['delete'].offset
        }
      } else Iif (diff['insert']) {
        console.warn('DEPRECATED: use doc.update(path, {type:"insert", pos:1, value: "foo"}) instead')
        diff = {
          type: 'insert',
          pos: diff['insert'].offset,
          value: diff['insert'].value
        }
      }
    } else Eif (value._isCoordinate) {
      Iif (diff.hasOwnProperty('shift')) {
        console.warn('DEPRECATED: use doc.update(path, {type:"shift", value:2}) instead')
        diff = {
          type: 'shift',
          value: diff['shift']
        }
      }
    }
    return diff
  }
 
  /*
    DEPRECATED: We moved away from having JSON as first-class exchange format.
    We will remove this soon.
 
    @internal
    @deprecated
   */
  toJSON() {
    let nodes = {}
    forEach(this.nodes, (node)=>{
      nodes[node.id] = node.toJSON()
    })
    return {
      schema: [this.schema.id, this.schema.version],
      nodes: nodes
    }
  }
 
  /**
    Clear nodes.
 
    @internal
   */
  reset() {
    this.nodes.clear()
  }
 
  /**
    Add a node index.
 
    @param {String} name
    @param {NodeIndex} index
   */
  addIndex(name, index) {
    Iif (this.indexes[name]) {
      console.error('Index with name %s already exists.', name)
    }
    index.reset(this)
    this.indexes[name] = index
    return index
  }
 
  /**
    Get the node index with given name.
 
    @param {String} name
    @returns {NodeIndex} The node index.
   */
  getIndex(name) {
    return this.indexes[name]
  }
 
  /**
    Update a node index by providing of change object.
 
    @param {Object} change
   */
  _updateIndexes(change) {
    Iif (!change || this.__QUEUE_INDEXING__) return
    forEach(this.indexes, function(index) {
      if (index.select(change.node)) {
        Iif (!index[change.type]) {
          console.error('Contract: every NodeIndex must implement ' + change.type)
        }
        index[change.type](change.node, change.path, change.newValue, change.oldValue)
      }
    })
  }
 
  /**
    Stops indexing process, all changes will be collected in indexing queue.
 
    @private
  */
  _stopIndexing() {
    this.__QUEUE_INDEXING__ = true
  }
 
  /**
    Update all index changes from indexing queue.
 
    @private
  */
  _startIndexing() {
    this.__QUEUE_INDEXING__ = false
    while(this.queue.length >0) {
      var change = this.queue.shift()
      this._updateIndexes(change)
    }
  }
 
}
 
function _setValue(root, path, newValue) {
  let ctx = root
  let L = path.length
  for (let i = 0; i < L-1; i++) {
    ctx = ctx[path[i]]
    Iif (!ctx) throw new Error('Can not set value.')
  }
  let oldValue = ctx[path[L-1]]
  ctx[path[L-1]] = newValue
  return oldValue
}
 
export default Data