all files / ui/ TextPropertyComponent.js

70.19% Statements 113/161
58.33% Branches 56/96
76% Functions 19/25
70.19% Lines 113/161
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                                                              858× 858× 858× 858×   857× 857×           858×           848×             112× 112×         1032×   1032×                 1032× 1032×   1032×       1032×     1032×         117× 117× 117× 117×   117×     117× 117× 117×     117× 117×                                                                           3168×       1032×       1150×       1964×       982× 982×       982× 982×                       283×         117× 117×       300× 300× 300× 65×         235× 295× 250× 250× 212×         38×   45× 45× 45× 45× 45×   23×                   17×   22×                                             12× 12×         10× 10× 10× 10× 10×           12×             12× 22× 16× 16× 10× 10× 10× 10×                     12×       10× 10×                       10× 10×                                                                   10×                                            
import { diff, isNumber } from '../util'
import { DefaultDOMElement } from '../dom'
import { Coordinate } from '../model'
import Component from './Component'
import AnnotatedTextComponent from './AnnotatedTextComponent'
import CursorComponent from './CursorComponent'
import SelectionFragmentComponent from './SelectionFragmentComponent'
 
/**
  Renders a text property. Used internally by different components to render
  editable text.
 
  @class
  @component
  @extends ui/AnnotatedTextComponent
 
  @prop {String[]} path path to a text property
  @prop {String} [tagName] specifies which tag should be used - defaults to `div`
 
  @example
 
  ```js
  $$(TextProperty, {
    path: [ 'paragraph-1', 'content']
  })
  ```
*/
 
class TextPropertyComponent extends AnnotatedTextComponent {
 
  getInitialState() {
    const markersManager = this.context.markersManager
    let path = this.props.path
    let markers
    if (markersManager) {
      // register and get initial set of markers
      markersManager.register(this)
      markers = markersManager.getMarkers(path, {
        surfaceId: this.getSurfaceId(),
        containerId: this.getContainerId()
      })
    } else {
      const doc = this.getDocument()
      markers = doc.getAnnotations(path)
    }
    return {
      markers: markers
    }
  }
 
  didMount() {
    Iif (this.context.surface && this.context.surface.hasNativeSpellcheck()) {
      this.domObserver = new window.MutationObserver(this._onDomMutations.bind(this));
      this.domObserver.observe(this.el.getNativeElement(), { subtree: true, characterData: true, characterDataOldValue: true });
    }
  }
 
  dispose() {
    Eif (this.context.markersManager) {
      this.context.markersManager.deregister(this)
    }
  }
 
  render($$) {
    let path = this.getPath()
 
    let el = this._renderContent($$)
      .addClass('sc-text-property')
      .attr({
        'data-path': path.join('.')
      })
      .css({
        'white-space': 'pre-wrap'
      })
 
    Eif (!this.props.withoutBreak) {
      el.append($$('br'))
    }
    return el
  }
 
  getAnnotations() {
    Iif (this.props.markers) {
      return this.state.markers.concat(this.props.markers)
    } else {
      return this.state.markers
    }
  }
 
  _renderFragment($$, fragment) {
    let node = fragment.node
    let id = node.id
    let el
    Iif (node.type === 'cursor') {
      el = $$(CursorComponent, { collaborator: node.collaborator })
    } else Iif (node.type === 'selection-fragment') {
      el = $$(SelectionFragmentComponent, { collaborator: node.collaborator })
    } else {
      el = super._renderFragment.apply(this, arguments)
      Eif (id) {
        el.ref(id + '@' + fragment.counter)
      }
    }
    el.attr('data-offset', fragment.pos)
    return el
  }
 
  _onDomMutations(mutations) {
    // HACK: only detecting mutations that are coming from the native spell-correction
    if (mutations.length === 2 && mutations[0].target === mutations[1].target) {
      let textEl = DefaultDOMElement.unwrap(mutations[0].target)
      if (textEl) {
        this._applyTextMutation(textEl, mutations[0].oldValue)
        return
      }
    }
    // in all other cases, revert the change by rerendering
    this.rerender()
  }
 
  _applyTextMutation(textEl, oldText) {
    // find the offset
    let offset = _getCharPos(textEl, 0)
    let newText = textEl.textContent
    let changes = diff(oldText, newText, offset)
 
    let editorSession = this.context.editorSession
    let path = this.getPath()
    editorSession.transaction(function(tx) {
      changes.forEach(function(change) {
        // NOTE: atomic text replace is not supported currently
        if (change.type === 'replace') {
          tx.update(path, { type: 'delete', start: change.start, end: change.end })
          tx.update(path, { type: 'insert', start: change.start, text: change.text })
        } else {
          tx.update(path, change)
        }
      })
    })
  }
 
  getPath() {
    return this.props.path
  }
 
  getText() {
    return this.getDocument().get(this.getPath())
  }
 
  getDocument() {
    return this.props.doc ||this.context.doc
  }
 
  getSurface() {
    return this.props.surface || this.context.surface
  }
 
  getSurfaceId() {
    let surface = this.getSurface()
    return surface ? surface.id : null
  }
 
  getContainerId() {
    let surface = this.getSurface()
    return surface ? surface.getContainerId() : null
  }
 
  isEditable() {
    return this.getSurface().isEditable()
  }
 
  isReadonly() {
    return this.getSurface().isReadonly()
  }
 
  getDOMCoordinate(charPos) {
    return this._getDOMCoordinate(this.el, charPos)
  }
 
 
  _finishFragment(fragment, context, parentContext) {
    context.attr('data-length', fragment.length)
    parentContext.append(context)
  }
 
  _getDOMCoordinate(el, charPos) {
    let l
    let idx = 0
    if (charPos === 0) {
      return {
        container: el.getNativeElement(),
        offset: 0
      }
    }
    for (let child = el.getFirstChild(); child; child = child.getNextSibling(), idx++) {
      if (child.isTextNode()) {
        l = child.textContent.length
        if (l >= charPos) {
          return {
            container: child.getNativeElement(),
            offset: charPos
          }
        } else {
          charPos -= l;
        }
      } else Eif (child.isElementNode()) {
        let length = child.getAttribute('data-length')
        Eif (length) {
          l = parseInt(length, 10)
          if (l >= charPos) {
            // special handling for InlineNodes
            if (child.attr('data-inline')) {
              let nextSibling = child.getNextSibling()
              if (nextSibling && nextSibling.isTextNode()) {
                return {
                  container: nextSibling.getNativeElement(),
                  offset: 0
                }
              } else {
                return {
                  container: el.getNativeElement(),
                  offset: el.getChildIndex(child) + 1
                }
              }
            }
            return this._getDOMCoordinate(child, charPos, idx)
          } else {
            charPos -= l
          }
        } else {
          console.error('FIXME: Can not map to DOM coordinates.')
          return null
        }
      }
    }
  }
 
}
 
TextPropertyComponent.prototype._isTextPropertyComponent = true
 
 
// Helpers for DOM selection mapping
 
/*
  Used to map from DOM to model.
  Given a root element and a DOM element - which is typically somewhere inside a surface
  it tries to find the next TextProperty by walking up the DOM.
  If found it computes the character position, counting chars and using the hints, data-length and data-offset,
  rendered by the TextPropertyComponent
*/
TextPropertyComponent.getCoordinate = function(root, el, offset) {
  let context = _getPropertyContext(root, el, offset)
  if (!context) {
    return null
  }
  // in some cases we need to normalize the DOM coordinate
  // before we can use it for retrieving charPos
  // E.g. observed with #273
  let charPos = _getCharPos(context.node, context.offset)
  Eif (isNumber(charPos)) {
    let coor = new Coordinate(context.path, charPos)
    coor._comp = context.comp
    return coor
  } else {
    return null
  }
}
 
function _getPropertyContext(root, node, offset) {
  let result = {
    comp: null,
    el: null,
    path: null,
    node: node,
    offset: offset
  }
  while (node && node !== root) {
    if (node.isElementNode()) {
      let comp = Component.unwrap(node)
      if (comp && comp._isTextPropertyComponent) {
        result.comp = comp
        result.el = node
        result.path = comp.getPath()
        return result;
      }
      // we need to normalize situations where the DOM coordinate
      // is inside an inline node, which we have observed
      // can actually happen.
      Iif (node.getAttribute('data-inline')) {
        result.node = node
        if (offset > 0) {
          result.offset = 1
        }
      }
    }
    node = node.getParent()
  }
  return null
}
 
function _getCharPos(node, offset) {
  let charPos = offset
  let parent, childIdx
 
  /*
    In the following implementation we are exploiting two facts
    for optimization:
    - an element with data-path is assumed to be the text property element
    - an element with data-offset is assumed to be an annotation element
 
    Particularly, the data-offset property is helpful to get the character position
    in just one iteration.
  */
 
  parent = node.getParent()
  if (node.isTextNode()) {
    // TextNode is first child
    Eif (node === parent.firstChild) {
      // ... we can stop if parent is text property
      let parentPath = parent.getAttribute('data-path')
      let parentOffset = parent.getAttribute('data-offset')
      if (parentPath) {
        charPos = offset
      }
      // ... and we can stop if parent has an offset hint
      else Eif (parentOffset) {
        charPos = parseInt(parentOffset, 10) + offset
      }
      // ... otherwise we count the charPos by recursing up-tree
      else {
        charPos = _getCharPos(parent, 0) + offset
      }
    } else {
      // the node has a predecessor so we can apply recurse using the child index
      childIdx = parent.getChildIndex(node)
      charPos = _getCharPos(parent, childIdx) + offset
    }
  } else Eif (node.isElementNode()) {
    let pathStr = node.getAttribute('data-path')
    let offsetStr = node.getAttribute('data-offset')
    // if node is the element of a text property, then offset is a child index
    // up to which we need to sum up all lengths
    Eif (pathStr) {
      charPos = _countCharacters(node, offset)
    }
    // similar if node is the element of an annotation, and we can use the
    // element's offset
    else if (offsetStr) {
      childIdx = parent.getChildIndex(node)
      charPos = parseInt(offsetStr, 10) + _countCharacters(node, offset)
    }
    // for other elements we need to count characters in the child tree
    // adding the offset of this element which needs to be computed by recursing up-tree
    else {
      childIdx = parent.getChildIndex(node)
      charPos = _getCharPos(parent, childIdx) + _countCharacters(node, offset)
    }
  } else {
    // Unsupported case
    return null
  }
  return charPos;
}
 
function _countCharacters(el, maxIdx) {
  let charPos = 0
  // inline elements have a length of 1
  Iif (el.getAttribute('data-inline')) {
    return maxIdx === 0 ? 0 : 1;
  }
  let l = el.getChildCount()
  Iif (arguments.length === 1) {
    maxIdx = l;
  }
  maxIdx = Math.min(l, maxIdx)
  for (let i=0, child = el.getFirstChild(); i < maxIdx; child = child.getNextSibling(), i++) {
    Eif (child.isTextNode()) {
      charPos += child.getTextContent().length
    } else if (child.isElementNode()) {
      let length = child.getAttribute('data-length')
      if (child.getAttribute('data-inline')) {
        charPos += 1
      } else if (length) {
        charPos += parseInt(length, 10)
      } else {
        charPos += _countCharacters(child)
      }
    }
  }
  return charPos
}
 
export default TextPropertyComponent