From aa6aad652e8091ea6039af82f41d4de3669a5944 Mon Sep 17 00:00:00 2001 From: Samuel Newman Date: Thu, 31 Oct 2024 20:45:34 +0000 Subject: [Settings] Thread prefs revamp (#5772) * thread preferences screen * minor tweaks * more spacing * replace gate with IS_INTERNAL * [Settings] Following feed prefs revamp (#5773) * gated new settings screen * Following feed prefs * Update src/screens/Settings/FollowingFeedPreferences.tsx Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * Update src/screens/Settings/FollowingFeedPreferences.tsx Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * replace pref following feed gate * Update src/screens/Settings/FollowingFeedPreferences.tsx Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * use "Experimental" as the header --------- Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * [Settings] External media prefs revamp (#5774) * gated new settings screen * external media prefs revamp * replace gate ext media embeds * Update src/screens/Settings/ExternalMediaPreferences.tsx Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * add imports for translation * alternate list style on native --------- Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * [Settings] Languages revamp (partial) (#5775) * language settings (lazy restyle) * replace gate * fix text determining flex space * [Settings] App passwords revamp (#5777) * rework app passwords screen * Apply surfdude's copy changes Thanks @surfdude29! Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * format * replace gate * use admonition for input error and animate --------- Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * [Settings] Change handle dialog (#5781) * new change handle dialog * animations native only * overflow hidden on togglebutton animation * add a low-contrast border * extract out copybutton * finish change handle dialog * invalidate query on success * web fixes * error message for rate limit exceeded * typo * em dash! Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * another em dash Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * set maxwidth of suffixtext * Copy tweak Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> --------- Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> * [Settings] Notifs settings revamp (#5884) * rename, move, and restyle notif settings * bold "experimental:" --------- Co-authored-by: surfdude29 <149612116+surfdude29@users.noreply.github.com> --- .../Settings/components/AddAppPasswordDialog.tsx | 280 ++++++++++ .../Settings/components/ChangeHandleDialog.tsx | 602 +++++++++++++++++++++ src/screens/Settings/components/CopyButton.tsx | 69 +++ src/screens/Settings/components/SettingsList.tsx | 14 +- 4 files changed, 961 insertions(+), 4 deletions(-) create mode 100644 src/screens/Settings/components/AddAppPasswordDialog.tsx create mode 100644 src/screens/Settings/components/ChangeHandleDialog.tsx create mode 100644 src/screens/Settings/components/CopyButton.tsx (limited to 'src/screens/Settings/components') diff --git a/src/screens/Settings/components/AddAppPasswordDialog.tsx b/src/screens/Settings/components/AddAppPasswordDialog.tsx new file mode 100644 index 000000000..dcb212879 --- /dev/null +++ b/src/screens/Settings/components/AddAppPasswordDialog.tsx @@ -0,0 +1,280 @@ +import React, {useEffect, useMemo, useState} from 'react' +import {useWindowDimensions, View} from 'react-native' +import Animated, { + FadeIn, + FadeOut, + LayoutAnimationConfig, + LinearTransition, + SlideInRight, + SlideOutLeft, +} from 'react-native-reanimated' +import {ComAtprotoServerCreateAppPassword} from '@atproto/api' +import {msg, Trans} from '@lingui/macro' +import {useLingui} from '@lingui/react' +import {useMutation} from '@tanstack/react-query' + +import {isWeb} from '#/platform/detection' +import {useAppPasswordCreateMutation} from '#/state/queries/app-passwords' +import {atoms as a, native, useTheme} from '#/alf' +import {Admonition} from '#/components/Admonition' +import {Button, ButtonIcon, ButtonText} from '#/components/Button' +import * as Dialog from '#/components/Dialog' +import * as TextInput from '#/components/forms/TextField' +import * as Toggle from '#/components/forms/Toggle' +import {ChevronRight_Stroke2_Corner0_Rounded as ChevronRight} from '#/components/icons/Chevron' +import {SquareBehindSquare4_Stroke2_Corner0_Rounded as CopyIcon} from '#/components/icons/SquareBehindSquare4' +import {Text} from '#/components/Typography' +import {CopyButton} from './CopyButton' + +export function AddAppPasswordDialog({ + control, + passwords, +}: { + control: Dialog.DialogControlProps + passwords: string[] +}) { + const {height} = useWindowDimensions() + return ( + + + + + ) +} + +function CreateDialogInner({passwords}: {passwords: string[]}) { + const control = Dialog.useDialogContext() + const t = useTheme() + const {_} = useLingui() + const autogeneratedName = useRandomName() + const [name, setName] = useState('') + const [privileged, setPrivileged] = useState(false) + const { + mutateAsync: actuallyCreateAppPassword, + error: apiError, + data, + } = useAppPasswordCreateMutation() + + const regexFailError = useMemo( + () => + new DisplayableError( + _( + msg`App password names can only contain letters, numbers, spaces, dashes, and underscores`, + ), + ), + [_], + ) + + const { + mutate: createAppPassword, + error: validationError, + isPending, + } = useMutation< + ComAtprotoServerCreateAppPassword.AppPassword, + Error | DisplayableError + >({ + mutationFn: async () => { + const chosenName = name.trim() || autogeneratedName + if (chosenName.length < 4) { + throw new DisplayableError( + _(msg`App password names must be at least 4 characters long`), + ) + } + if (passwords.find(p => p === chosenName)) { + throw new DisplayableError(_(msg`App password name must be unique`)) + } + return await actuallyCreateAppPassword({name: chosenName, privileged}) + }, + }) + + const [hasBeenCopied, setHasBeenCopied] = useState(false) + useEffect(() => { + if (hasBeenCopied) { + const timeout = setTimeout(() => setHasBeenCopied(false), 100) + return () => clearTimeout(timeout) + } + }, [hasBeenCopied]) + + const error = + validationError || (!name.match(/^[a-zA-Z0-9-_ ]*$/) && regexFailError) + + return ( + + + + {!data ? ( + + + Add App Password + + + + Please enter a unique name for this app password or use our + randomly generated one. + + + + + createAppPassword()} + blurOnSubmit + autoCorrect={false} + autoComplete="off" + autoCapitalize="none" + autoFocus + /> + + + {error instanceof DisplayableError && ( + + {error.message} + + )} + + + + + Allow access to your direct messages + + + + {!!apiError || + (error && !(error instanceof DisplayableError) && ( + + + + Failed to create app password. Please try again. + + + + ))} + + + ) : ( + + + Here is your app password! + + + + Use this to sign into the other app along with your handle. + + + + {data.password} + + + + + For security reasons, you won't be able to view this again. If + you lose this app password, you'll need to generate a new one. + + + + + )} + + + + + ) +} + +class DisplayableError extends Error { + constructor(message: string) { + super(message) + this.name = 'DisplayableError' + } +} + +function useRandomName() { + return useState( + () => shadesOfBlue[Math.floor(Math.random() * shadesOfBlue.length)], + )[0] +} + +const shadesOfBlue: string[] = [ + 'AliceBlue', + 'Aqua', + 'Aquamarine', + 'Azure', + 'BabyBlue', + 'Blue', + 'BlueViolet', + 'CadetBlue', + 'CornflowerBlue', + 'Cyan', + 'DarkBlue', + 'DarkCyan', + 'DarkSlateBlue', + 'DeepSkyBlue', + 'DodgerBlue', + 'ElectricBlue', + 'LightBlue', + 'LightCyan', + 'LightSkyBlue', + 'LightSteelBlue', + 'MediumAquaMarine', + 'MediumBlue', + 'MediumSlateBlue', + 'MidnightBlue', + 'Navy', + 'PowderBlue', + 'RoyalBlue', + 'SkyBlue', + 'SlateBlue', + 'SteelBlue', + 'Teal', + 'Turquoise', +] diff --git a/src/screens/Settings/components/ChangeHandleDialog.tsx b/src/screens/Settings/components/ChangeHandleDialog.tsx new file mode 100644 index 000000000..e76d6257f --- /dev/null +++ b/src/screens/Settings/components/ChangeHandleDialog.tsx @@ -0,0 +1,602 @@ +import React, {useCallback, useMemo, useState} from 'react' +import {useWindowDimensions, View} from 'react-native' +import Animated, { + FadeIn, + FadeOut, + LayoutAnimationConfig, + LinearTransition, + SlideInLeft, + SlideInRight, + SlideOutLeft, + SlideOutRight, +} from 'react-native-reanimated' +import {ComAtprotoServerDescribeServer} from '@atproto/api' +import {msg, Trans} from '@lingui/macro' +import {useLingui} from '@lingui/react' +import {useMutation, useQueryClient} from '@tanstack/react-query' + +import {HITSLOP_10} from '#/lib/constants' +import {cleanError} from '#/lib/strings/errors' +import {createFullHandle, validateHandle} from '#/lib/strings/handles' +import {useFetchDid, useUpdateHandleMutation} from '#/state/queries/handle' +import {RQKEY as RQKEY_PROFILE} from '#/state/queries/profile' +import {useServiceQuery} from '#/state/queries/service' +import {useAgent, useSession} from '#/state/session' +import {ErrorScreen} from '#/view/com/util/error/ErrorScreen' +import {atoms as a, native, useBreakpoints, useTheme} from '#/alf' +import {Admonition} from '#/components/Admonition' +import {Button, ButtonIcon, ButtonText} from '#/components/Button' +import * as Dialog from '#/components/Dialog' +import * as TextField from '#/components/forms/TextField' +import * as ToggleButton from '#/components/forms/ToggleButton' +import {ArrowRight_Stroke2_Corner0_Rounded as ArrowRightIcon} from '#/components/icons/Arrow' +import {At_Stroke2_Corner0_Rounded as AtIcon} from '#/components/icons/At' +import {CheckThick_Stroke2_Corner0_Rounded as CheckIcon} from '#/components/icons/Check' +import {SquareBehindSquare4_Stroke2_Corner0_Rounded as CopyIcon} from '#/components/icons/SquareBehindSquare4' +import {InlineLinkText} from '#/components/Link' +import {Loader} from '#/components/Loader' +import {Text} from '#/components/Typography' +import {CopyButton} from './CopyButton' + +export function ChangeHandleDialog({ + control, +}: { + control: Dialog.DialogControlProps +}) { + const {height} = useWindowDimensions() + + return ( + + + + ) +} + +function ChangeHandleDialogInner() { + const control = Dialog.useDialogContext() + const {_} = useLingui() + const agent = useAgent() + const { + data: serviceInfo, + error: serviceInfoError, + refetch, + } = useServiceQuery(agent.serviceUrl.toString()) + + const [page, setPage] = useState<'provided-handle' | 'own-handle'>( + 'provided-handle', + ) + + const cancelButton = useCallback( + () => ( + + ), + [control, _], + ) + + return ( + + + Change Handle + + + } + contentContainerStyle={[a.pt_0, a.px_0]}> + + {serviceInfoError ? ( + + ) : serviceInfo ? ( + + {page === 'provided-handle' ? ( + + setPage('own-handle')} + /> + + ) : ( + + setPage('provided-handle')} + /> + + )} + + ) : ( + + + + )} + + + ) +} + +function ProvidedHandlePage({ + serviceInfo, + goToOwnHandle, +}: { + serviceInfo: ComAtprotoServerDescribeServer.OutputSchema + goToOwnHandle: () => void +}) { + const {_} = useLingui() + const [subdomain, setSubdomain] = useState('') + const agent = useAgent() + const control = Dialog.useDialogContext() + const {currentAccount} = useSession() + const queryClient = useQueryClient() + + const { + mutate: changeHandle, + isPending, + error, + isSuccess, + } = useUpdateHandleMutation({ + onSuccess: () => { + if (currentAccount) { + queryClient.invalidateQueries({ + queryKey: RQKEY_PROFILE(currentAccount.did), + }) + } + agent.resumeSession(agent.session!).then(() => control.close()) + }, + }) + + const host = serviceInfo.availableUserDomains[0] + + const validation = useMemo( + () => validateHandle(subdomain, host), + [subdomain, host], + ) + + const isTooLong = subdomain.length > 18 + const isInvalid = + isTooLong || + !validation.handleChars || + !validation.hyphenStartOrEnd || + !validation.totalLength + + return ( + + + {isSuccess && ( + + + + )} + {error && ( + + + + )} + + + + New handle + + + + setSubdomain(text)} + label={_(msg`New handle`)} + placeholder={_(msg`e.g. alice`)} + autoCapitalize="none" + autoCorrect={false} + /> + + {host} + + + + + + Your full handle will be{' '} + + @{createFullHandle(subdomain, host)} + + + + + + + If you have your own domain, you can use that as your handle. This + lets you self-verify your identity –{' '} + + learn more + + . + + + + + + + ) +} + +function OwnHandlePage({goToServiceHandle}: {goToServiceHandle: () => void}) { + const {_} = useLingui() + const t = useTheme() + const {currentAccount} = useSession() + const [dnsPanel, setDNSPanel] = useState(true) + const [domain, setDomain] = useState('') + const agent = useAgent() + const control = Dialog.useDialogContext() + const fetchDid = useFetchDid() + const queryClient = useQueryClient() + + const { + mutate: changeHandle, + isPending, + error, + isSuccess, + } = useUpdateHandleMutation({ + onSuccess: () => { + if (currentAccount) { + queryClient.invalidateQueries({ + queryKey: RQKEY_PROFILE(currentAccount.did), + }) + } + agent.resumeSession(agent.session!).then(() => control.close()) + }, + }) + + const { + mutate: verify, + isPending: isVerifyPending, + isSuccess: isVerified, + error: verifyError, + reset: resetVerification, + } = useMutation({ + mutationKey: ['verify-handle', domain], + mutationFn: async () => { + const did = await fetchDid(domain) + if (did !== currentAccount?.did) { + throw new DidMismatchError(did) + } + return true + }, + }) + + return ( + + {isSuccess && ( + + + + )} + {error && ( + + + + )} + {verifyError && ( + + + {verifyError instanceof DidMismatchError ? ( + + Wrong DID returned from server. Received: {verifyError.did} + + ) : ( + Failed to verify handle. Please try again. + )} + + + )} + + + + Enter the domain you want to use + + + + { + setDomain(text) + resetVerification() + }} + autoCapitalize="none" + autoCorrect={false} + /> + + + setDNSPanel(values[0] === 'dns')}> + + + DNS Panel + + + + + No DNS Panel + + + + {dnsPanel ? ( + <> + + Add the following DNS record to your domain: + + + + Host: + + + + _atproto + + + + + Type: + + + TXT + + + Value: + + + + + did={currentAccount?.did} + + + + + + + This should create a domain record at: + + + _atproto.{domain} + + + ) : ( + <> + + Upload a text file to: + + + + https://{domain}/.well-known/atproto-did + + + + That contains the following: + + + {currentAccount?.did} + + + + )} + + {isVerified && ( + + + + )} + + + + + + + + ) +} + +class DidMismatchError extends Error { + did: string + constructor(did: string) { + super('DID mismatch') + this.name = 'DidMismatchError' + this.did = did + } +} + +function ChangeHandleError({error}: {error: unknown}) { + const {_} = useLingui() + + let message = _(msg`Failed to change handle. Please try again.`) + + if (error instanceof Error) { + if (error.message.startsWith('Handle already taken')) { + message = _(msg`Handle already taken. Please try a different one.`) + } else if (error.message === 'Reserved handle') { + message = _(msg`This handle is reserved. Please try a different one.`) + } else if (error.message === 'Handle too long') { + message = _(msg`Handle too long. Please try a shorter one.`) + } else if (error.message === 'Input/handle must be a valid handle') { + message = _(msg`Invalid handle. Please try a different one.`) + } else if (error.message === 'Rate Limit Exceeded') { + message = _( + msg`Rate limit exceeded – you've tried to change your handle too many times in a short period. Please wait a minute before trying again.`, + ) + } + } + + return {message} +} + +function SuccessMessage({text}: {text: string}) { + const {gtMobile} = useBreakpoints() + const t = useTheme() + return ( + + + + + {text} + + ) +} diff --git a/src/screens/Settings/components/CopyButton.tsx b/src/screens/Settings/components/CopyButton.tsx new file mode 100644 index 000000000..eb538f5de --- /dev/null +++ b/src/screens/Settings/components/CopyButton.tsx @@ -0,0 +1,69 @@ +import React, {useCallback, useEffect, useState} from 'react' +import {GestureResponderEvent, View} from 'react-native' +import Animated, {FadeOutUp, ZoomIn} from 'react-native-reanimated' +import * as Clipboard from 'expo-clipboard' +import {Trans} from '@lingui/macro' + +import {atoms as a, useTheme} from '#/alf' +import {Button, ButtonProps} from '#/components/Button' +import {Text} from '#/components/Typography' + +export function CopyButton({ + style, + value, + onPress: onPressProp, + ...props +}: ButtonProps & {value: string}) { + const [hasBeenCopied, setHasBeenCopied] = useState(false) + const t = useTheme() + + useEffect(() => { + if (hasBeenCopied) { + const timeout = setTimeout(() => setHasBeenCopied(false), 100) + return () => clearTimeout(timeout) + } + }, [hasBeenCopied]) + + const onPress = useCallback( + (evt: GestureResponderEvent) => { + Clipboard.setStringAsync(value) + setHasBeenCopied(true) + onPressProp?.(evt) + }, + [value, onPressProp], + ) + + return ( + + {hasBeenCopied && ( + + + Copied! + + + )} +