[fix] TextInput selection for Blink on Android

Close #492
This commit is contained in:
Nick
2017-06-01 09:30:22 -07:00
committed by Nicolas Gallagher
parent 70282cb4ca
commit e78ce713cb
2 changed files with 27 additions and 1 deletions
@@ -199,4 +199,23 @@ describe('components/TextInput', () => {
const input = findNativeInput(shallow(<TextInput value={value} />));
expect(input.prop('value')).toEqual(value);
});
describe('prop "selection"', () => {
test('set cursor location', () => {
const cursorLocation = { start: 3, end: 3 };
const inputDefaultSelection = findNativeInput(mount(<TextInput defaultValue="12345" />));
const inputCustomSelection = findNativeInput(
mount(<TextInput defaultValue="12345" selection={cursorLocation} />)
);
// default selection is 0
expect(inputDefaultSelection.node.selectionStart).toEqual(0);
expect(inputDefaultSelection.node.selectionEnd).toEqual(0);
// custom selection sets cursor at custom position
expect(inputCustomSelection.node.selectionStart).toEqual(cursorLocation.start);
expect(inputCustomSelection.node.selectionEnd).toEqual(cursorLocation.end);
});
});
});
+8 -1
View File
@@ -4,6 +4,7 @@
import applyLayout from '../../modules/applyLayout';
import applyNativeMethods from '../../modules/applyNativeMethods';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import { Component } from 'react';
import NativeMethodsMixin from '../../modules/NativeMethodsMixin';
import createDOMElement from '../../modules/createDOMElement';
@@ -15,6 +16,7 @@ import TextInputState from './TextInputState';
import ViewPropTypes from '../View/ViewPropTypes';
import { bool, func, number, oneOf, shape, string } from 'prop-types';
const isAndroid = canUseDOM && /Android/i.test(navigator && navigator.userAgent);
const emptyObject = {};
/**
@@ -48,7 +50,12 @@ const setSelection = (node, selection) => {
try {
if (isSelectionStale(node, selection)) {
const { start, end } = selection;
node.setSelectionRange(start, end || start);
// workaround for Blink on Android: see https://github.com/text-mask/text-mask/issues/300
if (isAndroid) {
setTimeout(() => node.setSelectionRange(start, end || start), 10);
} else {
node.setSelectionRange(start, end || start);
}
}
} catch (e) {}
};