Address lint warnings (#10188)

This commit is contained in:
DS Boyce
2026-04-08 15:54:43 -07:00
committed by GitHub
parent e4b4e48acb
commit d0d00ba9f8
15 changed files with 170 additions and 173 deletions
+2 -2
View File
@@ -215,11 +215,11 @@ function InnerApp() {
} }
function App() { function App() {
const [isReady, setReady] = useState(false) const [isReady, setIsReady] = useState(false)
useEffect(() => { useEffect(() => {
void Promise.all([initPersistedState(), Geo.resolve(), setupDeviceId]).then( void Promise.all([initPersistedState(), Geo.resolve(), setupDeviceId]).then(
() => setReady(true), () => setIsReady(true),
) )
}, []) }, [])
+2 -2
View File
@@ -194,11 +194,11 @@ function InnerApp() {
} }
function App() { function App() {
const [isReady, setReady] = useState(false) const [isReady, setIsReady] = useState(false)
useEffect(() => { useEffect(() => {
void Promise.all([initPersistedState(), Geo.resolve(), setupDeviceId]).then( void Promise.all([initPersistedState(), Geo.resolve(), setupDeviceId]).then(
() => setReady(true), () => setIsReady(true),
) )
}, []) }, [])
+12 -12
View File
@@ -105,19 +105,18 @@ export function getConfigFromCache():
) )
} }
let configPrefetchPromise: Promise<void> | undefined let configPrefetchPromise: Promise<void> | undefined
export async function prefetchConfig() { export function prefetchConfig() {
if (configPrefetchPromise) { if (configPrefetchPromise) {
logger.debug(`prefetchAgeAssuranceConfig: already in progress`) logger.debug(`prefetchAgeAssuranceConfig: already in progress`)
return return
} }
configPrefetchPromise = new Promise(async resolve => { configPrefetchPromise = (async () => {
await cacheHydrationPromise await cacheHydrationPromise
const cached = getConfigFromCache() const cached = getConfigFromCache()
if (cached) { if (cached) {
logger.debug(`prefetchAgeAssuranceConfig: using cache`) logger.debug(`prefetchAgeAssuranceConfig: using cache`)
resolve()
} else { } else {
try { try {
logger.debug(`prefetchAgeAssuranceConfig: resolving...`) logger.debug(`prefetchAgeAssuranceConfig: resolving...`)
@@ -126,15 +125,14 @@ export async function prefetchConfig() {
configQueryKey, configQueryKey,
res, res,
) )
} catch (e: any) { } catch (err) {
const e = err as Error
logger.warn(`prefetchAgeAssuranceConfig: failed`, { logger.warn(`prefetchAgeAssuranceConfig: failed`, {
safeMessage: e.message, safeMessage: e.message,
}) })
} finally {
resolve()
} }
} }
}) })()
} }
export async function refetchConfig() { export async function refetchConfig() {
logger.debug(`refetchConfig: fetching...`) logger.debug(`refetchConfig: fetching...`)
@@ -228,7 +226,8 @@ export async function prefetchServerState({agent}: {agent: AtpAgent}) {
logger.debug(`prefetchServerState: resolving...`) logger.debug(`prefetchServerState: resolving...`)
const res = await networkRetry(3, () => getServerState({agent})) const res = await networkRetry(3, () => getServerState({agent}))
qc.setQueryData<AppBskyAgeassuranceGetState.OutputSchema>(qk, res) qc.setQueryData<AppBskyAgeassuranceGetState.OutputSchema>(qk, res)
} catch (e: any) { } catch (err) {
const e = err as Error
logger.warn(`prefetchServerState: failed`, { logger.warn(`prefetchServerState: failed`, {
safeMessage: e.message, safeMessage: e.message,
}) })
@@ -248,7 +247,7 @@ export async function refetchServerState({agent}: {agent: AtpAgent}) {
export function usePatchServerState() { export function usePatchServerState() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
return useCallback( return useCallback(
async (next: AppBskyAgeassuranceDefs.State) => { (next: AppBskyAgeassuranceDefs.State) => {
if (!currentAccount) return if (!currentAccount) return
const did = currentAccount.did const did = currentAccount.did
const prev = getServerStateFromCache({did}) const prev = getServerStateFromCache({did})
@@ -313,7 +312,7 @@ export function useServerStateQuery() {
// only refetch when needed // only refetch when needed
if (isAssured || !isAArequired) return if (isAssured || !isAArequired) return
refetch() void refetch()
}) })
}, [did, refetch, isAssured]) }, [did, refetch, isAssured])
@@ -409,7 +408,8 @@ export async function prefetchOtherRequiredData({agent}: {agent: AtpAgent}) {
logger.debug(`prefetchOtherRequiredData: resolving...`) logger.debug(`prefetchOtherRequiredData: resolving...`)
const res = await networkRetry(3, () => getOtherRequiredData({agent})) const res = await networkRetry(3, () => getOtherRequiredData({agent}))
qc.setQueryData<OtherRequiredData>(qk, res) qc.setQueryData<OtherRequiredData>(qk, res)
} catch (e: any) { } catch (err) {
const e = err as Error
logger.warn(`prefetchOtherRequiredData: failed`, { logger.warn(`prefetchOtherRequiredData: failed`, {
safeMessage: e.message, safeMessage: e.message,
}) })
@@ -418,7 +418,7 @@ export async function prefetchOtherRequiredData({agent}: {agent: AtpAgent}) {
export function usePatchOtherRequiredData() { export function usePatchOtherRequiredData() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
return useCallback( return useCallback(
async (next: OtherRequiredData) => { (next: OtherRequiredData) => {
if (!currentAccount) return if (!currentAccount) return
const did = currentAccount.did const did = currentAccount.did
const prev = getOtherRequiredDataFromCache({did}) const prev = getOtherRequiredDataFromCache({did})
+1 -1
View File
@@ -85,7 +85,7 @@ function InnerProvider({children}: {children: React.ReactNode}) {
const handleAccessUpdate = useCallback( const handleAccessUpdate = useCallback(
(s: AgeAssuranceState) => { (s: AgeAssuranceState) => {
getAndRegisterPushToken({ void getAndRegisterPushToken({
isAgeRestricted: s.access !== AgeAssuranceAccess.Full, isAgeRestricted: s.access !== AgeAssuranceAccess.Full,
}) })
}, },
+1
View File
@@ -99,6 +99,7 @@ export function useOnAgeAssuranceAccessUpdate(
useEffect(() => { useEffect(() => {
if (prevAccess !== state.access) { if (prevAccess !== state.access) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setPrevAccess(state.access) setPrevAccess(state.access)
cb(state) cb(state)
logger.debug(`useOnAgeAssuranceAccessUpdate`, {state}) logger.debug(`useOnAgeAssuranceAccessUpdate`, {state})
+11 -9
View File
@@ -161,7 +161,9 @@ export function SettingsScreen({}: Props) {
p => p.did === account.did, p => p.did === account.did,
)} )}
pendingDid={pendingDid} pendingDid={pendingDid}
onPressSwitchAccount={onPressSwitchAccount} onPressSwitchAccount={(account, logContext) =>
void onPressSwitchAccount(account, logContext)
}
/> />
))} ))}
<AddAccountRow /> <AddAccountRow />
@@ -245,7 +247,7 @@ export function SettingsScreen({}: Props) {
</SettingsList.ItemText> </SettingsList.ItemText>
</SettingsList.LinkItem> </SettingsList.LinkItem>
<SettingsList.PressableItem <SettingsList.PressableItem
onPress={() => Linking.openURL(HELP_DESK_URL)} onPress={() => void Linking.openURL(HELP_DESK_URL)}
label={_(msg`Help`)} label={_(msg`Help`)}
accessibilityHint={_(msg`Opens helpdesk in browser`)}> accessibilityHint={_(msg`Opens helpdesk in browser`)}>
<SettingsList.ItemIcon icon={CircleQuestionIcon} /> <SettingsList.ItemIcon icon={CircleQuestionIcon} />
@@ -392,7 +394,7 @@ function DevOptions() {
} = useApplyPullRequestOTAUpdate() } = useApplyPullRequestOTAUpdate()
const [actyNotifNudged, setActyNotifNudged] = useActivitySubscriptionsNudged() const [actyNotifNudged, setActyNotifNudged] = useActivitySubscriptionsNudged()
const resetOnboarding = async () => { const resetOnboarding = () => {
navigation.navigate('Home') navigation.navigate('Home')
onboardingDispatch({type: 'start'}) onboardingDispatch({type: 'start'})
Toast.show(_(msg`Onboarding reset`)) Toast.show(_(msg`Onboarding reset`))
@@ -407,7 +409,7 @@ function DevOptions() {
const lastEmailConfirm = new Date() const lastEmailConfirm = new Date()
// wind back 3 days // wind back 3 days
lastEmailConfirm.setDate(lastEmailConfirm.getDate() - 3) lastEmailConfirm.setDate(lastEmailConfirm.getDate() - 3)
persisted.write('reminders', { void persisted.write('reminders', {
...persisted.get('reminders'), ...persisted.get('reminders'),
lastEmailConfirm: lastEmailConfirm.toISOString(), lastEmailConfirm: lastEmailConfirm.toISOString(),
}) })
@@ -431,7 +433,7 @@ function DevOptions() {
style: 'default', style: 'default',
text: 'Apply', text: 'Apply',
onPress: (channel?: string) => { onPress: (channel?: string) => {
tryApplyUpdate(channel ?? '') void tryApplyUpdate(channel ?? '')
}, },
}, },
], ],
@@ -473,7 +475,7 @@ function DevOptions() {
</SettingsList.ItemText> </SettingsList.ItemText>
</SettingsList.PressableItem> </SettingsList.PressableItem>
<SettingsList.PressableItem <SettingsList.PressableItem
onPress={() => resetOnboarding()} onPress={() => void resetOnboarding()}
label={_(msg`Reset onboarding state`)}> label={_(msg`Reset onboarding state`)}>
<SettingsList.ItemText> <SettingsList.ItemText>
<Trans>Reset onboarding state</Trans> <Trans>Reset onboarding state</Trans>
@@ -496,7 +498,7 @@ function DevOptions() {
</SettingsList.PressableItem> </SettingsList.PressableItem>
)} )}
<SettingsList.PressableItem <SettingsList.PressableItem
onPress={() => clearAllStorage()} onPress={() => void clearAllStorage()}
label={_(msg`Clear all storage data`)}> label={_(msg`Clear all storage data`)}>
<SettingsList.ItemText> <SettingsList.ItemText>
<Trans>Clear all storage data (restart after this)</Trans> <Trans>Clear all storage data (restart after this)</Trans>
@@ -513,7 +515,7 @@ function DevOptions() {
) : null} ) : null}
{IS_NATIVE && isCurrentlyRunningPullRequestDeployment ? ( {IS_NATIVE && isCurrentlyRunningPullRequestDeployment ? (
<SettingsList.PressableItem <SettingsList.PressableItem
onPress={revertToEmbedded} onPress={() => void revertToEmbedded()}
label={_(msg`Unapply Pull Request`)}> label={_(msg`Unapply Pull Request`)}>
<SettingsList.ItemText> <SettingsList.ItemText>
<Trans>Unapply Pull Request {currentChannel}</Trans> <Trans>Unapply Pull Request {currentChannel}</Trans>
@@ -543,7 +545,7 @@ function DevOptions() {
<Button <Button
onPress={() => { onPress={() => {
device.set([PolicyUpdate202508], false) device.set([PolicyUpdate202508], false)
agent.bskyAppRemoveNuxs([PolicyUpdate202508]) void agent.bskyAppRemoveNuxs([PolicyUpdate202508])
Toast.show(`Done`, { Toast.show(`Done`, {
type: 'info', type: 'info',
}) })
@@ -48,9 +48,9 @@ export function CaptchaWebView({
return return
} }
onSuccess(code) onSuccess(code)
} catch (e: unknown) { } catch (e) {
// We don't actually want to record an error here, because this will happen quite a bit. We will only be able to // We don't actually want to record an error here, because this will happen quite a bit. We will only be able to
// get hte href of the iframe if it's on our domain, so all the hcaptcha requests will throw here, although it's // get the href of the iframe if it's on our domain, so all the hcaptcha requests will throw here, although it's
// harmless. Our other indicators of time-to-complete and back press should be more reliable in catching issues. // harmless. Our other indicators of time-to-complete and back press should be more reliable in catching issues.
} }
}, [stateParam, onSuccess, onError]) }, [stateParam, onSuccess, onError])
+3 -2
View File
@@ -34,7 +34,7 @@ export function StepCaptchaNative() {
const [ready, setReady] = useState(false) const [ready, setReady] = useState(false)
useEffect(() => { useEffect(() => {
;(async () => { void (async () => {
logger.debug('trying to generate attestation token...') logger.debug('trying to generate attestation token...')
try { try {
if (IS_IOS) { if (IS_IOS) {
@@ -48,7 +48,8 @@ export function StepCaptchaNative() {
setToken(token) setToken(token)
setPayload(base64UrlEncode(payload)) setPayload(base64UrlEncode(payload))
} }
} catch (e: any) { } catch (err) {
const e = err as Error
logger.error(e) logger.error(e)
} finally { } finally {
setReady(true) setReady(true)
+18 -24
View File
@@ -1,8 +1,6 @@
import {useEffect, useRef, useState} from 'react' import {useEffect, useRef, useState} from 'react'
import {type TextInput, View} from 'react-native' import {type TextInput, View} from 'react-native'
import {msg} from '@lingui/core/macro' import {Plural, Trans, useLingui} from '@lingui/react/macro'
import {useLingui} from '@lingui/react'
import {Plural, Trans} from '@lingui/react/macro'
import * as EmailValidator from 'email-validator' import * as EmailValidator from 'email-validator'
import type tldts from 'tldts' import type tldts from 'tldts'
@@ -60,7 +58,7 @@ export function StepInfo({
refetchServer: () => void refetchServer: () => void
isLoadingStarterPack: boolean isLoadingStarterPack: boolean
}) { }) {
const {_} = useLingui() const {t: l} = useLingui()
const ax = useAnalytics() const ax = useAnalytics()
const {state, dispatch} = useSignupContext() const {state, dispatch} = useSignupContext()
const preemptivelyCompleteActivePolicyUpdate = const preemptivelyCompleteActivePolicyUpdate =
@@ -94,12 +92,12 @@ export function StepInfo({
const tldtsRef = useRef<typeof tldts>(undefined) const tldtsRef = useRef<typeof tldts>(undefined)
useEffect(() => { useEffect(() => {
// @ts-expect-error - valid path // @ts-expect-error - valid path
import('tldts/dist/index.cjs.min.js').then(tldts => { void import('tldts/dist/index.cjs.min.js').then(tldts => {
tldtsRef.current = tldts tldtsRef.current = tldts
}) })
// This will get used in the avatar creator a few steps later, so lets preload it now // This will get used in the avatar creator a few steps later, so lets preload it now
// @ts-expect-error - valid path // @ts-expect-error - valid path
import('react-native-view-shot/src/index') void import('react-native-view-shot/src/index')
}, []) }, [])
const onNextPress = () => { const onNextPress = () => {
@@ -115,21 +113,21 @@ export function StepInfo({
if (state.serviceDescription?.inviteCodeRequired && !inviteCode) { if (state.serviceDescription?.inviteCodeRequired && !inviteCode) {
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Please enter your invite code.`), value: l`Please enter your invite code.`,
field: 'invite-code', field: 'invite-code',
}) })
} }
if (!email) { if (!email) {
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Please enter your email.`), value: l`Please enter your email.`,
field: 'email', field: 'email',
}) })
} }
if (!EmailValidator.validate(email)) { if (!EmailValidator.validate(email)) {
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Your email appears to be invalid.`), value: l`Your email appears to be invalid.`,
field: 'email', field: 'email',
}) })
} }
@@ -139,9 +137,7 @@ export function StepInfo({
setHasWarnedEmail(true) setHasWarnedEmail(true)
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _( value: l`Please double-check that you have entered your email address correctly.`,
msg`Please double-check that you have entered your email address correctly.`,
),
}) })
} }
} else if (hasWarnedEmail) { } else if (hasWarnedEmail) {
@@ -151,14 +147,14 @@ export function StepInfo({
if (!password) { if (!password) {
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Please choose your password.`), value: l`Please choose your password.`,
field: 'password', field: 'password',
}) })
} }
if (password.length < 8) { if (password.length < 8) {
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Your password must be at least 8 characters long.`), value: l`Your password must be at least 8 characters long.`,
field: 'password', field: 'password',
}) })
} }
@@ -205,7 +201,7 @@ export function StepInfo({
dispatch({type: 'clearError'}) dispatch({type: 'clearError'})
} }
}} }}
label={_(msg`Required for this provider`)} label={l`Required for this provider`}
defaultValue={state.inviteCode} defaultValue={state.inviteCode}
autoCapitalize="none" autoCapitalize="none"
autoComplete="email" autoComplete="email"
@@ -241,7 +237,7 @@ export function StepInfo({
dispatch({type: 'clearError'}) dispatch({type: 'clearError'})
} }
}} }}
label={_(msg`Enter your email address`)} label={l`Enter your email address`}
defaultValue={state.email} defaultValue={state.email}
autoCapitalize="none" autoCapitalize="none"
autoComplete="email" autoComplete="email"
@@ -269,7 +265,7 @@ export function StepInfo({
dispatch({type: 'clearError'}) dispatch({type: 'clearError'})
} }
}} }}
label={_(msg`Choose your password`)} label={l`Choose your password`}
defaultValue={state.password} defaultValue={state.password}
secureTextEntry secureTextEntry
autoComplete="new-password" autoComplete="new-password"
@@ -297,8 +293,8 @@ export function StepInfo({
value: sanitizeDate(new Date(date)), value: sanitizeDate(new Date(date)),
}) })
}} }}
label={_(msg`Date of birth`)} label={l`Date of birth`}
accessibilityHint={_(msg`Select your date of birth`)} accessibilityHint={l`Select your date of birth`}
maximumDate={new Date()} maximumDate={new Date()}
/> />
</View> </View>
@@ -331,9 +327,7 @@ export function StepInfo({
<Trans> <Trans>
Have we got your location wrong?{' '} Have we got your location wrong?{' '}
<SimpleInlineLinkText <SimpleInlineLinkText
label={_( label={l`Tap here to confirm your location with GPS.`}
msg`Tap here to confirm your location with GPS.`,
)}
{...createStaticClick(() => { {...createStaticClick(() => {
locationControl.open() locationControl.open()
})}> })}>
@@ -363,7 +357,7 @@ export function StepInfo({
props.closeDialog(() => { props.closeDialog(() => {
// set this after close! // set this after close!
setDeviceGeolocation(props.geolocation) setDeviceGeolocation(props.geolocation)
Toast.show(_(msg`Your location has been updated.`), { Toast.show(l`Your location has been updated.`, {
type: 'success', type: 'success',
}) })
}) })
@@ -380,7 +374,7 @@ export function StepInfo({
onBackPress={onPressBack} onBackPress={onPressBack}
onNextPress={onNextPress} onNextPress={onNextPress}
onRetryPress={refetchServer} onRetryPress={refetchServer}
overrideNextText={hasWarnedEmail ? _(msg`It's correct`) : undefined} overrideNextText={hasWarnedEmail ? l`It's correct` : undefined}
/> />
</> </>
) )
+12 -13
View File
@@ -3,9 +3,7 @@ import {AppState, type AppStateStatus, View} from 'react-native'
import ReactNativeDeviceAttest from 'react-native-device-attest' import ReactNativeDeviceAttest from 'react-native-device-attest'
import Animated, {FadeIn, LayoutAnimationConfig} from 'react-native-reanimated' import Animated, {FadeIn, LayoutAnimationConfig} from 'react-native-reanimated'
import {AppBskyGraphStarterpack} from '@atproto/api' import {AppBskyGraphStarterpack} from '@atproto/api'
import {msg} from '@lingui/core/macro' import {Trans, useLingui} from '@lingui/react/macro'
import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro'
import {FEEDBACK_FORM_URL} from '#/lib/constants' import {FEEDBACK_FORM_URL} from '#/lib/constants'
import {logger} from '#/logger' import {logger} from '#/logger'
@@ -36,7 +34,7 @@ import * as bsky from '#/types/bsky'
export function Signup({onPressBack}: {onPressBack: () => void}) { export function Signup({onPressBack}: {onPressBack: () => void}) {
const ax = useAnalytics() const ax = useAnalytics()
const {_} = useLingui() const {t: l} = useLingui()
const t = useTheme() const t = useTheme()
const [state, dispatch] = useReducer(reducer, { const [state, dispatch] = useReducer(reducer, {
...initialState, ...initialState,
@@ -61,6 +59,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
uri: activeStarterPack?.uri, uri: activeStarterPack?.uri,
}) })
// eslint-disable-next-line react/hook-use-state
const [isFetchedAtMount] = useState(starterPack != null) const [isFetchedAtMount] = useState(starterPack != null)
const showStarterPackCard = const showStarterPackCard =
activeStarterPack?.uri && !isFetchingStarterPack && starterPack activeStarterPack?.uri && !isFetchingStarterPack && starterPack
@@ -85,21 +84,21 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
dispatch({type: 'setServiceDescription', value: undefined}) dispatch({type: 'setServiceDescription', value: undefined})
dispatch({ dispatch({
type: 'setError', type: 'setError',
value: _( value: l`Unable to contact your service. Please check your Internet connection.`,
msg`Unable to contact your service. Please check your Internet connection.`,
),
}) })
} else if (serviceInfo) { } else if (serviceInfo) {
dispatch({type: 'setServiceDescription', value: serviceInfo}) dispatch({type: 'setServiceDescription', value: serviceInfo})
dispatch({type: 'setError', value: ''}) dispatch({type: 'setError', value: ''})
} }
}, [_, serviceInfo, isError]) }, [l, serviceInfo, isError])
useEffect(() => { useEffect(() => {
if (state.pendingSubmit) { if (state.pendingSubmit) {
if (!state.pendingSubmit.mutableProcessed) { if (!state.pendingSubmit.mutableProcessed) {
// OK to mutate assuming it's never read in render.
// eslint-disable-next-line react-hooks/immutability, react-compiler/react-compiler
state.pendingSubmit.mutableProcessed = true state.pendingSubmit.mutableProcessed = true
submit(state, dispatch) void submit(state, dispatch)
} }
} }
}, [state, dispatch, submit]) }, [state, dispatch, submit])
@@ -133,8 +132,8 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
<SignupContext.Provider value={{state, dispatch}}> <SignupContext.Provider value={{state, dispatch}}>
<LoggedOutLayout <LoggedOutLayout
leadin="" leadin=""
title={_(msg`Create Account`)} title={l`Create account`}
description={_(msg`We're so excited to have you join us!`)} description={l`We’re so excited to have you join us!`}
scrollable> scrollable>
<View testID="createAccount" style={a.flex_1}> <View testID="createAccount" style={a.flex_1}>
{showStarterPackCard && {showStarterPackCard &&
@@ -204,7 +203,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
isFetchingStarterPack && !isErrorStarterPack isFetchingStarterPack && !isErrorStarterPack
} }
isServerError={isError} isServerError={isError}
refetchServer={refetch} refetchServer={() => void refetch()}
/> />
) : state.activeStep === SignupStep.HANDLE ? ( ) : state.activeStep === SignupStep.HANDLE ? (
<StepHandle /> <StepHandle />
@@ -231,7 +230,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
]}> ]}>
<Trans>Having trouble?</Trans>{' '} <Trans>Having trouble?</Trans>{' '}
<InlineLinkText <InlineLinkText
label={_(msg`Contact support`)} label={l`Contact support`}
to={FEEDBACK_FORM_URL({email: state.email})} to={FEEDBACK_FORM_URL({email: state.email})}
style={[!gtMobile && a.text_md]}> style={[!gtMobile && a.text_md]}>
<Trans>Contact support</Trans> <Trans>Contact support</Trans>
+14 -14
View File
@@ -4,8 +4,7 @@ import {
ComAtprotoServerCreateAccount, ComAtprotoServerCreateAccount,
type ComAtprotoServerDescribeServer, type ComAtprotoServerDescribeServer,
} from '@atproto/api' } from '@atproto/api'
import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react/macro'
import {useLingui} from '@lingui/react'
import * as EmailValidator from 'email-validator' import * as EmailValidator from 'email-validator'
import {DEFAULT_SERVICE} from '#/lib/constants' import {DEFAULT_SERVICE} from '#/lib/constants'
@@ -18,7 +17,9 @@ import {type AnalyticsContextType, useAnalytics} from '#/analytics'
export type ServiceDescription = ComAtprotoServerDescribeServer.OutputSchema export type ServiceDescription = ComAtprotoServerDescribeServer.OutputSchema
const DEFAULT_DATE = new Date(Date.now() - 60e3 * 60 * 24 * 365 * 20) // default to 20 years ago const date = new Date()
date.setFullYear(date.getFullYear() - 20) // default to 20 years ago
const DEFAULT_DATE = date
export enum SignupStep { export enum SignupStep {
INFO, INFO,
@@ -256,7 +257,7 @@ export const useSignupContext = () => useContext(SignupContext)
export function useSubmitSignup() { export function useSubmitSignup() {
const ax = useAnalytics() const ax = useAnalytics()
const {_} = useLingui() const {t: l} = useLingui()
const {createAccount} = useSessionApi() const {createAccount} = useSessionApi()
const onboardingDispatch = useOnboardingDispatch() const onboardingDispatch = useOnboardingDispatch()
@@ -266,7 +267,7 @@ export function useSubmitSignup() {
dispatch({type: 'setStep', value: SignupStep.INFO}) dispatch({type: 'setStep', value: SignupStep.INFO})
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Please enter your email.`), value: l`Please enter your email.`,
field: 'email', field: 'email',
}) })
} }
@@ -274,7 +275,7 @@ export function useSubmitSignup() {
dispatch({type: 'setStep', value: SignupStep.INFO}) dispatch({type: 'setStep', value: SignupStep.INFO})
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Your email appears to be invalid.`), value: l`Your email appears to be invalid.`,
field: 'email', field: 'email',
}) })
} }
@@ -282,7 +283,7 @@ export function useSubmitSignup() {
dispatch({type: 'setStep', value: SignupStep.INFO}) dispatch({type: 'setStep', value: SignupStep.INFO})
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Please choose your password.`), value: l`Please choose your password.`,
field: 'password', field: 'password',
}) })
} }
@@ -290,7 +291,7 @@ export function useSubmitSignup() {
dispatch({type: 'setStep', value: SignupStep.HANDLE}) dispatch({type: 'setStep', value: SignupStep.HANDLE})
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Please choose your handle.`), value: l`Please choose your handle.`,
field: 'handle', field: 'handle',
}) })
} }
@@ -305,7 +306,7 @@ export function useSubmitSignup() {
}) })
return dispatch({ return dispatch({
type: 'setError', type: 'setError',
value: _(msg`Please complete the verification captcha.`), value: l`Please complete the verification captcha.`,
}) })
} }
dispatch({type: 'setError', value: ''}) dispatch({type: 'setError', value: ''})
@@ -337,14 +338,13 @@ export function useSubmitSignup() {
* createAccount fails, one tab is not stuck in onboarding — Eric * createAccount fails, one tab is not stuck in onboarding — Eric
*/ */
onboardingDispatch({type: 'start'}) onboardingDispatch({type: 'start'})
} catch (e: any) { } catch (err) {
const e = err as Error
let errMsg = e.toString() let errMsg = e.toString()
if (e instanceof ComAtprotoServerCreateAccount.InvalidInviteCodeError) { if (e instanceof ComAtprotoServerCreateAccount.InvalidInviteCodeError) {
dispatch({ dispatch({
type: 'setError', type: 'setError',
value: _( value: l`Invite code not accepted. Check that you input it correctly and try again.`,
msg`Invite code not accepted. Check that you input it correctly and try again.`,
),
field: 'invite-code', field: 'invite-code',
}) })
dispatch({type: 'setStep', value: SignupStep.INFO}) dispatch({type: 'setStep', value: SignupStep.INFO})
@@ -370,6 +370,6 @@ export function useSubmitSignup() {
dispatch({type: 'setIsLoading', value: false}) dispatch({type: 'setIsLoading', value: false})
} }
}, },
[_, onboardingDispatch, createAccount], [l, ax.logger, createAccount, onboardingDispatch],
) )
} }
+1 -1
View File
@@ -14,7 +14,7 @@ const BIRTHDATE_DELAY_HOURS = IS_DEV ? 0.001 : 48
* Stores the timestamp of the birthday update locally. This is used to * Stores the timestamp of the birthday update locally. This is used to
* debounce birthday updates globally. * debounce birthday updates globally.
* *
* Use {@link useIsBirthDateUpdateAllowed} to check if an update is allowed. * Use {@link useIsBirthdateUpdateAllowed} to check if an update is allowed.
*/ */
export function snoozeBirthdateUpdateAllowedForDid(did: string) { export function snoozeBirthdateUpdateAllowedForDid(did: string) {
account.set([did, 'birthdateLastUpdatedAt'], new Date().toISOString()) account.set([did, 'birthdateLastUpdatedAt'], new Date().toISOString())
@@ -52,7 +52,7 @@ export function useUpdateActorDeclaration({
onError: error => { onError: error => {
logger.error(error) logger.error(error)
if (currentAccount) { if (currentAccount) {
queryClient.invalidateQueries({ void queryClient.invalidateQueries({
queryKey: PROFILE_RKEY(currentAccount.did), queryKey: PROFILE_RKEY(currentAccount.did),
}) })
} }
+9 -12
View File
@@ -181,8 +181,7 @@ export async function createAgentAndCreateAccount(
// Not awaited so that we can still get into onboarding. // Not awaited so that we can still get into onboarding.
// This is OK because we won't let you toggle adult stuff until you set the date. // This is OK because we won't let you toggle adult stuff until you set the date.
if (IS_PROD_SERVICE(service)) { if (IS_PROD_SERVICE(service)) {
Promise.allSettled( void Promise.allSettled([
[
networkRetry(3, () => { networkRetry(3, () => {
return agent.setPersonalDetails({ return agent.setPersonalDetails({
birthDate: birthdate, birthDate: birthdate,
@@ -216,12 +215,11 @@ export async function createAgentAndCreateAccount(
}, },
]) ])
}).catch(e => { }).catch(e => {
logger.info( logger.info(`createAgentAndCreateAccount: failed to set initial feeds`)
`createAgentAndCreateAccount: failed to set initial feeds`,
)
throw e throw e
}), }),
getAge(birthDate) < 18 && ...(getAge(birthDate) < 18
? [
networkRetry(3, () => { networkRetry(3, () => {
return agent.com.atproto.repo.putRecord({ return agent.com.atproto.repo.putRecord({
repo: account.did, repo: account.did,
@@ -238,8 +236,9 @@ export async function createAgentAndCreateAccount(
) )
throw e throw e
}), }),
].filter(Boolean), ]
).then(promises => { : []),
]).then(promises => {
const rejected = promises.filter(p => p.status === 'rejected') const rejected = promises.filter(p => p.status === 'rejected')
if (rejected.length > 0) { if (rejected.length > 0) {
logger.error( logger.error(
@@ -248,8 +247,7 @@ export async function createAgentAndCreateAccount(
} }
}) })
} else { } else {
Promise.allSettled( void Promise.allSettled([
[
networkRetry(3, () => { networkRetry(3, () => {
return agent.setPersonalDetails({ return agent.setPersonalDetails({
birthDate: birthDate.toISOString(), birthDate: birthDate.toISOString(),
@@ -270,8 +268,7 @@ export async function createAgentAndCreateAccount(
) )
throw e throw e
}), }),
].filter(Boolean), ]).then(promises => {
).then(promises => {
const rejected = promises.filter(p => p.status === 'rejected') const rejected = promises.filter(p => p.status === 'rejected')
if (rejected.length > 0) { if (rejected.length > 0) {
logger.error( logger.error(
+10 -7
View File
@@ -8,7 +8,7 @@ import {
useState, useState,
useSyncExternalStore, useSyncExternalStore,
} from 'react' } from 'react'
import {type AtpSessionEvent, type BskyAgent} from '@atproto/api' import {type AtpAgent, type AtpSessionEvent} from '@atproto/api'
import * as persisted from '#/state/persisted' import * as persisted from '#/state/persisted'
import {useCloseAllActiveElements} from '#/state/util' import {useCloseAllActiveElements} from '#/state/util'
@@ -47,7 +47,7 @@ const StateContext = createContext<SessionStateContext>({
}) })
StateContext.displayName = 'SessionStateContext' StateContext.displayName = 'SessionStateContext'
const AgentContext = createContext<BskyAgent | null>(null) const AgentContext = createContext<AtpAgent | null>(null)
AgentContext.displayName = 'SessionAgentContext' AgentContext.displayName = 'SessionAgentContext'
const ApiContext = createContext<SessionApiContext>({ const ApiContext = createContext<SessionApiContext>({
@@ -96,7 +96,7 @@ class SessionStore {
), ),
} }
addSessionDebugLog({type: 'persisted:broadcast', data: persistedData}) addSessionDebugLog({type: 'persisted:broadcast', data: persistedData})
persisted.write('session', persistedData) void persisted.write('session', persistedData)
} }
this.listeners.forEach(listener => listener()) this.listeners.forEach(listener => listener())
} }
@@ -105,12 +105,13 @@ class SessionStore {
export function Provider({children}: React.PropsWithChildren<{}>) { export function Provider({children}: React.PropsWithChildren<{}>) {
const ax = useAnalyticsBase() const ax = useAnalyticsBase()
const cancelPendingTask = useOneTaskAtATime() const cancelPendingTask = useOneTaskAtATime()
// eslint-disable-next-line react/hook-use-state
const [store] = useState(() => new SessionStore()) const [store] = useState(() => new SessionStore())
const state = useSyncExternalStore(store.subscribe, store.getState) const state = useSyncExternalStore(store.subscribe, store.getState)
const onboardingDispatch = useOnboardingDispatch() const onboardingDispatch = useOnboardingDispatch()
const onAgentSessionChange = useCallback( const onAgentSessionChange = useCallback(
(agent: BskyAgent, accountDid: string, sessionEvent: AtpSessionEvent) => { (agent: AtpAgent, accountDid: string, sessionEvent: AtpSessionEvent) => {
const refreshedAccount = agentToSessionAccount(agent) // Mutable, so snapshot it right away. const refreshedAccount = agentToSessionAccount(agent) // Mutable, so snapshot it right away.
if (sessionEvent === 'expired' || sessionEvent === 'create-failed') { if (sessionEvent === 'expired' || sessionEvent === 'create-failed') {
emitSessionDropped() emitSessionDropped()
@@ -327,10 +328,11 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
* follower tabs. Follower tabs will therefore receive the fresh * follower tabs. Follower tabs will therefore receive the fresh
* session. See APP-1960, or ask Eric. * session. See APP-1960, or ask Eric.
*/ */
resumeSession(syncedAccount) void resumeSession(syncedAccount)
} else { } else {
const agent = state.currentAgentState.agent as BskyAgent const agent = state.currentAgentState.agent as AtpAgent
const prevSession = agent.session const prevSession = agent.session
// eslint-disable-next-line react-compiler/react-compiler
agent.sessionManager.session = sessionAccountToSession(syncedAccount) agent.sessionManager.session = sessionAccountToSession(syncedAccount)
addSessionDebugLog({ addSessionDebugLog({
type: 'agent:patch', type: 'agent:patch',
@@ -376,6 +378,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
) )
// @ts-expect-error window type is not declared, debug only // @ts-expect-error window type is not declared, debug only
// eslint-disable-next-line react-hooks/immutability
if (__DEV__ && IS_WEB) window.agent = state.currentAgentState.agent if (__DEV__ && IS_WEB) window.agent = state.currentAgentState.agent
const agent = state.currentAgentState.agent as BskyAppAgent const agent = state.currentAgentState.agent as BskyAppAgent
@@ -448,7 +451,7 @@ export function useRequireAuth() {
) )
} }
export function useAgent(): BskyAgent { export function useAgent(): AtpAgent {
const agent = useContext(AgentContext) const agent = useContext(AgentContext)
if (!agent) { if (!agent) {
throw Error('useAgent() must be below <SessionProvider>.') throw Error('useAgent() must be below <SessionProvider>.')