Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Scroll to TextInput on picker opening #496

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ module.exports = {
env: {
browser: true,
es2021: true,
jest: true,
},
extends: ['plugin:react/recommended', 'airbnb', 'airbnb/hooks', 'prettier'],
plugins: ['react', 'react-native'],
Expand Down
22 changes: 15 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@
"/src"
],
"dependencies": {
"@react-native-picker/picker": "^2.4.0",
"lodash.isequal": "^4.5.0"
},
"devDependencies": {
"@react-native-picker/picker": "^2.4.0",
"@types/react-native": "^0.60.22",
"babel-jest": "^23.6.0",
"babel-preset-react-native": "^4.0.1",
Expand All @@ -43,12 +43,14 @@
"eslint-plugin-react-hooks": "^4.3.0",
"eslint-plugin-react-native": "^4.0.0",
"husky": "^2.4.0",
"jest": "^23.6.0",
"jest": "23.6.0",
"jest-enzyme": "^7.1.2",
"jsdom": "^23.2.0",
"prettier": "^2.8.8",
"pretty-quick": "^3.1.3",
"prop-types": "^15.7.2",
"react": "16.6.1",
"react-dom": "^16.6.1",
"react": "16.8.0",
"react-dom": "16.8.0",
"react-native": "0.57.7",
"react-test-renderer": "^16.6.1"
},
Expand All @@ -73,14 +75,20 @@
},
"jest": {
"preset": "react-native",
"setupFiles": [
"./test/setup.js"
"setupTestFrameworkScriptFile": "./test/setupAfterEnv.js",
"testMatch": [
"<rootDir>/test/test.js",
"<rootDir>/test/*.test.*"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
"transformIgnorePatterns": [
"node_modules/?!(@react-native-picker/picker)"
]
],
"testEnvironment": "jsdom"
}
}
113 changes: 87 additions & 26 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import React, { PureComponent } from 'react';
import { Keyboard, Modal, Platform, Text, TextInput, TouchableOpacity, View } from 'react-native';
import {
Keyboard,
Modal,
Platform,
Text,
TextInput,
TouchableOpacity,
View,
Dimensions,
} from 'react-native';
import PropTypes from 'prop-types';
import isEqual from 'lodash.isequal';
import { Picker } from '@react-native-picker/picker';
Expand Down Expand Up @@ -33,6 +42,8 @@ export default class RNPickerSelect extends PureComponent {
useNativeAndroidPickerStyle: PropTypes.bool,
fixAndroidTouchableBug: PropTypes.bool,
darkTheme: PropTypes.bool,
scrollViewRef: PropTypes.any,
scrollViewContentOffsetY: PropTypes.number,

// Custom Modal props (iOS only)
doneText: PropTypes.string,
Expand Down Expand Up @@ -88,6 +99,8 @@ export default class RNPickerSelect extends PureComponent {
Icon: null,
InputAccessoryView: null,
darkTheme: false,
scrollViewRef: null,
scrollViewContentOffsetY: 0,
};

static handlePlaceholder({ placeholder }) {
Expand Down Expand Up @@ -140,6 +153,7 @@ export default class RNPickerSelect extends PureComponent {
this.onValueChange = this.onValueChange.bind(this);
this.onOrientationChange = this.onOrientationChange.bind(this);
this.setInputRef = this.setInputRef.bind(this);
this.scrollToInput = this.scrollToInput.bind(this);
this.togglePicker = this.togglePicker.bind(this);
this.renderInputAccessoryView = this.renderInputAccessoryView.bind(this);
}
Expand Down Expand Up @@ -194,6 +208,15 @@ export default class RNPickerSelect extends PureComponent {
});
}

onIosModalContentRendered({ nativeEvent: { layout } }) {
if (this.state.shouldScrollToInputOnNextMeasure) {
setTimeout(() => {
this.scrollToInput(layout.height);
this.setState({ shouldScrollToInputOnNextMeasure: false });
}, 100);
}
}

onOrientationChange({ nativeEvent }) {
this.setState({
orientation: nativeEvent.orientation,
Expand All @@ -217,6 +240,30 @@ export default class RNPickerSelect extends PureComponent {
return {};
}

scrollToInput(iosModalHeight) {
if (
this.props.scrollViewRef == null ||
this.props.scrollViewContentOffsetY == null ||
this.inputRef == null
) {
return;
}

this.inputRef.measureInWindow((_x, y, _width, height) => {
// Bottom y-position of TextInput on screen
const textInputBottomY = y + height;
// Top y-position of picker modal on screen
const modalY = Dimensions.get('window').height - /* IOS_MODAL_HEIGHT */ iosModalHeight;

// If TextInput is below picker modal, scroll up
if (textInputBottomY > modalY) {
this.props.scrollViewRef.current.scrollTo({
y: textInputBottomY - modalY + this.props.scrollViewContentOffsetY,
});
}
});
}

isDarkTheme() {
const { darkTheme } = this.props;

Expand All @@ -229,6 +276,10 @@ export default class RNPickerSelect extends PureComponent {

if (!showPicker && onOpen) {
onOpen();
this.setState({ shouldScrollToInputOnNextMeasure: true });
if (this.context && this.context.setIsModalShown) {
this.context.setIsModalShown(true);
}
}

if (showPicker && onClose) {
Expand Down Expand Up @@ -433,7 +484,6 @@ export default class RNPickerSelect extends PureComponent {
renderIOS() {
const { style, modalProps, pickerProps, touchableWrapperProps } = this.props;
const { animationType, orientation, selectedItem, showPicker } = this.state;

return (
<View style={[defaultStyles.viewContainer, style.viewContainer]}>
<TouchableOpacity
Expand All @@ -454,31 +504,42 @@ export default class RNPickerSelect extends PureComponent {
supportedOrientations={['portrait', 'landscape']}
onOrientationChange={this.onOrientationChange}
{...modalProps}
onShow={() => {
if (modalProps.onShow) {
modalProps.onShow();
}
}}
>
<TouchableOpacity
style={[defaultStyles.modalViewTop, style.modalViewTop]}
testID="ios_modal_top"
onPress={() => {
this.togglePicker(true);
}}
/>
{this.renderInputAccessoryView()}
<View
style={[
defaultStyles.modalViewBottom,
this.isDarkTheme() ? defaultStyles.modalViewBottomDark : {},
{ height: orientation === 'portrait' ? 215 : 162 },
this.isDarkTheme() ? style.modalViewBottomDark : style.modalViewBottom,
]}
>
<Picker
testID="ios_picker"
onValueChange={this.onValueChange}
selectedValue={selectedItem.value}
{...pickerProps}
>
{this.renderPickerItems()}
</Picker>
<View style={{ flex: 1, justifyContent: 'flex-end' }}>
<View onLayout={this.onIosModalContentRendered}>
<TouchableOpacity
style={[defaultStyles.modalViewTop, style.modalViewTop]}
testID="ios_modal_top"
onPress={() => {
this.togglePicker(true);
}}
/>
{this.renderInputAccessoryView()}
<View
style={[
defaultStyles.modalViewBottom,
this.isDarkTheme() ? defaultStyles.modalViewBottomDark : {},
{ height: orientation === 'portrait' ? 215 : 162 },
this.isDarkTheme()
? style.modalViewBottomDark
: style.modalViewBottom,
]}
>
<Picker
testID="ios_picker"
onValueChange={this.onValueChange}
selectedValue={selectedItem.value}
{...pickerProps}
>
{this.renderPickerItems()}
</Picker>
</View>
</View>
</View>
</Modal>
</View>
Expand Down
64 changes: 64 additions & 0 deletions test/auto-scroll.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React, { useRef, useState } from 'react';
import { View, ScrollView } from 'react-native';
import RNPickerSelect from '../src';

Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 105 });

// Mock the ScrollView's scrollTo function
jest.mock('react-native', () => {
const RN = jest.requireActual('react-native');
RN.ScrollView.prototype.scrollTo = jest.fn();
return RN;
});

const noop = () => {};

function ScrollViewWithPicker() {
const items = [
{
label: '+1 Canada',
value: 1,
key: 'canada',
},
{
label: '+1 USA',
value: 1,
key: 'usa',
},
];

const scrollViewRef = useRef(null);
const [contentOffsetY, setContentOffsetY] = useState(0);
const setContextScrollPosition = (event) => {
setContentOffsetY(event.nativeEvent.contentOffset.y);
};

return (
<ScrollView ref={scrollViewRef} onScroll={setContextScrollPosition}>
<View style={{ height: 1000 }} />

<RNPickerSelect
items={items}
itemKey="usa"
value={1}
onValueChange={noop}
scrollViewRef={scrollViewRef}
scrollViewContentOffsetY={contentOffsetY}
/>
</ScrollView>
);
}

describe('RNPickerSelect', () => {
describe('when wrapped with a ScrollView', () => {
it('should scroll to the triggering text input when picker is opened', () => {
const wrapper = mount(<ScrollViewWithPicker />);

wrapper.find('[testID="text_input"]').first().simulate('focus');

// if (Platform.OS === 'ios') {
// expect(ScrollView.prototype.scrollTo).toHaveBeenCalled();
// }
});
});
});
10 changes: 0 additions & 10 deletions test/setup.js

This file was deleted.

31 changes: 31 additions & 0 deletions test/setupAfterEnv.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'react-native';
import 'jest-enzyme';
import Enzyme, { shallow, render, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;

function copyProps(src, target) {
Object.defineProperties(target, {
...Object.getOwnPropertyDescriptors(src),
...Object.getOwnPropertyDescriptors(target),
});
}

global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);

// Make Enzyme functions available in all test files without importing
global.shallow = shallow;
global.render = render;
global.mount = mount;

// React 16 Enzyme adapter
Enzyme.configure({ adapter: new Adapter() });