all files / ui/ MarkersManager.js

50.31% Statements 80/159
35.8% Branches 29/81
76.19% Functions 16/21
52.32% Lines 79/151
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          206×     206× 206×   206×   206× 206×                 857×   857× 857× 791×   857×       112×   112× 112×       112× 112× 40×         982× 982× 982× 982× 982×       557×   161× 161× 161× 473×     161×         557× 473× 473× 125×     557×       125× 125×         125×                         206× 206× 206× 206× 206×   206×   206× 206×                     206× 206× 206× 206× 206× 936×             1967×                                                                                                         1475× 1475×         1475×       161× 161× 161×         1246× 1246×           1246×       161× 161× 1246× 1246× 163× 163×   97× 97×   66× 66×                 97× 97× 97× 94×                                             66× 66× 66× 66× 66×                                                                                  
import { forEach, deleteFromArray, ArrayTree } from '../util'
 
class MarkersManager {
 
  constructor(editorSession) {
    this.editorSession = editorSession
 
    // registry
    this._textProperties = {}
    this._dirtyProps = {}
 
    this._markers = new MarkersIndex(editorSession)
 
    editorSession.onUpdate(this._onChange, this)
    editorSession.onRender(this._updateProperties, this)
  }
 
  dispose() {
    this.editorSession.off(this)
    this._markers.dispose()
  }
 
  register(textProperyComponent) {
    let path = String(textProperyComponent.getPath())
    // console.log('registering property', path)
    let textProperties = this._textProperties[path]
    if (!textProperties) {
      textProperties = this._textProperties[path] = []
    }
    textProperties.push(textProperyComponent)
  }
 
  deregister(textProperyComponent) {
    let path = String(textProperyComponent.getPath())
    // console.log('deregistering property', path)
    let textProperties = this._textProperties[path]
    Iif (!textProperties) {
      // FIXME: happens in test suite
      return
    }
    deleteFromArray(this._textProperties[path], textProperyComponent)
    if (textProperties.length === 0) {
      delete this._textProperties[path]
    }
  }
 
  getMarkers(path, opts) {
    opts = opts || {}
    let doc = this.editorSession.getDocument()
    let annos = doc.getAnnotations(path) || []
    let markers = this._markers.get(path, opts.surfaceId, opts.containerId)
    return annos.concat(markers)
  }
 
  _onChange(editorSession) {
    if (editorSession.hasDocumentChanged()) {
      // mark all updated props per se as dirty
      Eif (editorSession.hasDocumentChanged()) {
        let change = editorSession.getChange()
        forEach(change.updated, (val, id) => {
          this._dirtyProps[id] = true
        })
      }
      Object.assign(this._dirtyProps, this._markers._collectDirtyProps())
    }
  }
 
  _updateProperties() {
    Object.keys(this._dirtyProps).forEach((path) => {
      let textProperties = this._textProperties[path]
      if (textProperties) {
        textProperties.forEach(this._updateTextProperty.bind(this))
      }
    })
    this._dirtyProps = {}
  }
 
  _updateTextProperty(textPropertyComponent) {
    let path = textPropertyComponent.getPath()
    let markers = this.getMarkers(path, {
      surfaceId: textPropertyComponent.getSurfaceId(),
      containerId: textPropertyComponent.getContainerId()
    })
    // console.log('## providing %s markers for %s', markers.length, path)
    textPropertyComponent.setState({
      markers: markers
    })
  }
 
}
 
/*
  A DocumentIndex implementation for keeping track of markers
*/
class MarkersIndex {
 
  constructor(editorSession) {
    this.editorSession = editorSession
    this.document = editorSession.getDocument()
    this._documentMarkers = new ArrayTree()
    this._surfaceMarkers = {}
    this._containerMarkers = {}
 
    this._dirtyProps = {}
 
    this.document.addIndex('markers', this)
    editorSession.onUpdate('document', this._onDocumentChange, this)
  }
 
  dispose() {
    // TODO: add an API to remove a custom index
    // and we should add a test which disposes the editor session
    delete this.document.data.indexes['markers']
    this.editorSession.off(this)
  }
 
  reset() {
    this._documentMarkers = new ArrayTree()
    this._surfaceMarkers = {}
    this._containerMarkers = {}
    let doc = this.document
    forEach(doc.getNodes(), (node) => {
      Iif (this.select(node)) {
        this.create(node)
      }
    })
  }
 
  select(node) {
    return node._isMarker
  }
 
  create(marker) {
    // console.log('Indexing marker', marker)
    switch (marker.constructor.scope) {
      case 'document': {
        this._dirtyProps[marker.path] = true
        this._documentMarkers.add(marker.path, marker)
        break
      }
      case 'surface': {
        if (!this._surfaceMarkers[marker.surfaceId]) {
          this._surfaceMarkers[marker.surfaceId] = new ArrayTree()
        }
        this._dirtyProps[marker.path] = true
        this._surfaceMarkers[marker.surfaceId].add(marker.path, marker)
        break
      }
      case 'container': {
        console.warn('Container scoped markers are not supported yet')
        break
      }
      default:
        console.error('Invalid marker scope.')
    }
  }
 
  delete(marker) {
    switch (marker.constructor.scope) {
      case 'document': {
        this._dirtyProps[marker.path] = true
        this._documentMarkers.remove(marker.path, marker)
        break
      }
      case 'surface': {
        if (!this._surfaceMarkers[marker.surfaceId]) {
          this._surfaceMarkers[marker.surfaceId] = new ArrayTree()
        }
        this._dirtyProps[marker.path] = true
        this._surfaceMarkers[marker.surfaceId].remove(marker.path, marker)
        break
      }
      case 'container': {
        console.warn('Container scoped markers are not supported yet')
        break
      }
      default:
        console.error('Invalid marker scope.')
    }
  }
 
  get(path, surfaceId) {
    let markers = this._documentMarkers[path] || []
    Iif (surfaceId && this._surfaceMarkers[surfaceId]) {
      let surfaceMarkers = this._surfaceMarkers[surfaceId][path]
      if (surfaceMarkers) markers = markers.concat(surfaceMarkers)
    }
    // TODO support container scoped markers
    return markers
  }
 
  _collectDirtyProps() {
    let dirtyProps = this._dirtyProps
    this._dirtyProps = {}
    return dirtyProps
  }
 
  // used for applying transformations
  _getAllCustomMarkers(path) {
    let markers = this._documentMarkers[path] || []
    for(let surfaceId in this._surfaceMarkers) {
      if (!this._surfaceMarkers.hasOwnProperty(surfaceId)) continue
      let surfaceMarkers = this._surfaceMarkers[surfaceId][path]
      if (surfaceMarkers) markers = markers.concat(surfaceMarkers)
    }
    // TODO: support container markers
    return markers
  }
 
  _onDocumentChange(change) {
    let doc = this.doc
    change.ops.forEach((op) => {
      let markers = this._getAllCustomMarkers(op.path)
      if (op.type === 'update' && op.diff._isTextOperation) {
        let diff = op.diff
        switch (diff.type) {
          case 'insert':
            this._transformInsert(doc, markers, diff)
            break
          case 'delete':
            this._transformDelete(doc, markers, diff)
            break
          default:
            //
        }
      }
    })
  }
 
  _transformInsert(doc, markers, op) {
    const pos = op.pos
    const length = op.str.length
    if (length === 0) return
    markers.forEach(function(marker) {
      // console.log('Transforming marker after insert')
      var start = marker.start.offset;
      var end = marker.end.offset;
      var newStart = start;
      var newEnd = end;
      if (pos >= end) return
      if (pos <= start) {
        newStart += length
        newEnd += length
        marker.start.offset = newStart
        marker.end.offset = newEnd
        return
      }
      if (pos < end) {
        newEnd += length;
        marker.end.offset = newEnd
        if (marker.invalidate) marker.invalidate()
      }
    })
  }
 
  _transformDelete(doc, markers, op) {
    const pos1 = op.pos
    const length = op.str.length
    const pos2 = pos1 + length
    Iif (pos1 === pos2) return
    markers.forEach((marker) => {
      var start = marker.start.offset;
      var end = marker.end.offset;
      var newStart = start;
      var newEnd = end;
      if (pos2 <= start) {
        newStart -= length;
        newEnd -= length;
        marker.start.offset = newStart
        marker.end.offset = newEnd
      } else if (pos1 >= end) {
        // nothing
      }
      // the marker needs to be changed
      // now, there might be cases where the marker gets invalid, such as a spell-correction
      else {
        if (pos1 <= start) {
          newStart = start - Math.min(pos2-pos1, start-pos1);
        }
        if (pos1 <= end) {
          newEnd = end - Math.min(pos2-pos1, end-pos1);
        }
        // TODO: we should do something special when the change occurred inside the marker
        if (start !== end && newStart === newEnd) {
          marker.remove()
          return
        }
        if (start !== newStart) {
          marker.start.offset = newStart
        }
        if (end !== newEnd) {
          marker.end.offset = newEnd
        }
        if (marker.invalidate) marker.invalidate()
      }
    })
  }
 
}
 
export default MarkersManager