From e78ce713cbaf6a3b80746b751c9b9abe70cc132a Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 25 May 2017 16:52:10 -0700 Subject: [PATCH] [fix] TextInput selection for Blink on Android Close #492 --- .../TextInput/__tests__/index-test.js | 19 +++++++++++++++++++ src/components/TextInput/index.js | 9 ++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/components/TextInput/__tests__/index-test.js b/src/components/TextInput/__tests__/index-test.js index 117ca959..bdddda16 100644 --- a/src/components/TextInput/__tests__/index-test.js +++ b/src/components/TextInput/__tests__/index-test.js @@ -199,4 +199,23 @@ describe('components/TextInput', () => { const input = findNativeInput(shallow()); expect(input.prop('value')).toEqual(value); }); + + describe('prop "selection"', () => { + test('set cursor location', () => { + const cursorLocation = { start: 3, end: 3 }; + + const inputDefaultSelection = findNativeInput(mount()); + const inputCustomSelection = findNativeInput( + mount() + ); + + // 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); + }); + }); }); diff --git a/src/components/TextInput/index.js b/src/components/TextInput/index.js index 366fa233..c6ff90e5 100644 --- a/src/components/TextInput/index.js +++ b/src/components/TextInput/index.js @@ -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) {} };