UNPKG

2.3 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2013-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 */
8
9'use strict';
10
11var _assign = require('object-assign');
12
13var PooledClass = require('./PooledClass');
14
15var getTextContentAccessor = require('./getTextContentAccessor');
16
17/**
18 * This helper class stores information about text content of a target node,
19 * allowing comparison of content before and after a given event.
20 *
21 * Identify the node where selection currently begins, then observe
22 * both its text content and its current position in the DOM. Since the
23 * browser may natively replace the target node during composition, we can
24 * use its position to find its replacement.
25 *
26 * @param {DOMEventTarget} root
27 */
28function FallbackCompositionState(root) {
29 this._root = root;
30 this._startText = this.getText();
31 this._fallbackText = null;
32}
33
34_assign(FallbackCompositionState.prototype, {
35 destructor: function () {
36 this._root = null;
37 this._startText = null;
38 this._fallbackText = null;
39 },
40
41 /**
42 * Get current text of input.
43 *
44 * @return {string}
45 */
46 getText: function () {
47 if ('value' in this._root) {
48 return this._root.value;
49 }
50 return this._root[getTextContentAccessor()];
51 },
52
53 /**
54 * Determine the differing substring between the initially stored
55 * text content and the current content.
56 *
57 * @return {string}
58 */
59 getData: function () {
60 if (this._fallbackText) {
61 return this._fallbackText;
62 }
63
64 var start;
65 var startValue = this._startText;
66 var startLength = startValue.length;
67 var end;
68 var endValue = this.getText();
69 var endLength = endValue.length;
70
71 for (start = 0; start < startLength; start++) {
72 if (startValue[start] !== endValue[start]) {
73 break;
74 }
75 }
76
77 var minEnd = startLength - start;
78 for (end = 1; end <= minEnd; end++) {
79 if (startValue[startLength - end] !== endValue[endLength - end]) {
80 break;
81 }
82 }
83
84 var sliceTail = end > 1 ? 1 - end : undefined;
85 this._fallbackText = endValue.slice(start, sliceTail);
86 return this._fallbackText;
87 }
88});
89
90PooledClass.addPoolingTo(FallbackCompositionState);
91
92module.exports = FallbackCompositionState;
\No newline at end of file