Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418import {createContext, useCallback, useContext} from 'react'import {LayoutAnimation, Platform} from 'react-native'import { ComAtprotoServerCreateAccount, type ComAtprotoServerDescribeServer,} from '@atproto/api'import {useLingui} from '@lingui/react/macro'import * as EmailValidator from 'email-validator'
import {DEFAULT_SERVICE} from '#/lib/constants'import {cleanError} from '#/lib/strings/errors'import {createFullHandle} from '#/lib/strings/handles'import {getAge} from '#/lib/strings/time'import {useSessionApi} from '#/state/session'import {useOnboardingDispatch} from '#/state/shell'import {type AnalyticsContextType, useAnalytics} from '#/analytics'
export type ServiceDescription = ComAtprotoServerDescribeServer.OutputSchema
const date = new Date()date.setFullYear(date.getFullYear() - 20) // default to 20 years agoconst DEFAULT_DATE = date
export enum SignupStep { COMMUNITY, INFO, HANDLE, CAPTCHA,}
/** * On web the community is fixed by the hostname the app is served from, so the * community-picker step is skipped and INFO is the first step. On native the * user chooses their community first. Used as the "floor" step for back/prev. */export const FIRST_SIGNUP_STEP = Platform.OS === 'web' ? SignupStep.INFO : SignupStep.COMMUNITY
type SubmitTask = { verificationCode: string | undefined mutableProcessed: boolean // OK to mutate assuming it's never read in render.}
type ErrorField = | 'invite-code' | 'email' | 'handle' | 'password' | 'date-of-birth'
export type SignupState = { analytics?: AnalyticsContextType
hasPrev: boolean activeStep: SignupStep screenTransitionDirection: 'Forward' | 'Backward'
serviceUrl: string serviceDescription?: ServiceDescription userDomain: string /** Slug of the community selected at signup; stamped on the created account. */ selectedBrandSlug?: string dateOfBirth: Date email: string password: string inviteCode: string handle: string
error: string errorField?: ErrorField isLoading: boolean
pendingSubmit: null | SubmitTask
// Tracking signupStartTime: number fieldErrors: Record<ErrorField, number> backgroundCount: number}
export type SignupAction = | {type: 'setAnalytics'; value: AnalyticsContextType} | {type: 'prev'} | {type: 'next'} | {type: 'finish'} | {type: 'setStep'; value: SignupStep} | {type: 'setServiceUrl'; value: string} | {type: 'setCommunity'; slug: string; serviceUrl: string} | { type: 'setServiceDescription' value: ServiceDescription | undefined availableHandles?: string[] } | {type: 'setUserDomain'; value: string} | {type: 'setEmail'; value: string} | {type: 'setPassword'; value: string} | {type: 'setDateOfBirth'; value: Date} | {type: 'setInviteCode'; value: string} | {type: 'setHandle'; value: string} | {type: 'setError'; value: string; field?: ErrorField} | {type: 'clearError'} | {type: 'setIsLoading'; value: boolean} | {type: 'submit'; task: SubmitTask} | {type: 'incrementBackgroundCount'}
export const initialState: SignupState = { analytics: undefined,
hasPrev: false, activeStep: FIRST_SIGNUP_STEP, screenTransitionDirection: 'Forward',
serviceUrl: DEFAULT_SERVICE, serviceDescription: undefined, userDomain: '', dateOfBirth: DEFAULT_DATE, email: '', password: '', handle: '', inviteCode: '',
error: '', errorField: undefined, isLoading: false,
pendingSubmit: null,
// Tracking signupStartTime: Date.now(), fieldErrors: { 'invite-code': 0, email: 0, handle: 0, password: 0, 'date-of-birth': 0, }, backgroundCount: 0,}
export function is13(date: Date) { return getAge(date) >= 13}
export function is18(date: Date) { return getAge(date) >= 18}
export function reducer(s: SignupState, a: SignupAction): SignupState { let next = {...s}
switch (a.type) { case 'setAnalytics': { next.analytics = a.value break } case 'prev': { if (s.activeStep !== FIRST_SIGNUP_STEP) { next.screenTransitionDirection = 'Backward' next.activeStep-- next.error = '' next.errorField = undefined } break } case 'next': { if (s.activeStep !== SignupStep.CAPTCHA) { next.screenTransitionDirection = 'Forward' next.activeStep++ next.error = '' next.errorField = undefined } break } case 'setStep': { next.activeStep = a.value break } case 'setServiceUrl': { next.serviceUrl = a.value next.userDomain = '' break } case 'setCommunity': { // Selecting a community points signup at that community's PDS; the existing // describeServer pipeline then drives the available handle domains. next.selectedBrandSlug = a.slug next.serviceUrl = a.serviceUrl next.userDomain = '' break } case 'setServiceDescription': { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
const domains = a.value?.availableUserDomains ?? [] const allowed = a.availableHandles const filtered = allowed && allowed.length > 0 ? domains.filter(d => allowed.includes(d)) : domains
next.serviceDescription = a.value ? {...a.value, availableUserDomains: filtered} : a.value if (filtered[0]) { next.userDomain = filtered[0] } next.isLoading = false break } case 'setUserDomain': { next.userDomain = a.value break } case 'setEmail': { next.email = a.value break } case 'setPassword': { next.password = a.value break } case 'setDateOfBirth': { next.dateOfBirth = a.value break } case 'setInviteCode': { next.inviteCode = a.value break } case 'setHandle': { next.handle = a.value break } case 'setIsLoading': { next.isLoading = a.value break } case 'setError': { next.error = a.value next.errorField = a.field
// Track field errors if (a.field) { next.fieldErrors[a.field] = (next.fieldErrors[a.field] || 0) + 1
// Log the field error s.analytics?.metric('signup:fieldError', { field: a.field, errorCount: next.fieldErrors[a.field], errorMessage: a.value, activeStep: next.activeStep, }) } break } case 'clearError': { next.error = '' next.errorField = undefined break } case 'submit': { next.pendingSubmit = a.task break } case 'incrementBackgroundCount': { next.backgroundCount = s.backgroundCount + 1
// Log background/foreground event during signup s.analytics?.metric('signup:backgrounded', { activeStep: next.activeStep, backgroundCount: next.backgroundCount, }) break } }
next.hasPrev = next.activeStep !== FIRST_SIGNUP_STEP
s.analytics?.logger.debug('signup', next)
if (s.activeStep !== next.activeStep) { s.analytics?.logger.debug('signup: step changed', { activeStep: next.activeStep, }) }
return next}
interface IContext { state: SignupState dispatch: React.Dispatch<SignupAction>}export const SignupContext = createContext<IContext>({} as IContext)SignupContext.displayName = 'SignupContext'export const useSignupContext = () => useContext(SignupContext)
export function useSubmitSignup() { const ax = useAnalytics() const {t: l} = useLingui() const {createAccount} = useSessionApi() const onboardingDispatch = useOnboardingDispatch()
return useCallback( async (state: SignupState, dispatch: (action: SignupAction) => void) => { if (!state.email) { dispatch({type: 'setStep', value: SignupStep.INFO}) return dispatch({ type: 'setError', value: l`Please enter your email.`, field: 'email', }) } if (!EmailValidator.validate(state.email)) { dispatch({type: 'setStep', value: SignupStep.INFO}) return dispatch({ type: 'setError', value: l`Your email appears to be invalid.`, field: 'email', }) } if (!state.password) { dispatch({type: 'setStep', value: SignupStep.INFO}) return dispatch({ type: 'setError', value: l`Please choose your password.`, field: 'password', }) } if (!state.handle) { dispatch({type: 'setStep', value: SignupStep.HANDLE}) return dispatch({ type: 'setError', value: l`Please choose your handle.`, field: 'handle', }) } if ( state.serviceDescription?.phoneVerificationRequired && !state.pendingSubmit?.verificationCode ) { dispatch({type: 'setStep', value: SignupStep.CAPTCHA}) ax.logger.error('Signup Flow Error', { errorMessage: 'Verification captcha code was not set.', registrationHandle: state.handle, }) return dispatch({ type: 'setError', value: l`Please complete the verification captcha.`, }) } dispatch({type: 'setError', value: ''}) dispatch({type: 'setIsLoading', value: true})
try { await createAccount( { service: state.serviceUrl, email: state.email, handle: createFullHandle(state.handle, state.userDomain), password: state.password, birthDate: state.dateOfBirth, inviteCode: state.inviteCode.trim(), verificationCode: state.pendingSubmit?.verificationCode, communitySlug: state.selectedBrandSlug, }, { signupDuration: Date.now() - state.signupStartTime, fieldErrorsTotal: Object.values(state.fieldErrors).reduce( (a, b) => a + b, 0, ), backgroundCount: state.backgroundCount, }, )
/* * Must happen last so that if the user has multiple tabs open and * createAccount fails, one tab is not stuck in onboarding — Eric */ onboardingDispatch({type: 'start'}) } catch (err) { const e = err as Error let errMsg = e.toString() if (e instanceof ComAtprotoServerCreateAccount.InvalidInviteCodeError) { dispatch({ type: 'setError', value: l`Invite code not accepted. Check that you input it correctly and try again.`, field: 'invite-code', }) dispatch({type: 'setStep', value: SignupStep.INFO}) return }
const error = cleanError(errMsg) const isHandleError = error.toLowerCase().includes('handle')
dispatch({type: 'setIsLoading', value: false}) dispatch({ type: 'setError', value: error, field: isHandleError ? 'handle' : undefined, }) dispatch({type: 'setStep', value: isHandleError ? 2 : 1})
ax.logger.error('Signup Flow Error', { errorMessage: error, registrationHandle: state.handle, selectedDomain: state.userDomain, // Include domain in error logs }) } finally { dispatch({type: 'setIsLoading', value: false}) } }, [l, ax.logger, createAccount, onboardingDispatch], )}