import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { FlatList, Platform, TextInput, View, ViewStyle } from 'react-native'; import { Divider } from 'react-native-paper'; import { useDispatch } from 'react-redux'; import Button from '../../../base/ui/components/native/Button'; import Input from '../../../base/ui/components/native/Input'; import { BUTTON_TYPES } from '../../../base/ui/constants.native'; import { editPoll } from '../../actions'; import { ANSWERS_LIMIT, CHAR_LIMIT } from '../../constants'; import AbstractPollCreate, { AbstractProps } from '../AbstractPollCreate'; import { dialogStyles, pollsStyles } from './styles'; const PollCreate = (props: AbstractProps) => { const { addAnswer, answers, editingPoll, editingPollId, isSubmitDisabled, onSubmit, question, removeAnswer, setAnswer, setCreateMode, setQuestion, t } = props; const answerListRef = useRef(null); const dispatch = useDispatch(); /* * This ref stores the Array of answer input fields, allowing us to focus on them. * This array is maintained by registerFieldRef and the useEffect below. */ const answerInputs = useRef([]); const registerFieldRef = useCallback((i, input) => { if (input === null) { return; } answerInputs.current[i] = input; }, [ answerInputs ]); useEffect(() => { answerInputs.current = answerInputs.current.slice(0, answers.length); setTimeout(() => { answerListRef.current?.scrollToEnd({ animated: true }); }, 1000); }, [ answers ]); /* * This state allows us to requestFocus asynchronously, without having to worry * about whether a newly created input field has been rendered yet or not. */ const [ lastFocus, requestFocus ] = useState(null); const { PRIMARY, SECONDARY, TERTIARY } = BUTTON_TYPES; useEffect(() => { if (lastFocus === null) { return; } const input = answerInputs.current[lastFocus]; if (input === undefined) { return; } input.focus(); }, [ answerInputs, lastFocus ]); const onQuestionKeyDown = useCallback(() => { answerInputs.current[0].focus(); }, []); // Called on keypress in answer fields const onAnswerKeyDown = useCallback((index: number, ev) => { const { key } = ev.nativeEvent; const currentText = answers[index].name; if (key === 'Backspace' && currentText === '' && answers.length > 1) { removeAnswer(index); requestFocus(index > 0 ? index - 1 : 0); } }, [ answers, addAnswer, removeAnswer, requestFocus ]); /* eslint-disable react/no-multi-comp */ const createRemoveOptionButton = (onPress: () => void) => (