textAreaInput.ts 20.4 KB
Newer Older
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

J
Johannes Rieken 已提交
7
import { RunOnceScheduler } from 'vs/base/common/async';
8 9
import { Position } from 'vs/editor/common/core/position';
import { Selection } from 'vs/editor/common/core/selection';
A
Alex Dima 已提交
10
import * as strings from 'vs/base/common/strings';
J
Johannes Rieken 已提交
11 12 13
import Event, { Emitter } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
14
import { ITypeData, TextAreaState, ITextAreaWrapper } from 'vs/editor/browser/controller/textAreaState';
15
import * as browser from 'vs/base/browser/browser';
16
import * as platform from 'vs/base/common/platform';
A
Alex Dima 已提交
17
import * as dom from 'vs/base/browser/dom';
18 19
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
20

21
export interface ICompositionData {
22 23
	data: string;
}
24 25 26 27

export const CopyOptions = {
	forceCopyWithSyntaxHighlighting: false
};
28

A
Alex Dima 已提交
29
const enum ReadFromTextArea {
30 31 32 33
	Type,
	Paste
}

34 35 36 37
export interface IPasteData {
	text: string;
}

38
export interface ITextAreaInputHost {
A
Alex Dima 已提交
39 40
	getPlainTextToCopy(): string;
	getHTMLToCopy(): string;
41
	getScreenReaderContent(currentState: TextAreaState): TextAreaState;
42
	deduceModelPosition(viewAnchorPosition: Position, deltaOffset: number, lineFeedCnt: number): Position;
A
Alex Dima 已提交
43 44
}

45 46 47 48 49 50 51 52 53
/**
 * Writes screen reader content to the textarea and is able to analyze its input events to generate:
 *  - onCut
 *  - onPaste
 *  - onType
 *
 * Composition events are generated for presentation purposes (composition input is reflected in onType).
 */
export class TextAreaInput extends Disposable {
54

55 56 57 58 59 60
	private _onFocus = this._register(new Emitter<void>());
	public onFocus: Event<void> = this._onFocus.event;

	private _onBlur = this._register(new Emitter<void>());
	public onBlur: Event<void> = this._onBlur.event;

61 62
	private _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
	public onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
63

64 65
	private _onKeyUp = this._register(new Emitter<IKeyboardEvent>());
	public onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
66 67 68 69 70 71 72 73 74 75

	private _onCut = this._register(new Emitter<void>());
	public onCut: Event<void> = this._onCut.event;

	private _onPaste = this._register(new Emitter<IPasteData>());
	public onPaste: Event<IPasteData> = this._onPaste.event;

	private _onType = this._register(new Emitter<ITypeData>());
	public onType: Event<ITypeData> = this._onType.event;

A
Alex Dima 已提交
76 77
	private _onCompositionStart = this._register(new Emitter<void>());
	public onCompositionStart: Event<void> = this._onCompositionStart.event;
78

79 80
	private _onCompositionUpdate = this._register(new Emitter<ICompositionData>());
	public onCompositionUpdate: Event<ICompositionData> = this._onCompositionUpdate.event;
81

A
Alex Dima 已提交
82 83
	private _onCompositionEnd = this._register(new Emitter<void>());
	public onCompositionEnd: Event<void> = this._onCompositionEnd.event;
84

85 86 87
	private _onSelectionChangeRequest = this._register(new Emitter<Selection>());
	public onSelectionChangeRequest: Event<Selection> = this._onSelectionChangeRequest.event;

A
Alex Dima 已提交
88
	// ---
89

90
	private readonly _host: ITextAreaInputHost;
A
Alex Dima 已提交
91 92
	private readonly _textArea: TextAreaWrapper;
	private readonly _asyncTriggerCut: RunOnceScheduler;
93

A
Alex Dima 已提交
94
	private _textAreaState: TextAreaState;
95

96 97
	private _hasFocus: boolean;
	private _isDoingComposition: boolean;
98 99
	private _nextCommand: ReadFromTextArea;

100
	constructor(host: ITextAreaInputHost, textArea: FastDomNode<HTMLTextAreaElement>) {
101
		super();
A
Alex Dima 已提交
102 103 104 105
		this._host = host;
		this._textArea = this._register(new TextAreaWrapper(textArea));
		this._asyncTriggerCut = this._register(new RunOnceScheduler(() => this._onCut.fire(), 0));

A
Alex Dima 已提交
106
		this._textAreaState = TextAreaState.EMPTY;
107
		this.writeScreenReaderContent('ctor');
108

109 110
		this._hasFocus = false;
		this._isDoingComposition = false;
A
Alex Dima 已提交
111
		this._nextCommand = ReadFromTextArea.Type;
112

A
Alex Dima 已提交
113
		this._register(dom.addStandardDisposableListener(textArea.domNode, 'keydown', (e: IKeyboardEvent) => {
114
			if (this._isDoingComposition && e.keyCode === KeyCode.KEY_IN_COMPOSITION) {
A
Alex Dima 已提交
115 116 117
				// Stop propagation for keyDown events if the IME is processing key input
				e.stopPropagation();
			}
118

A
Alex Dima 已提交
119 120 121 122 123 124 125
			if (e.equals(KeyCode.Escape)) {
				// Prevent default always for `Esc`, otherwise it will generate a keypress
				// See https://msdn.microsoft.com/en-us/library/ie/ms536939(v=vs.85).aspx
				e.preventDefault();
			}
			this._onKeyDown.fire(e);
		}));
126

A
Alex Dima 已提交
127 128 129
		this._register(dom.addStandardDisposableListener(textArea.domNode, 'keyup', (e: IKeyboardEvent) => {
			this._onKeyUp.fire(e);
		}));
130

A
Alex Dima 已提交
131
		this._register(dom.addDisposableListener(textArea.domNode, 'compositionstart', (e: CompositionEvent) => {
A
Alex Dima 已提交
132
			if (this._isDoingComposition) {
A
Alex Dima 已提交
133 134
				return;
			}
A
Alex Dima 已提交
135
			this._isDoingComposition = true;
A
Alex Dima 已提交
136 137

			// In IE we cannot set .value when handling 'compositionstart' because the entire composition will get canceled.
138
			if (!browser.isEdgeOrIE) {
A
Alex Dima 已提交
139
				this._setAndWriteTextAreaState('compositionstart', TextAreaState.EMPTY);
A
Alex Dima 已提交
140
			}
141

A
Alex Dima 已提交
142
			this._onCompositionStart.fire();
143 144
		}));

A
Alex Dima 已提交
145 146 147
		/**
		 * Deduce the typed input from a text area's value and the last observed state.
		 */
148
		const deduceInputFromTextAreaValue = (couldBeEmojiInput: boolean): [TextAreaState, ITypeData] => {
A
Alex Dima 已提交
149 150
			const oldState = this._textAreaState;
			const newState = this._textAreaState.readFromTextArea(this._textArea);
151
			return [newState, TextAreaState.deduceInput(oldState, newState, couldBeEmojiInput)];
A
Alex Dima 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
		};

		/**
		 * Deduce the composition input from a string.
		 */
		const deduceComposition = (text: string): [TextAreaState, ITypeData] => {
			const oldState = this._textAreaState;
			const newState = TextAreaState.selectedText(text);
			const typeInput: ITypeData = {
				text: newState.value,
				replaceCharCnt: oldState.selectionEnd - oldState.selectionStart
			};
			return [newState, typeInput];
		};

A
Alex Dima 已提交
167
		this._register(dom.addDisposableListener(textArea.domNode, 'compositionupdate', (e: CompositionEvent) => {
168
			if (browser.isChromev56) {
169
				// See https://github.com/Microsoft/monaco-editor/issues/320
170
				// where compositionupdate .data is broken in Chrome v55 and v56
171
				// See https://bugs.chromium.org/p/chromium/issues/detail?id=677050#c9
172 173 174
				// The textArea doesn't get the composition update yet, the value of textarea is still obsolete
				// so we can't correct e at this moment.
				return;
175
			}
176

177
			if (browser.isEdgeOrIE && e.locale === 'ja') {
178 179 180 181
				// https://github.com/Microsoft/monaco-editor/issues/339
				// Multi-part Japanese compositions reset cursor in Edge/IE, Chinese and Korean IME don't have this issue.
				// The reason that we can't use this path for all CJK IME is IE and Edge behave differently when handling Korean IME,
				// which breaks this path of code.
182
				const [newState, typeInput] = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/false);
A
Alex Dima 已提交
183
				this._textAreaState = newState;
184 185 186 187 188
				this._onType.fire(typeInput);
				this._onCompositionUpdate.fire(e);
				return;
			}

A
Alex Dima 已提交
189 190
			const [newState, typeInput] = deduceComposition(e.data);
			this._textAreaState = newState;
191
			this._onType.fire(typeInput);
192 193 194
			this._onCompositionUpdate.fire(e);
		}));

A
Alex Dima 已提交
195
		this._register(dom.addDisposableListener(textArea.domNode, 'compositionend', (e: CompositionEvent) => {
196
			if (browser.isEdgeOrIE && e.locale === 'ja') {
197
				// https://github.com/Microsoft/monaco-editor/issues/339
198
				const [newState, typeInput] = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/false);
A
Alex Dima 已提交
199
				this._textAreaState = newState;
200 201 202
				this._onType.fire(typeInput);
			}
			else {
A
Alex Dima 已提交
203 204
				const [newState, typeInput] = deduceComposition(e.data);
				this._textAreaState = newState;
205 206
				this._onType.fire(typeInput);
			}
207

208
			// Due to isEdgeOrIE (where the textarea was not cleared initially) and isChrome (the textarea is not updated correctly when composition ends)
209
			// we cannot assume the text at the end consists only of the composited text
210
			if (browser.isEdgeOrIE || browser.isChrome) {
A
Alex Dima 已提交
211
				this._textAreaState = this._textAreaState.readFromTextArea(this._textArea);
A
Andre Weinand 已提交
212
			}
213

A
Alex Dima 已提交
214
			if (!this._isDoingComposition) {
A
Alex Dima 已提交
215 216
				return;
			}
A
Alex Dima 已提交
217
			this._isDoingComposition = false;
A
Alex Dima 已提交
218 219

			this._onCompositionEnd.fire();
220 221
		}));

A
Alex Dima 已提交
222
		this._register(dom.addDisposableListener(textArea.domNode, 'input', () => {
223 224 225 226
			// Pretend here we touched the text area, as the `input` event will most likely
			// result in a `selectionchange` event which we want to ignore
			this._textArea.setIgnoreSelectionChangeTime('received input event');

A
Alex Dima 已提交
227
			if (this._isDoingComposition) {
228
				// See https://github.com/Microsoft/monaco-editor/issues/320
229
				if (browser.isChromev56) {
A
Alex Dima 已提交
230 231 232
					const [newState, typeInput] = deduceComposition(this._textArea.getValue());
					this._textAreaState = newState;

233
					this._onType.fire(typeInput);
234
					let e: ICompositionData = {
A
Alex Dima 已提交
235
						data: typeInput.text
236 237 238
					};
					this._onCompositionUpdate.fire(e);
				}
239
				return;
240 241
			}

242
			const [newState, typeInput] = deduceInputFromTextAreaValue(/*couldBeEmojiInput*/platform.isMacintosh);
A
Alex Dima 已提交
243 244 245 246 247
			if (typeInput.replaceCharCnt === 0 && typeInput.text.length === 1 && strings.isHighSurrogate(typeInput.text.charCodeAt(0))) {
				// Ignore invalid input but keep it around for next time
				return;
			}

A
Alex Dima 已提交
248
			this._textAreaState = newState;
A
Alex Dima 已提交
249 250 251 252 253 254
			// console.log('==> DEDUCED INPUT: ' + JSON.stringify(typeInput));
			if (this._nextCommand === ReadFromTextArea.Type) {
				if (typeInput.text !== '') {
					this._onType.fire(typeInput);
				}
			} else {
A
Alex Dima 已提交
255 256 257 258 259
				if (typeInput.text !== '') {
					this._onPaste.fire({
						text: typeInput.text
					});
				}
A
Alex Dima 已提交
260 261
				this._nextCommand = ReadFromTextArea.Type;
			}
262
		}));
263

A
Alex Dima 已提交
264 265
		// --- Clipboard operations

A
Alex Dima 已提交
266
		this._register(dom.addDisposableListener(textArea.domNode, 'cut', (e: ClipboardEvent) => {
267 268 269 270
			// Pretend here we touched the text area, as the `cut` event will most likely
			// result in a `selectionchange` event which we want to ignore
			this._textArea.setIgnoreSelectionChangeTime('received cut event');

A
Alex Dima 已提交
271
			this._ensureClipboardGetsEditorSelection(e);
A
Alex Dima 已提交
272
			this._asyncTriggerCut.schedule();
A
Alex Dima 已提交
273 274
		}));

A
Alex Dima 已提交
275
		this._register(dom.addDisposableListener(textArea.domNode, 'copy', (e: ClipboardEvent) => {
A
Alex Dima 已提交
276 277 278
			this._ensureClipboardGetsEditorSelection(e);
		}));

A
Alex Dima 已提交
279
		this._register(dom.addDisposableListener(textArea.domNode, 'paste', (e: ClipboardEvent) => {
280 281 282 283
			// Pretend here we touched the text area, as the `paste` event will most likely
			// result in a `selectionchange` event which we want to ignore
			this._textArea.setIgnoreSelectionChangeTime('received paste event');

A
Alex Dima 已提交
284
			if (ClipboardEventUtils.canUseTextData(e)) {
A
Alex Dima 已提交
285 286 287 288 289 290
				const pastePlainText = ClipboardEventUtils.getTextData(e);
				if (pastePlainText !== '') {
					this._onPaste.fire({
						text: pastePlainText
					});
				}
A
Alex Dima 已提交
291
			} else {
A
Alex Dima 已提交
292
				if (this._textArea.getSelectionStart() !== this._textArea.getSelectionEnd()) {
A
Alex Dima 已提交
293
					// Clean up the textarea, to get a clean paste
A
Alex Dima 已提交
294
					this._setAndWriteTextAreaState('paste', TextAreaState.EMPTY);
A
Alex Dima 已提交
295
				}
296
				this._nextCommand = ReadFromTextArea.Paste;
A
Alex Dima 已提交
297 298
			}
		}));
299 300 301

		this._register(dom.addDisposableListener(textArea.domNode, 'focus', () => this._setHasFocus(true)));
		this._register(dom.addDisposableListener(textArea.domNode, 'blur', () => this._setHasFocus(false)));
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


		// See https://github.com/Microsoft/vscode/issues/27216
		// When using a Braille display, it is possible for users to reposition the
		// system caret. This is reflected in Chrome as a `selectionchange` event.
		//
		// The `selectionchange` event appears to be emitted under numerous other circumstances,
		// so it is quite a challenge to distinguish a `selectionchange` coming in from a user
		// using a Braille display from all the other cases.
		//
		// The problems with the `selectionchange` event are:
		//  * the event is emitted when the textarea is focused programmatically -- textarea.focus()
		//  * the event is emitted when the selection is changed in the textarea programatically -- textarea.setSelectionRange(...)
		//  * the event is emitted when the value of the textarea is changed programmatically -- textarea.value = '...'
		//  * the event is emitted when tabbing into the textarea
		//  * the event is emitted asynchronously (sometimes with a delay as high as a few tens of ms)
		//  * the event sometimes comes in bursts for a single logical textarea operation

		// `selectionchange` events often come multiple times for a single logical change
		// so throttle multiple `selectionchange` events that burst in a short period of time.
		let previousSelectionChangeEventTime = 0;
		this._register(dom.addDisposableListener(document, 'selectionchange', (e) => {
			if (!this._hasFocus) {
				return;
			}
			if (this._isDoingComposition) {
				return;
			}
			if (!browser.isChrome || !platform.isWindows) {
				// Support only for Chrome on Windows until testing happens on other browsers + OS configurations
				return;
			}

			const now = Date.now();

			const delta1 = now - previousSelectionChangeEventTime;
			previousSelectionChangeEventTime = now;
			if (delta1 < 5) {
				// received another `selectionchange` event within 5ms of the previous `selectionchange` event
				// => ignore it
				return;
			}

			const delta2 = now - this._textArea.getIgnoreSelectionChangeTime();
			this._textArea.resetSelectionChangeTime();
			if (delta2 < 100) {
				// received a `selectionchange` event within 100ms since we touched the textarea
				// => ignore it, since we caused it
				return;
			}

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
			if (!this._textAreaState.selectionStartPosition || !this._textAreaState.selectionEndPosition) {
				// Cannot correlate a position in the textarea with a position in the editor...
				return;
			}

			const newValue = this._textArea.getValue();
			if (this._textAreaState.value !== newValue) {
				// Cannot correlate a position in the textarea with a position in the editor...
				return;
			}

			const newSelectionStart = this._textArea.getSelectionStart();
			const newSelectionEnd = this._textArea.getSelectionEnd();
			if (this._textAreaState.selectionStart === newSelectionStart && this._textAreaState.selectionEnd === newSelectionEnd) {
				// Nothing to do...
				return;
			}

371 372 373 374 375 376 377 378 379 380
			const _newSelectionStartPosition = this._textAreaState.deduceEditorPosition(newSelectionStart);
			const newSelectionStartPosition = this._host.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]);

			const _newSelectionEndPosition = this._textAreaState.deduceEditorPosition(newSelectionEnd);
			const newSelectionEndPosition = this._host.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]);

			const newSelection = new Selection(
				newSelectionStartPosition.lineNumber, newSelectionStartPosition.column,
				newSelectionEndPosition.lineNumber, newSelectionEndPosition.column
			);
381

382
			this._onSelectionChangeRequest.fire(newSelection);
383
		}));
384 385 386
	}

	public dispose(): void {
387
		super.dispose();
388 389
	}

A
Alex Dima 已提交
390 391
	public focusTextArea(): void {
		// Setting this._hasFocus and writing the screen reader content
392 393 394 395 396 397
		// will result in a focus() and setSelectionRange() in the textarea
		this._setHasFocus(true);
	}

	public isFocused(): boolean {
		return this._hasFocus;
398 399
	}

400 401
	private _setHasFocus(newHasFocus: boolean): void {
		if (this._hasFocus === newHasFocus) {
402 403 404
			// no change
			return;
		}
405 406
		this._hasFocus = newHasFocus;

A
Alex Dima 已提交
407
		if (this._hasFocus) {
A
Alex Dima 已提交
408 409 410 411 412
			if (browser.isEdge) {
				// Edge has a bug where setting the selection range while the focus event
				// is dispatching doesn't work. To reproduce, "tab into" the editor.
				this._setAndWriteTextAreaState('focusgain', TextAreaState.EMPTY);
			} else {
413
				this.writeScreenReaderContent('focusgain');
A
Alex Dima 已提交
414
			}
415
		}
416 417 418 419 420 421

		if (this._hasFocus) {
			this._onFocus.fire();
		} else {
			this._onBlur.fire();
		}
422 423
	}

A
Alex Dima 已提交
424
	private _setAndWriteTextAreaState(reason: string, textAreaState: TextAreaState): void {
A
Alex Dima 已提交
425
		if (!this._hasFocus) {
A
Alex Dima 已提交
426
			textAreaState = textAreaState.collapseSelection();
427 428
		}

A
Alex Dima 已提交
429
		textAreaState.writeToTextArea(reason, this._textArea, this._hasFocus);
A
Alex Dima 已提交
430
		this._textAreaState = textAreaState;
431 432
	}

433
	public writeScreenReaderContent(reason: string): void {
A
Alex Dima 已提交
434 435 436
		if (this._isDoingComposition) {
			// Do not write to the text area when doing composition
			return;
437 438
		}

439
		this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent(this._textAreaState));
440
	}
A
Alex Dima 已提交
441 442 443 444 445 446

	private _ensureClipboardGetsEditorSelection(e: ClipboardEvent): void {
		const copyPlainText = this._host.getPlainTextToCopy();
		if (!ClipboardEventUtils.canUseTextData(e)) {
			// Looks like an old browser. The strategy is to place the text
			// we'd like to be copied to the clipboard in the textarea and select it.
A
Alex Dima 已提交
447
			this._setAndWriteTextAreaState('copy or cut', TextAreaState.selectedText(copyPlainText));
A
Alex Dima 已提交
448 449 450 451 452 453 454 455 456
			return;
		}

		let copyHTML: string = null;
		if (!browser.isEdgeOrIE && (copyPlainText.length < 65536 || CopyOptions.forceCopyWithSyntaxHighlighting)) {
			copyHTML = this._host.getHTMLToCopy();
		}
		ClipboardEventUtils.setTextData(e, copyPlainText, copyHTML);
	}
457
}
A
Alex Dima 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

class ClipboardEventUtils {

	public static canUseTextData(e: ClipboardEvent): boolean {
		if (e.clipboardData) {
			return true;
		}
		if ((<any>window).clipboardData) {
			return true;
		}
		return false;
	}

	public static getTextData(e: ClipboardEvent): string {
		if (e.clipboardData) {
			e.preventDefault();
			return e.clipboardData.getData('text/plain');
		}

		if ((<any>window).clipboardData) {
			e.preventDefault();
			return (<any>window).clipboardData.getData('Text');
		}

		throw new Error('ClipboardEventUtils.getTextData: Cannot use text data!');
	}

	public static setTextData(e: ClipboardEvent, text: string, richText: string): void {
		if (e.clipboardData) {
			e.clipboardData.setData('text/plain', text);
			if (richText !== null) {
				e.clipboardData.setData('text/html', richText);
			}
			e.preventDefault();
			return;
		}

		if ((<any>window).clipboardData) {
			(<any>window).clipboardData.setData('Text', text);
			e.preventDefault();
			return;
		}

		throw new Error('ClipboardEventUtils.setTextData: Cannot use text data!');
	}
}

class TextAreaWrapper extends Disposable implements ITextAreaWrapper {

	private readonly _actual: FastDomNode<HTMLTextAreaElement>;
508
	private _ignoreSelectionChangeTime: number;
A
Alex Dima 已提交
509 510 511 512

	constructor(_textArea: FastDomNode<HTMLTextAreaElement>) {
		super();
		this._actual = _textArea;
513 514 515 516 517 518 519 520 521 522 523 524 525
		this._ignoreSelectionChangeTime = 0;
	}

	public setIgnoreSelectionChangeTime(reason: string): void {
		this._ignoreSelectionChangeTime = Date.now();
	}

	public getIgnoreSelectionChangeTime(): number {
		return this._ignoreSelectionChangeTime;
	}

	public resetSelectionChangeTime(): void {
		this._ignoreSelectionChangeTime = 0;
A
Alex Dima 已提交
526 527 528 529 530 531 532 533
	}

	public getValue(): string {
		// console.log('current value: ' + this._textArea.value);
		return this._actual.domNode.value;
	}

	public setValue(reason: string, value: string): void {
A
Alex Dima 已提交
534 535 536 537 538
		const textArea = this._actual.domNode;
		if (textArea.value === value) {
			// No change
			return;
		}
A
Alex Dima 已提交
539
		// console.log('reason: ' + reason + ', current value: ' + textArea.value + ' => new value: ' + value);
540
		this.setIgnoreSelectionChangeTime('setValue');
A
Alex Dima 已提交
541
		textArea.value = value;
A
Alex Dima 已提交
542 543 544 545 546 547 548 549 550 551
	}

	public getSelectionStart(): number {
		return this._actual.domNode.selectionStart;
	}

	public getSelectionEnd(): number {
		return this._actual.domNode.selectionEnd;
	}

A
Alex Dima 已提交
552
	public setSelectionRange(reason: string, selectionStart: number, selectionEnd: number): void {
A
Alex Dima 已提交
553
		const textArea = this._actual.domNode;
554 555 556 557 558 559 560 561 562 563 564 565 566 567

		const currentIsFocused = (document.activeElement === textArea);
		const currentSelectionStart = textArea.selectionStart;
		const currentSelectionEnd = textArea.selectionEnd;

		if (currentIsFocused && currentSelectionStart === selectionStart && currentSelectionEnd === selectionEnd) {
			// No change
			return;
		}

		// console.log('reason: ' + reason + ', setSelectionRange: ' + selectionStart + ' -> ' + selectionEnd);

		if (currentIsFocused) {
			// No need to focus, only need to change the selection range
568
			this.setIgnoreSelectionChangeTime('setSelectionRange');
A
Alex Dima 已提交
569
			textArea.setSelectionRange(selectionStart, selectionEnd);
570 571 572 573 574 575 576
			return;
		}

		// If the focus is outside the textarea, browsers will try really hard to reveal the textarea.
		// Here, we try to undo the browser's desperate reveal.
		try {
			const scrollState = dom.saveParentsScrollTop(textArea);
577
			this.setIgnoreSelectionChangeTime('setSelectionRange');
578 579 580 581 582
			textArea.focus();
			textArea.setSelectionRange(selectionStart, selectionEnd);
			dom.restoreParentsScrollTop(textArea, scrollState);
		} catch (e) {
			// Sometimes IE throws when setting selection (e.g. textarea is off-DOM)
A
Alex Dima 已提交
583 584 585
		}
	}
}