Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417import {type ReactNode, useMemo, useState} from 'react'import {View} from 'react-native'import Animated, { FadeIn, FadeOut, LayoutAnimationConfig, LinearTransition,} from 'react-native-reanimated'import {msg} from '@lingui/core/macro'import {useLingui} from '@lingui/react'import {Plural, Trans} from '@lingui/react/macro'
import { createFullHandle, MAX_SERVICE_HANDLE_LENGTH, validateServiceHandle,} from '#/lib/strings/handles'import {logger} from '#/logger'import { checkHandleAvailability, useHandleAvailabilityQuery,} from '#/state/queries/handle-availability'import {useSignupContext} from '#/screens/Signup/state'import {atoms as a, native, useTheme} from '#/alf'import {Button, ButtonIcon, ButtonText} from '#/components/Button'import * as TextField from '#/components/forms/TextField'import {useThrottledValue} from '#/components/hooks/useThrottledValue'import {At_Stroke2_Corner0_Rounded as At} from '#/components/icons/At'import {Check_Stroke2_Corner0_Rounded as Check} from '#/components/icons/Check'import {ChevronBottom_Stroke2_Corner0_Rounded as ChevronDown} from '#/components/icons/Chevron'import * as Menu from '#/components/Menu'import {ScreenTransition} from '#/components/ScreenTransition'import {Text} from '#/components/Typography'import {useAnalytics} from '#/analytics'import {BackNextButtons} from '../BackNextButtons'import {HandleSuggestions} from './HandleSuggestions'
export function StepHandle({ onPressSignIn,}: { onPressSignIn?: (handle: string) => void}) { const {_} = useLingui() const ax = useAnalytics() const t = useTheme() const {state, dispatch} = useSignupContext() const [draftValue, setDraftValue] = useState(state.handle) const [submitFoundTaken, setSubmitFoundTaken] = useState(false) const [selectedDomain, setSelectedDomain] = useState( state.userDomain || state.serviceDescription?.availableUserDomains?.[0] || '', ) const isNextLoading = useThrottledValue(state.isLoading, 500)
// Get available domains from service description const availableDomains = useMemo( () => state.serviceDescription?.availableUserDomains || [], [state.serviceDescription?.availableUserDomains], ) const hasMultipleDomains = useMemo( () => availableDomains.length > 1, [availableDomains], )
const validCheck = validateServiceHandle(draftValue, selectedDomain)
// Real-time handle availability checking const { debouncedUsername: debouncedDraftValue, enabled: queryEnabled, query: {data: isHandleAvailable, isPending}, } = useHandleAvailabilityQuery({ username: draftValue, serviceDid: state.serviceDescription?.did ?? 'UNKNOWN', serviceDomain: selectedDomain, birthDate: state.dateOfBirth.toISOString(), email: state.email, enabled: validCheck.overall, })
// Calculate disabled state based on real-time checking const hasDebounceSettled = draftValue === debouncedDraftValue const isHandleTaken = !isPending && queryEnabled && isHandleAvailable && !isHandleAvailable.available const isNotReady = isPending || !hasDebounceSettled const isNextDisabled = !validCheck.overall || !!state.error || isNotReady ? true : isHandleTaken
const showSignInInstead = !!onPressSignIn && draftValue.length > 0 && ((isHandleTaken && hasDebounceSettled) || submitFoundTaken) const fullDraftHandle = createFullHandle(draftValue.trim(), selectedDomain)
const textFieldInvalid = isHandleTaken || !validCheck.frontLengthNotTooLong || !validCheck.handleChars || !validCheck.hyphenStartOrEnd || !validCheck.totalLength
const onNextPress = async () => { const handle = draftValue.trim()
// Save both handle and domain to state dispatch({ type: 'setHandle', value: handle, }) dispatch({ type: 'setUserDomain', value: selectedDomain, })
if (!validCheck.overall) { return }
dispatch({type: 'setIsLoading', value: true})
try { const {available: handleAvailable} = await checkHandleAvailability( createFullHandle(handle, selectedDomain), state.serviceDescription?.did ?? 'UNKNOWN', {}, )
if (!handleAvailable) { setSubmitFoundTaken(true) dispatch({ type: 'setError', value: _(msg`That handle is already taken.`), field: 'handle', }) return } } catch (error) { logger.error('Failed to check handle availability on next press', { safeMessage: error, }) // Don't block on error - let them proceed } finally { dispatch({type: 'setIsLoading', value: false}) }
ax.metric('signup:nextPressed', { activeStep: state.activeStep, phoneVerificationRequired: state.serviceDescription?.phoneVerificationRequired, })
// phoneVerificationRequired is actually whether a captcha is required if (!state.serviceDescription?.phoneVerificationRequired) { dispatch({ type: 'submit', task: {verificationCode: undefined, mutableProcessed: false}, }) return } dispatch({type: 'next'}) }
const onBackPress = () => { const handle = draftValue.trim() dispatch({ type: 'setHandle', value: handle, }) dispatch({ type: 'setUserDomain', value: selectedDomain, }) dispatch({type: 'prev'}) ax.metric('signup:backPressed', {activeStep: state.activeStep}) }
return ( <ScreenTransition direction={state.screenTransitionDirection ?? 'Forward'}> <View style={[a.gap_sm, a.pt_lg, a.z_10]}> <View> <TextField.Root isInvalid={textFieldInvalid}> <TextField.Icon icon={At} /> <TextField.Input testID="handleInput" onChangeText={val => { if (state.error) { dispatch({type: 'setError', value: ''}) } setSubmitFoundTaken(false) setDraftValue(val.toLowerCase()) }} label={selectedDomain} value={draftValue} keyboardType="ascii-capable" // fix for iOS replacing -- with — autoCapitalize="none" autoCorrect={false} autoFocus autoComplete="off" /> {draftValue.length > 0 && ( <TextField.GhostText value={selectedDomain}> {draftValue} </TextField.GhostText> )} {isHandleAvailable?.available && draftValue.length > 0 && ( <Check size="md" style={{color: t.palette.positive_600}} /> )} </TextField.Root>
{/* Domain selector - only shown if multiple domains are available */} {hasMultipleDomains && ( <View style={[a.mt_md]}> <Text style={[a.text_sm, a.mb_xs, t.atoms.text_contrast_medium]}> <Trans>Domain</Trans> </Text> <Menu.Root> <Menu.Trigger label={_(msg`Select domain`)}> {({props}) => ( <Button {...props} label={_(msg`Select domain`)} variant="solid" color="secondary" size="large" style={[ a.flex_row, a.align_center, a.justify_between, a.w_full, ]}> <View style={[a.flex_1, a.align_start]}> <ButtonText style={[a.text_md, a.font_bold]}> {selectedDomain} </ButtonText> {selectedDomain === availableDomains[0] && ( <Text style={[a.text_xs, t.atoms.text_contrast_medium]}> <Trans>Default</Trans> </Text> )} </View> <ButtonIcon icon={ChevronDown} /> </Button> )} </Menu.Trigger>
<Menu.Outer> <Menu.Group> {availableDomains.map((domain, index) => ( <Menu.Item key={domain} label={domain} onPress={() => { setSubmitFoundTaken(false) setSelectedDomain(domain) }}> <Menu.ItemText> <View style={[a.flex_row, a.align_center, a.gap_sm]}> <Text>{domain}</Text> {index === 0 && ( <Text style={[ a.text_xs, t.atoms.text_contrast_medium, ]}> (<Trans>Default</Trans>) </Text> )} </View> </Menu.ItemText> {selectedDomain === domain && ( <Menu.ItemIcon icon={Check} /> )} </Menu.Item> ))} </Menu.Group> </Menu.Outer> </Menu.Root> </View> )} </View>
{/* Validation messages with animations */} <LayoutAnimationConfig skipEntering skipExiting> <View style={[a.gap_xs]}> {state.error && ( <Requirement> <RequirementText>{state.error}</RequirementText> </Requirement> )} {isHandleTaken && validCheck.overall && ( <> <Requirement> <RequirementText> <Trans> {createFullHandle(draftValue, selectedDomain)} is not available </Trans> </RequirementText> </Requirement> {isHandleAvailable?.suggestions && isHandleAvailable.suggestions.length > 0 && ( <HandleSuggestions suggestions={isHandleAvailable.suggestions} onSelect={suggestion => { // Extract just the handle part without the domain const handlePart = suggestion.handle.includes('.') ? suggestion.handle.split('.')[0] : suggestion.handle.slice( 0, selectedDomain.length * -1, ) setDraftValue(handlePart) ax.metric('signup:handleSuggestionSelected', { method: suggestion.method, }) }} /> )} </> )} {(!validCheck.handleChars || !validCheck.hyphenStartOrEnd) && ( <Requirement> {!validCheck.hyphenStartOrEnd ? ( <RequirementText> <Trans>Username cannot begin or end with a hyphen</Trans> </RequirementText> ) : ( <RequirementText> <Trans> Username must only contain letters (a-z), numbers, and hyphens </Trans> </RequirementText> )} </Requirement> )} {(!validCheck.frontLengthNotTooLong || !validCheck.totalLength) && ( <Requirement> <RequirementText> {!validCheck.totalLength || draftValue.length > MAX_SERVICE_HANDLE_LENGTH ? ( <Trans> Username cannot be longer than{' '} <Plural value={MAX_SERVICE_HANDLE_LENGTH} other="# characters" /> </Trans> ) : ( <Trans>Username must be at least 3 characters</Trans> )} </RequirementText> </Requirement> )} {showSignInInstead && ( <Requirement> <View style={[a.mt_xs, a.align_start]}> <Text style={[a.text_sm, t.atoms.text_contrast_medium]}> <Trans>Is this your account?</Trans> </Text> <Button testID="signInInsteadButton" label={_(msg`Sign in instead`)} variant="ghost" color="primary" size="small" style={[a.mt_xs]} onPress={() => onPressSignIn(fullDraftHandle)}> <ButtonText> <Trans>Sign in as {fullDraftHandle}</Trans> </ButtonText> </Button> </View> </Requirement> )} </View> </LayoutAnimationConfig> </View>
<Animated.View layout={native(LinearTransition)}> <BackNextButtons isLoading={isNextLoading} isNextDisabled={isNextDisabled} onBackPress={onBackPress} onNextPress={onNextPress} /> </Animated.View> </ScreenTransition> )}
function Requirement({children}: {children: ReactNode}) { return ( <Animated.View style={[a.w_full]} layout={native(LinearTransition)} entering={native(FadeIn)} exiting={native(FadeOut)}> {children} </Animated.View> )}
function RequirementText({children}: {children: ReactNode}) { const t = useTheme() return ( <Text style={[a.text_sm, a.flex_1, {color: t.palette.negative_500}]}> {children} </Text> )}