import { useUserStore } from '../state/User' import { useState, useEffect, useRef } from '@wordpress/element' import { User as UserApi } from '../api/User' import { __ } from '@wordpress/i18n' import classNames from 'classnames' import { Spinner, Button } from '@wordpress/components' import { Icon } from '@wordpress/icons' import { user } from './icons/' import { success as successIcon } from './icons/' import { useIsDevMode } from '../hooks/helpers' export default function LoginInterface({ actionCallback, initialFocus }) { const loggedIn = useUserStore((state) => state.apiKey.length) const [email, setEmail] = useState('') const [apiKey, setApiKey] = useState('') const [feedback, setFeedback] = useState('') const [feedbackType, setFeedbackType] = useState('info') const [isWorking, setIsWorking] = useState(false) const [success, setSuccess] = useState(false) const viewPatternsButtonRef = useRef(null) const licenseKeyRef = useRef(null) const devMode = useIsDevMode() useEffect(() => { setEmail(useUserStore.getState().email) // This will reset the default error state to info return () => setFeedbackType('info') }, []) useEffect(() => { success && viewPatternsButtonRef?.current?.focus() }, [success]) const logout = () => { setApiKey('') useUserStore.setState({ apiKey: '' }) setTimeout(() => { licenseKeyRef?.current?.focus() }, 0) } const confirmKey = async (event) => { event.preventDefault() setIsWorking(true) setFeedback('') const { token, error, exception, message } = await UserApi.authenticate( email, apiKey, ) if (typeof message !== 'undefined') { setFeedbackType('error') setIsWorking(false) setFeedback( message.length ? message : 'Error: Are you interacting with the wrong server?', ) return } if (error || exception) { setFeedbackType('error') setIsWorking(false) setFeedback(error.length ? error : exception) return } if (!token || typeof token !== 'string') { setFeedbackType('error') setIsWorking(false) setFeedback(__('Something went wrong', 'extendify')) return } setFeedbackType('success') setFeedback('Success!') setSuccess(true) setIsWorking(false) useUserStore.setState({ email: email, apiKey: token, }) } if (success) { return (

{__("You've signed in to Extendify", 'extendify')}

) } if (loggedIn) { return (

{__('Account', 'extendify')}

{email?.length ? email : __('Logged In', 'extendify')}

{devMode && ( )}
) } return (

{__('Sign in to Extendify', 'extendify')}

{__("Don't have an account?", 'extendify')} {__('Sign up', 'extendify')}

setEmail(event.target.value)} />
setApiKey(event.target.value)} />
{feedback && (
{feedback}
)}
{__('Need Help?', 'extendify')}
) }