all files / ui/ Highlights.js

0% Statements 0/20
0% Branches 0/6
0% Functions 0/6
0% Lines 0/20
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                                                                                                                                                                                   
import { forEach, EventEmitter, without } from '../util'
 
/*
  Manages highlights. Used by {@link ui/ScrollPane}.
 
  @class
 
  @param {model/Document} doc document instance
 
  @example
 
  ```
  var contentHighlights = new Highlights(doc);
  ```
*/
 
class Highlights extends EventEmitter {
  constructor(doc) {
    super()
 
    this.doc = doc
    this._highlights = {}
  }
 
  /**
    Get currently active highlights.
 
    @return {Object} Returns current highlights as a scoped object.
  */
  get() {
    return this._highlights
  }
 
  /**
    Set highlights.
 
    @param {Object} scoped object describing highlights
 
    @example
 
    ```js
      highlights.set({
        'figures': ['figure-1', 'figure-3']
        'citations': ['citation-1', 'citation-5']
      });
    ```
  */
  set(highlights) {
    let oldHighlights = this._highlights
    let doc = this.doc
    // Iterate over scopes of provided highlights
    forEach(highlights, function(newScopedHighlights, scope) {
      let oldScopedHighlights = oldHighlights[scope] || []
 
      // old [1,2,3]  -> new [2,4,5]
      // toBeDeleted: [1,3]
      // toBeAdded:   [4,5]
      let toBeDeleted = without(oldScopedHighlights, newScopedHighlights)
      let toBeAdded = without(newScopedHighlights, oldScopedHighlights)
 
      // if (scopedHighlights) {
      forEach(toBeDeleted, function(nodeId) {
        let node = doc.get(nodeId)
        // Node could have been deleted in the meanwhile
        if (node) {
          node.setHighlighted(false, scope)
        }
      });
 
      forEach(toBeAdded, function(nodeId) {
        let node = doc.get(nodeId)
        if (node) {
          node.setHighlighted(true, scope)
        }
      })
    })
 
    this._highlights = highlights
 
    /**
      Emitted when highlights have been updated
 
      @event ui/Highlights@highlights:updated
    */
    this.emit('highlights:updated', highlights)
  }
}
 
export default Highlights