import type { ReactNode } from "react";
import React, { useEffect, useRef, useState } from "react";
import {
InputAccessoryView,
Keyboard,
Platform,
Button as RNButton,
View,
useColorScheme,
} from "react-native";
import uuid from "react-native-uuid";
import { InputAccessoriesContext } from "./InputAccessoriesContext";
import { useStyles } from "./InputAccessoriesProvider.style";
export function InputAccessoriesProvider({
children,
}: {
readonly children: ReactNode;
}) {
const inputAccessoryID = useRef(uuid.v4()).current;
const {
focusedInput,
setFocusedInput,
canFocusNext,
canFocusPrevious,
elements,
setElements,
previousKey,
nextKey,
} = useInputAccessoriesProviderState();
const colorScheme = useColorScheme();
const styles = useStyles();
return (
{children}
{Platform.OS === "ios" && (
)}
);
function register(name: string, onFocus: () => void) {
elements[name] = onFocus;
setElements(elements);
}
function unregister(name: string) {
delete elements[name];
setElements(elements);
}
function onFocusNext() {
const nextElement = elements[nextKey];
nextElement?.();
}
function onFocusPrevious() {
const previousElement = elements[previousKey];
previousElement?.();
}
}
function useInputAccessoriesProviderState() {
const [focusedInput, setFocusedInput] = useState("");
const [canFocusNext, setCanFocusNext] = useState(false);
const [canFocusPrevious, setCanFocusPrevious] = useState(false);
const [elements, setElements] = useState void>>({});
const keys = Object.keys(elements);
const selectedIndex = keys.findIndex(key => key === focusedInput);
const nextKey = keys[selectedIndex + 1];
const previousKey = keys[selectedIndex - 1];
useEffect(() => {
setCanFocusNext(Boolean(nextKey));
setCanFocusPrevious(Boolean(previousKey));
}, [previousKey, nextKey]);
return {
previousKey,
nextKey,
focusedInput,
setFocusedInput,
canFocusNext,
setCanFocusNext,
canFocusPrevious,
setCanFocusPrevious,
elements,
setElements,
};
}