/* Copyright (c) 2022 Skyflow, Inc. */ import React, { useEffect, useRef } from "react"; import { Text, TextInput, View } from "react-native"; import type CollectElement from "../../core/CollectElement"; import { CollectElementProps, ElementType, ELEMENT_REQUIRED_ASTERISK, REQUIRED_MARK_DEFAULT_STYLE, ContainerType } from "../../utils/constants"; import SkyflowError from "../../utils/skyflow-error"; import SKYFLOW_ERROR_CODE from "../../utils/skyflow-error-code"; import uuid from 'react-native-uuid'; const ExpirationMonthElement: React.FC = ({ container, options = { required: false }, ...rest }) => { const [element, setElement] = React.useState(); const [elementValue, setElementValue] = React.useState(''); const [errorText, setErrorText] = React.useState(''); const [labelStyles, setLabelStyles] = React.useState(rest?.labelStyles?.base || {}); const [inputStyles, setInputStyles] = React.useState(rest?.inputStyles?.base || {}); const textInputRef = useRef(); const uniqueElementID = useRef(uuid.v4() as string); useEffect(() => { if (container) { const element: CollectElement = container.create({ ...rest, type: ElementType.EXPIRATION_MONTH }, options); setElement(element); if (container.type === ContainerType.COLLECT) element.setMethods(setErrorText, { setInputStyles: setInputStyles, setLabelStyles: setLabelStyles }); else if (container.type === ContainerType.COMPOSABLE) { element.setMethods(rest.containerMethods.setErrorText, { setInputStyles: setInputStyles, setLabelStyles: setLabelStyles }) rest.containerMethods.setRef(textInputRef, uniqueElementID.current); } if (rest.onReady) { rest.onReady(element.getClientState()); } } else { throw new SkyflowError(SKYFLOW_ERROR_CODE.CONTAINER_OBJECT_IS_REQUIRED, [ElementType.EXPIRATION_MONTH, 'useCollectContainer()'], true) } }, []); return ( { rest.label && ( {rest.label} {options.required ? ELEMENT_REQUIRED_ASTERISK : ''} ) } { element?.onChangeElement(text); setElementValue(element.getInternalState().value) if (container.type === ContainerType.COMPOSABLE && (!element.getInternalState().isEmpty) && element.getInternalState().isValid) { (element.getInternalState().value.length === 2) && rest.containerMethods.shiftFocus(uniqueElementID); } }} onFocus={() => { element?.onFocusElement() setLabelStyles(element.updateLabelStyles()); setInputStyles(element.updateInputStyles()); }} onBlur={() => { element?.onBlurElement(); if (container.type === ContainerType.COLLECT) { setErrorText(element?.getErrorText() || ''); } else if (container.type === ContainerType.COMPOSABLE) { rest.containerMethods.setErrorText(element?.getErrorText() || '') } setElementValue(element.getInternalState().value); setLabelStyles(element.updateLabelStyles()); setInputStyles(element.updateInputStyles()); }} maxLength={2} keyboardType='numeric' style={inputStyles} /> { container && container?.type === ContainerType.COLLECT && {errorText} } ); } export default ExpirationMonthElement;