import React, { FC, useEffect, useRef, useState } from 'react' import { Button, Notice, Stack, ValidatedInputControl } from '@wordpress/ui' import { useI18n } from '@wordpress/react-i18n' import { connectToMybring, isKeyAccepted, parseMybringKey, } from '../model/mybringKey' export declare interface ActivationKeyFormProps { prominent: boolean /** Whether to move focus into the key field, when the merchant opened it */ focusOnOpen: boolean onConnected: () => void } /** * Lets the merchant activate the plugin by pasting the activation key copied * from Mybring, without leaving the landing page. */ const ActivationKeyForm: FC = ({ prominent, focusOnOpen, onConnected, }) => { const { __ } = useI18n() const [key, setKey] = useState('') const [activating, setActivating] = useState(false) const [problem, setProblem] = useState<'rejected' | 'failed' | null>(null) const keyField = useRef(null) useEffect(() => { if (focusOnOpen) { keyField.current?.focus() } }, [focusOnOpen]) const mybringKey = parseMybringKey(key.trim()) const invalidKey = key.trim() !== '' && !mybringKey const activate = async () => { if (!mybringKey || activating) { return } setActivating(true) setProblem(null) const outcome = await connectToMybring(mybringKey) .then(response => (isKeyAccepted(response) ? 'accepted' : 'rejected')) .catch(() => 'failed' as const) setActivating(false) if (outcome === 'accepted') { onConnected() } else { setProblem(outcome) } } return ( {problem === 'rejected' && ( {__("The key wasn't accepted", 'posten-bring-checkout')} {__( 'Check that you copied the key for this webshop from Mybring, and try again.', 'posten-bring-checkout' )} )} {problem === 'failed' && ( {__( "The key couldn't be checked right now", 'posten-bring-checkout' )} {__('Try again in a few minutes.', 'posten-bring-checkout')} )}
setKey(event.currentTarget.value)} onKeyDown={event => event.key === 'Enter' && activate()} />
) } export default ActivationKeyForm