1 | exports.onStringInsert = onStringInsert;
|
2 | exports.onStringRemove = onStringRemove;
|
3 | exports.onTextInput = onTextInput;
|
4 |
|
5 | function onStringInsert(el, previous, index, text) {
|
6 | function transformCursor(cursor) {
|
7 | return (index < cursor) ? cursor + text.length : cursor;
|
8 | }
|
9 | previous || (previous = '');
|
10 | var newText = previous.slice(0, index) + text + previous.slice(index);
|
11 | replaceText(el, newText, transformCursor);
|
12 | }
|
13 |
|
14 | function onStringRemove(el, previous, index, howMany) {
|
15 | function transformCursor(cursor) {
|
16 | return (index < cursor) ? cursor - Math.min(howMany, cursor - index) : cursor;
|
17 | }
|
18 | previous || (previous = '');
|
19 | var newText = previous.slice(0, index) + previous.slice(index + howMany);
|
20 | replaceText(el, newText, transformCursor);
|
21 | }
|
22 |
|
23 | function replaceText(el, newText, transformCursor) {
|
24 | var selectionStart = transformCursor(el.selectionStart);
|
25 | var selectionEnd = transformCursor(el.selectionEnd);
|
26 |
|
27 | var scrollTop = el.scrollTop;
|
28 | el.value = newText;
|
29 | if (el.scrollTop !== scrollTop) {
|
30 | el.scrollTop = scrollTop;
|
31 | }
|
32 | if (document.activeElement === el) {
|
33 | el.selectionStart = selectionStart;
|
34 | el.selectionEnd = selectionEnd;
|
35 | }
|
36 | }
|
37 |
|
38 | function onTextInput(model, segments, value) {
|
39 | var previous = model._get(segments) || '';
|
40 | if (previous === value) return;
|
41 | var start = 0;
|
42 | while (previous.charAt(start) === value.charAt(start)) {
|
43 | start++;
|
44 | }
|
45 | var end = 0;
|
46 | while (
|
47 | previous.charAt(previous.length - 1 - end) === value.charAt(value.length - 1 - end) &&
|
48 | end + start < previous.length &&
|
49 | end + start < value.length
|
50 | ) {
|
51 | end++;
|
52 | }
|
53 |
|
54 | if (previous.length !== start + end) {
|
55 | var howMany = previous.length - start - end;
|
56 | model._stringRemove(segments, start, howMany);
|
57 | }
|
58 | if (value.length !== start + end) {
|
59 | var inserted = value.slice(start, value.length - end);
|
60 | model._stringInsert(segments, start, inserted);
|
61 | }
|
62 | }
|