Merge branch 'main' into internationalization

This commit is contained in:
Ansh Nanda
2023-11-08 14:12:36 -08:00
108 changed files with 1448 additions and 1337 deletions
+13 -1
View File
@@ -22,6 +22,10 @@ import * as Toast from 'view/com/util/Toast'
import {queryClient} from 'lib/react-query'
import {TestCtrls} from 'view/com/testing/TestCtrls'
import {Provider as ShellStateProvider} from 'state/shell'
import {Provider as ModalStateProvider} from 'state/modals'
import {Provider as MutedThreadsProvider} from 'state/muted-threads'
import {Provider as InvitesStateProvider} from 'state/invites'
import {Provider as PrefsStateProvider} from 'state/preferences'
SplashScreen.preventAutoHideAsync()
@@ -78,7 +82,15 @@ function App() {
return (
<ShellStateProvider>
<InnerApp />
<PrefsStateProvider>
<MutedThreadsProvider>
<InvitesStateProvider>
<ModalStateProvider>
<InnerApp />
</ModalStateProvider>
</InvitesStateProvider>
</MutedThreadsProvider>
</PrefsStateProvider>
</ShellStateProvider>
)
}
+13 -1
View File
@@ -20,6 +20,10 @@ import {i18n} from '@lingui/core'
import {I18nProvider} from '@lingui/react'
import {defaultLocale, dynamicActivate} from './locale/i18n'
import {Provider as ShellStateProvider} from 'state/shell'
import {Provider as ModalStateProvider} from 'state/modals'
import {Provider as MutedThreadsProvider} from 'state/muted-threads'
import {Provider as InvitesStateProvider} from 'state/invites'
import {Provider as PrefsStateProvider} from 'state/preferences'
const InnerApp = observer(function AppImpl() {
const colorMode = useColorMode()
@@ -74,7 +78,15 @@ function App() {
return (
<ShellStateProvider>
<InnerApp />
<PrefsStateProvider>
<MutedThreadsProvider>
<InvitesStateProvider>
<ModalStateProvider>
<InnerApp />
</ModalStateProvider>
</InvitesStateProvider>
</MutedThreadsProvider>
</PrefsStateProvider>
</ShellStateProvider>
)
}
+4 -1
View File
@@ -7,6 +7,7 @@ import {AccountData} from 'state/models/session'
import {reset as resetNavigation} from '../../Navigation'
import * as Toast from 'view/com/util/Toast'
import {useSetDrawerOpen} from '#/state/shell/drawer-open'
import {useModalControls} from '#/state/modals'
export function useAccountSwitcher(): [
boolean,
@@ -16,6 +17,7 @@ export function useAccountSwitcher(): [
const {track} = useAnalytics()
const store = useStores()
const setDrawerOpen = useSetDrawerOpen()
const {closeModal} = useModalControls()
const [isSwitching, setIsSwitching] = useState(false)
const navigation = useNavigation<NavigationProp>()
@@ -25,6 +27,7 @@ export function useAccountSwitcher(): [
setIsSwitching(true)
const success = await store.session.resumeSession(acct)
setDrawerOpen(false)
closeModal()
store.shell.closeAllActiveElements()
if (success) {
resetNavigation()
@@ -36,7 +39,7 @@ export function useAccountSwitcher(): [
store.session.clear()
}
},
[track, setIsSwitching, navigation, store, setDrawerOpen],
[track, setIsSwitching, navigation, store, setDrawerOpen, closeModal],
)
return [isSwitching, setIsSwitching, onPressSwitchAccount]
+4 -4
View File
@@ -1,15 +1,15 @@
import * as Updates from 'expo-updates'
import {useCallback, useEffect} from 'react'
import {AppState} from 'react-native'
import {useStores} from 'state/index'
import {logger} from '#/logger'
import {useModalControls} from '#/state/modals'
export function useOTAUpdate() {
const store = useStores()
const {openModal} = useModalControls()
// HELPER FUNCTIONS
const showUpdatePopup = useCallback(() => {
store.shell.openModal({
openModal({
name: 'confirm',
title: 'Update Available',
message:
@@ -20,7 +20,7 @@ export function useOTAUpdate() {
})
},
})
}, [store.shell])
}, [openModal])
const checkForUpdate = useCallback(async () => {
logger.debug('useOTAUpdate: Checking for update...')
try {
-12
View File
@@ -1,12 +0,0 @@
import {RootStoreModel} from 'state/index'
import {ImageModel} from 'state/models/media/image'
export async function openAltTextModal(
store: RootStoreModel,
image: ImageModel,
) {
store.shell.openModal({
name: 'alt-text-image',
image,
})
}
+3 -2
View File
@@ -4,6 +4,7 @@ import {CameraOpts, CropperOptions} from './types'
import {RootStoreModel} from 'state/index'
import {Image as RNImage} from 'react-native-image-crop-picker'
export {openPicker} from './picker.shared'
import {unstable__openModal} from '#/state/modals'
export async function openCamera(
_store: RootStoreModel,
@@ -14,12 +15,12 @@ export async function openCamera(
}
export async function openCropper(
store: RootStoreModel,
_store: RootStoreModel,
opts: CropperOptions,
): Promise<RNImage> {
// TODO handle more opts
return new Promise((resolve, reject) => {
store.shell.openModal({
unstable__openModal({
name: 'crop-image',
uri: opts.path,
onSelect: (img?: RNImage) => {
+56
View File
@@ -0,0 +1,56 @@
import React from 'react'
import * as persisted from '#/state/persisted'
type StateContext = persisted.Schema['invites']
type ApiContext = {
setInviteCopied: (code: string) => void
}
const stateContext = React.createContext<StateContext>(
persisted.defaults.invites,
)
const apiContext = React.createContext<ApiContext>({
setInviteCopied(_: string) {},
})
export function Provider({children}: React.PropsWithChildren<{}>) {
const [state, setState] = React.useState(persisted.get('invites'))
const api = React.useMemo(
() => ({
setInviteCopied(code: string) {
setState(state => {
state = {
...state,
copiedInvites: state.copiedInvites.includes(code)
? state.copiedInvites
: state.copiedInvites.concat([code]),
}
persisted.write('invites', state)
return state
})
},
}),
[setState],
)
React.useEffect(() => {
return persisted.onUpdate(() => {
setState(persisted.get('invites'))
})
}, [setState])
return (
<stateContext.Provider value={state}>
<apiContext.Provider value={api}>{children}</apiContext.Provider>
</stateContext.Provider>
)
}
export function useInvitesState() {
return React.useContext(stateContext)
}
export function useInvitesAPI() {
return React.useContext(apiContext)
}
+284
View File
@@ -0,0 +1,284 @@
import React from 'react'
import {AppBskyActorDefs, ModerationUI} from '@atproto/api'
import {StyleProp, ViewStyle, DeviceEventEmitter} from 'react-native'
import {Image as RNImage} from 'react-native-image-crop-picker'
import {ProfileModel} from '#/state/models/content/profile'
import {ImageModel} from '#/state/models/media/image'
import {ListModel} from '#/state/models/content/list'
import {GalleryModel} from '#/state/models/media/gallery'
export interface ConfirmModal {
name: 'confirm'
title: string
message: string | (() => JSX.Element)
onPressConfirm: () => void | Promise<void>
onPressCancel?: () => void | Promise<void>
confirmBtnText?: string
confirmBtnStyle?: StyleProp<ViewStyle>
cancelBtnText?: string
}
export interface EditProfileModal {
name: 'edit-profile'
profileView: ProfileModel
onUpdate?: () => void
}
export interface ProfilePreviewModal {
name: 'profile-preview'
did: string
}
export interface ServerInputModal {
name: 'server-input'
initialService: string
onSelect: (url: string) => void
}
export interface ModerationDetailsModal {
name: 'moderation-details'
context: 'account' | 'content'
moderation: ModerationUI
}
export type ReportModal = {
name: 'report'
} & (
| {
uri: string
cid: string
}
| {did: string}
)
export interface CreateOrEditListModal {
name: 'create-or-edit-list'
purpose?: string
list?: ListModel
onSave?: (uri: string) => void
}
export interface UserAddRemoveListsModal {
name: 'user-add-remove-lists'
subject: string
displayName: string
onAdd?: (listUri: string) => void
onRemove?: (listUri: string) => void
}
export interface ListAddUserModal {
name: 'list-add-user'
list: ListModel
onAdd?: (profile: AppBskyActorDefs.ProfileViewBasic) => void
}
export interface EditImageModal {
name: 'edit-image'
image: ImageModel
gallery: GalleryModel
}
export interface CropImageModal {
name: 'crop-image'
uri: string
onSelect: (img?: RNImage) => void
}
export interface AltTextImageModal {
name: 'alt-text-image'
image: ImageModel
}
export interface DeleteAccountModal {
name: 'delete-account'
}
export interface RepostModal {
name: 'repost'
onRepost: () => void
onQuote: () => void
isReposted: boolean
}
export interface SelfLabelModal {
name: 'self-label'
labels: string[]
hasMedia: boolean
onChange: (labels: string[]) => void
}
export interface ChangeHandleModal {
name: 'change-handle'
onChanged: () => void
}
export interface WaitlistModal {
name: 'waitlist'
}
export interface InviteCodesModal {
name: 'invite-codes'
}
export interface AddAppPasswordModal {
name: 'add-app-password'
}
export interface ContentFilteringSettingsModal {
name: 'content-filtering-settings'
}
export interface ContentLanguagesSettingsModal {
name: 'content-languages-settings'
}
export interface PostLanguagesSettingsModal {
name: 'post-languages-settings'
}
export interface BirthDateSettingsModal {
name: 'birth-date-settings'
}
export interface VerifyEmailModal {
name: 'verify-email'
showReminder?: boolean
}
export interface ChangeEmailModal {
name: 'change-email'
}
export interface SwitchAccountModal {
name: 'switch-account'
}
export interface LinkWarningModal {
name: 'link-warning'
text: string
href: string
}
export type Modal =
// Account
| AddAppPasswordModal
| ChangeHandleModal
| DeleteAccountModal
| EditProfileModal
| ProfilePreviewModal
| BirthDateSettingsModal
| VerifyEmailModal
| ChangeEmailModal
| SwitchAccountModal
// Curation
| ContentFilteringSettingsModal
| ContentLanguagesSettingsModal
| PostLanguagesSettingsModal
// Moderation
| ModerationDetailsModal
| ReportModal
// Lists
| CreateOrEditListModal
| UserAddRemoveListsModal
| ListAddUserModal
// Posts
| AltTextImageModal
| CropImageModal
| EditImageModal
| ServerInputModal
| RepostModal
| SelfLabelModal
// Bluesky access
| WaitlistModal
| InviteCodesModal
// Generic
| ConfirmModal
| LinkWarningModal
const ModalContext = React.createContext<{
isModalActive: boolean
activeModals: Modal[]
}>({
isModalActive: false,
activeModals: [],
})
const ModalControlContext = React.createContext<{
openModal: (modal: Modal) => void
closeModal: () => void
}>({
openModal: () => {},
closeModal: () => {},
})
/**
* @deprecated DO NOT USE THIS unless you have no other choice.
*/
export let unstable__openModal: (modal: Modal) => void = () => {
throw new Error(`ModalContext is not initialized`)
}
export function Provider({children}: React.PropsWithChildren<{}>) {
const [isModalActive, setIsModalActive] = React.useState(false)
const [activeModals, setActiveModals] = React.useState<Modal[]>([])
const openModal = React.useCallback(
(modal: Modal) => {
DeviceEventEmitter.emit('navigation')
setActiveModals(activeModals => [...activeModals, modal])
setIsModalActive(true)
},
[setIsModalActive, setActiveModals],
)
unstable__openModal = openModal
const closeModal = React.useCallback(() => {
let totalActiveModals = 0
setActiveModals(activeModals => {
activeModals.pop()
totalActiveModals = activeModals.length
return activeModals
})
setIsModalActive(totalActiveModals > 0)
}, [setIsModalActive, setActiveModals])
const state = React.useMemo(
() => ({
isModalActive,
activeModals,
}),
[isModalActive, activeModals],
)
const methods = React.useMemo(
() => ({
openModal,
closeModal,
}),
[openModal, closeModal],
)
return (
<ModalContext.Provider value={state}>
<ModalControlContext.Provider value={methods}>
{children}
</ModalControlContext.Provider>
</ModalContext.Provider>
)
}
export function useModals() {
return React.useContext(ModalContext)
}
export function useModalControls() {
return React.useContext(ModalControlContext)
}
@@ -63,10 +63,6 @@ export class PostThreadItemModel {
return this.post.uri
}
get isThreadMuted() {
return this.data.isThreadMuted
}
get moderation(): PostModeration {
return this.data.moderation
}
@@ -129,10 +125,6 @@ export class PostThreadItemModel {
this.data.toggleRepost()
}
async toggleThreadMute() {
this.data.toggleThreadMute()
}
async delete() {
this.data.delete()
}
-12
View File
@@ -74,10 +74,6 @@ export class PostThreadModel {
return this.resolvedUri
}
get isThreadMuted() {
return this.rootStore.mutedThreads.uris.has(this.rootUri)
}
get isCachedPostAReply() {
if (AppBskyFeedPost.isRecord(this.thread?.post.record)) {
return !!this.thread?.post.record.reply
@@ -140,14 +136,6 @@ export class PostThreadModel {
this.refresh()
}
async toggleThreadMute() {
if (this.isThreadMuted) {
this.rootStore.mutedThreads.uris.delete(this.rootUri)
} else {
this.rootStore.mutedThreads.uris.add(this.rootUri)
}
}
// state transitions
// =
-106
View File
@@ -1,106 +0,0 @@
import {makeAutoObservable} from 'mobx'
import {RootStoreModel} from '../root-store'
import {hasProp} from 'lib/type-guards'
import {track} from 'lib/analytics/analytics'
import {SuggestedActorsModel} from './suggested-actors'
export const OnboardingScreenSteps = {
Welcome: 'Welcome',
RecommendedFeeds: 'RecommendedFeeds',
RecommendedFollows: 'RecommendedFollows',
Home: 'Home',
} as const
type OnboardingStep =
(typeof OnboardingScreenSteps)[keyof typeof OnboardingScreenSteps]
const OnboardingStepsArray = Object.values(OnboardingScreenSteps)
export class OnboardingModel {
// state
step: OnboardingStep = 'Home' // default state to skip onboarding, only enabled for new users by calling start()
// data
suggestedActors: SuggestedActorsModel
constructor(public rootStore: RootStoreModel) {
this.suggestedActors = new SuggestedActorsModel(this.rootStore)
makeAutoObservable(this, {
rootStore: false,
hydrate: false,
serialize: false,
})
}
serialize(): unknown {
return {
step: this.step,
}
}
hydrate(v: unknown) {
if (typeof v === 'object' && v !== null) {
if (
hasProp(v, 'step') &&
typeof v.step === 'string' &&
OnboardingStepsArray.includes(v.step as OnboardingStep)
) {
this.step = v.step as OnboardingStep
}
} else {
// if there is no valid state, we'll just reset
this.reset()
}
}
/**
* Returns the name of the next screen in the onboarding process based on the current step or screen name provided.
* @param {OnboardingStep} [currentScreenName]
* @returns name of next screen in the onboarding process
*/
next(currentScreenName?: OnboardingStep) {
currentScreenName = currentScreenName || this.step
if (currentScreenName === 'Welcome') {
this.step = 'RecommendedFeeds'
return this.step
} else if (this.step === 'RecommendedFeeds') {
this.step = 'RecommendedFollows'
// prefetch recommended follows
this.suggestedActors.loadMore(true)
return this.step
} else if (this.step === 'RecommendedFollows') {
this.finish()
return this.step
} else {
// if we get here, we're in an invalid state, let's just go Home
return 'Home'
}
}
start() {
this.step = 'Welcome'
track('Onboarding:Begin')
}
finish() {
this.rootStore.me.mainFeed.refresh() // load the selected content
this.step = 'Home'
track('Onboarding:Complete')
}
reset() {
this.step = 'Welcome'
track('Onboarding:Reset')
}
skip() {
this.step = 'Home'
track('Onboarding:Skipped')
}
get isComplete() {
return this.step === 'Home'
}
get isActive() {
return !this.isComplete
}
}
+3 -3
View File
@@ -18,6 +18,7 @@ import {RootStoreModel} from '../root-store'
import {PostThreadModel} from '../content/post-thread'
import {cleanError} from 'lib/strings/errors'
import {logger} from '#/logger'
import {isThreadMuted} from '#/state/muted-threads'
const GROUPABLE_REASONS = ['like', 'repost', 'follow']
const PAGE_SIZE = 30
@@ -303,7 +304,7 @@ export class NotificationsFeedModel {
}
get unreadCountLabel(): string {
const count = this.unreadCount + this.rootStore.invitedUsers.numNotifs
const count = this.unreadCount
if (count >= MAX_VISIBLE_NOTIFS) {
return `${MAX_VISIBLE_NOTIFS}+`
}
@@ -550,8 +551,7 @@ export class NotificationsFeedModel {
.filter(item => {
const hideByLabel = item.shouldFilter
let mutedThread = !!(
item.reasonSubjectRootUri &&
this.rootStore.mutedThreads.uris.has(item.reasonSubjectRootUri)
item.reasonSubjectRootUri && isThreadMuted(item.reasonSubjectRootUri)
)
return !hideByLabel && !mutedThread
})
-18
View File
@@ -75,10 +75,6 @@ export class PostsFeedItemModel {
return this.post.uri
}
get isThreadMuted() {
return this.rootStore.mutedThreads.uris.has(this.rootUri)
}
get moderation(): PostModeration {
return moderatePost(this.post, this.rootStore.preferences.moderationOpts)
}
@@ -172,20 +168,6 @@ export class PostsFeedItemModel {
}
}
async toggleThreadMute() {
try {
if (this.isThreadMuted) {
this.rootStore.mutedThreads.uris.delete(this.rootUri)
track('Post:ThreadUnmute')
} else {
this.rootStore.mutedThreads.uris.add(this.rootUri)
track('Post:ThreadMute')
}
} catch (error) {
logger.error('Failed to toggle thread mute', {error})
}
}
async delete() {
try {
await this.rootStore.agent.deletePost(this.post.uri)
-88
View File
@@ -1,88 +0,0 @@
import {makeAutoObservable, runInAction} from 'mobx'
import {ComAtprotoServerDefs, AppBskyActorDefs} from '@atproto/api'
import {RootStoreModel} from './root-store'
import {isObj, hasProp, isStrArray} from 'lib/type-guards'
import {logger} from '#/logger'
export class InvitedUsers {
copiedInvites: string[] = []
seenDids: string[] = []
profiles: AppBskyActorDefs.ProfileViewDetailed[] = []
get numNotifs() {
return this.profiles.length
}
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(
this,
{rootStore: false, serialize: false, hydrate: false},
{autoBind: true},
)
}
serialize() {
return {seenDids: this.seenDids, copiedInvites: this.copiedInvites}
}
hydrate(v: unknown) {
if (isObj(v) && hasProp(v, 'seenDids') && isStrArray(v.seenDids)) {
this.seenDids = v.seenDids
}
if (
isObj(v) &&
hasProp(v, 'copiedInvites') &&
isStrArray(v.copiedInvites)
) {
this.copiedInvites = v.copiedInvites
}
}
async fetch(invites: ComAtprotoServerDefs.InviteCode[]) {
// pull the dids of invited users not marked seen
const dids = []
for (const invite of invites) {
for (const use of invite.uses) {
if (!this.seenDids.includes(use.usedBy)) {
dids.push(use.usedBy)
}
}
}
// fetch their profiles
this.profiles = []
if (dids.length) {
try {
const res = await this.rootStore.agent.app.bsky.actor.getProfiles({
actors: dids,
})
runInAction(() => {
// save the ones following -- these are the ones we want to notify the user about
this.profiles = res.data.profiles.filter(
profile => !profile.viewer?.following,
)
})
this.rootStore.me.follows.hydrateMany(this.profiles)
} catch (e) {
logger.error('Failed to fetch profiles for invited users', {
error: e,
})
}
}
}
isInviteCopied(invite: string) {
return this.copiedInvites.includes(invite)
}
setInviteCopied(invite: string) {
if (!this.isInviteCopied(invite)) {
this.copiedInvites.push(invite)
}
}
markSeen(did: string) {
this.seenDids.push(did)
this.profiles = this.profiles.filter(profile => profile.did !== did)
}
}
-1
View File
@@ -193,7 +193,6 @@ export class MeModel {
error: e,
})
}
await this.rootStore.invitedUsers.fetch(this.invites)
}
}
-13
View File
@@ -4,7 +4,6 @@ import {ImageModel} from './image'
import {Image as RNImage} from 'react-native-image-crop-picker'
import {openPicker} from 'lib/media/picker'
import {getImageDim} from 'lib/media/manip'
import {isNative} from 'platform/detection'
export class GalleryModel {
images: ImageModel[] = []
@@ -42,18 +41,6 @@ export class GalleryModel {
}
}
async edit(image: ImageModel) {
if (isNative) {
this.crop(image)
} else {
this.rootStore.shell.openModal({
name: 'edit-image',
image,
gallery: this,
})
}
}
async paste(uri: string) {
if (this.size >= 4) {
return
-29
View File
@@ -1,29 +0,0 @@
/**
* This is a temporary client-side system for storing muted threads
* When the system lands on prod we should switch to that
*/
import {makeAutoObservable} from 'mobx'
import {isObj, hasProp, isStrArray} from 'lib/type-guards'
export class MutedThreads {
uris: Set<string> = new Set()
constructor() {
makeAutoObservable(
this,
{serialize: false, hydrate: false},
{autoBind: true},
)
}
serialize() {
return {uris: Array.from(this.uris)}
}
hydrate(v: unknown) {
if (isObj(v) && hasProp(v, 'uris') && isStrArray(v.uris)) {
this.uris = new Set(v.uris)
}
}
}
-24
View File
@@ -15,12 +15,9 @@ import {ProfilesCache} from './cache/profiles-view'
import {PostsCache} from './cache/posts'
import {LinkMetasCache} from './cache/link-metas'
import {MeModel} from './me'
import {InvitedUsers} from './invited-users'
import {PreferencesModel} from './ui/preferences'
import {resetToTab} from '../../Navigation'
import {ImageSizesCache} from './cache/image-sizes'
import {MutedThreads} from './muted-threads'
import {Reminders} from './ui/reminders'
import {reset as resetNavigation} from '../../Navigation'
import {logger} from '#/logger'
@@ -28,7 +25,6 @@ import {logger} from '#/logger'
// remove after backend testing finishes
// -prf
import {applyDebugHeader} from 'lib/api/debug-appview-proxy-header'
import {OnboardingModel} from './discovery/onboarding'
export const appInfo = z.object({
build: z.string(),
@@ -45,15 +41,11 @@ export class RootStoreModel {
shell = new ShellUiModel(this)
preferences = new PreferencesModel(this)
me = new MeModel(this)
onboarding = new OnboardingModel(this)
invitedUsers = new InvitedUsers(this)
handleResolutions = new HandleResolutionsCache()
profiles = new ProfilesCache(this)
posts = new PostsCache(this)
linkMetas = new LinkMetasCache(this)
imageSizes = new ImageSizesCache()
mutedThreads = new MutedThreads()
reminders = new Reminders(this)
constructor(agent: BskyAgent) {
this.agent = agent
@@ -73,11 +65,7 @@ export class RootStoreModel {
appInfo: this.appInfo,
session: this.session.serialize(),
me: this.me.serialize(),
onboarding: this.onboarding.serialize(),
preferences: this.preferences.serialize(),
invitedUsers: this.invitedUsers.serialize(),
mutedThreads: this.mutedThreads.serialize(),
reminders: this.reminders.serialize(),
}
}
@@ -92,24 +80,12 @@ export class RootStoreModel {
if (hasProp(v, 'me')) {
this.me.hydrate(v.me)
}
if (hasProp(v, 'onboarding')) {
this.onboarding.hydrate(v.onboarding)
}
if (hasProp(v, 'session')) {
this.session.hydrate(v.session)
}
if (hasProp(v, 'preferences')) {
this.preferences.hydrate(v.preferences)
}
if (hasProp(v, 'invitedUsers')) {
this.invitedUsers.hydrate(v.invitedUsers)
}
if (hasProp(v, 'mutedThreads')) {
this.mutedThreads.hydrate(v.mutedThreads)
}
if (hasProp(v, 'reminders')) {
this.reminders.hydrate(v.reminders)
}
}
}
+4 -3
View File
@@ -9,6 +9,7 @@ import {cleanError} from 'lib/strings/errors'
import {getAge} from 'lib/strings/time'
import {track} from 'lib/analytics/analytics'
import {logger} from '#/logger'
import {DispatchContext as OnboardingDispatchContext} from '#/state/shell/onboarding'
const DEFAULT_DATE = new Date(Date.now() - 60e3 * 60 * 24 * 365 * 20) // default to 20 years ago
@@ -90,7 +91,7 @@ export class CreateAccountModel {
}
}
async submit() {
async submit(onboardingDispatch: OnboardingDispatchContext) {
if (!this.email) {
this.setStep(2)
return this.setError('Please enter your email.')
@@ -111,7 +112,7 @@ export class CreateAccountModel {
this.setIsProcessing(true)
try {
this.rootStore.onboarding.start() // start now to avoid flashing the wrong view
onboardingDispatch({type: 'start'}) // start now to avoid flashing the wrong view
await this.rootStore.session.createAccount({
service: this.serviceUrl,
email: this.email,
@@ -122,7 +123,7 @@ export class CreateAccountModel {
/* dont await */ this.rootStore.preferences.setBirthDate(this.birthDate)
track('Create Account')
} catch (e: any) {
this.rootStore.onboarding.skip() // undo starting the onboard
onboardingDispatch({type: 'skip'}) // undo starting the onboard
let errMsg = e.toString()
if (e instanceof ComAtprotoServerCreateAccount.InvalidInviteCodeError) {
errMsg =
+2 -147
View File
@@ -10,11 +10,10 @@ import {isObj, hasProp} from 'lib/type-guards'
import {RootStoreModel} from '../root-store'
import {ModerationOpts} from '@atproto/api'
import {DEFAULT_FEEDS} from 'lib/constants'
import {deviceLocales} from 'platform/detection'
import {getAge} from 'lib/strings/time'
import {FeedTuner} from 'lib/api/feed-manip'
import {LANGUAGES} from '../../../locale/languages'
import {logger} from '#/logger'
import {getContentLanguages} from '#/state/preferences/languages'
// TEMP we need to permanently convert 'show' to 'ignore', for now we manually convert -prf
export type LabelPreference = APILabelPreference | 'show'
@@ -34,9 +33,6 @@ const LABEL_GROUPS = [
'impersonation',
]
const VISIBILITY_VALUES = ['ignore', 'warn', 'hide']
const DEFAULT_LANG_CODES = (deviceLocales || [])
.concat(['en', 'ja', 'pt', 'de'])
.slice(0, 6)
const THREAD_SORT_VALUES = ['oldest', 'newest', 'most-likes', 'random']
interface LegacyPreferences {
@@ -62,10 +58,6 @@ export class LabelPreferencesModel {
export class PreferencesModel {
adultContentEnabled = false
primaryLanguage: string = deviceLocales[0] || 'en'
contentLanguages: string[] = deviceLocales || []
postLanguage: string = deviceLocales[0] || 'en'
postLanguageHistory: string[] = DEFAULT_LANG_CODES
contentLabels = new LabelPreferencesModel()
savedFeeds: string[] = []
pinnedFeeds: string[] = []
@@ -83,7 +75,6 @@ export class PreferencesModel {
prioritizeFollowedUsers: true,
lab_treeViewEnabled: false, // experimental
}
requireAltTextEnabled: boolean = false
// used to help with transitions from device-stored to server-stored preferences
legacyPreferences: LegacyPreferences | undefined
@@ -104,14 +95,9 @@ export class PreferencesModel {
serialize() {
return {
primaryLanguage: this.primaryLanguage,
contentLanguages: this.contentLanguages,
postLanguage: this.postLanguage,
postLanguageHistory: this.postLanguageHistory,
contentLabels: this.contentLabels,
savedFeeds: this.savedFeeds,
pinnedFeeds: this.pinnedFeeds,
requireAltTextEnabled: this.requireAltTextEnabled,
}
}
@@ -122,44 +108,6 @@ export class PreferencesModel {
*/
hydrate(v: unknown) {
if (isObj(v)) {
if (
hasProp(v, 'primaryLanguage') &&
typeof v.primaryLanguage === 'string'
) {
this.primaryLanguage = v.primaryLanguage
} else {
// default to the device languages
this.primaryLanguage = deviceLocales[0] || 'en'
}
// check if content languages in preferences exist, otherwise default to device languages
if (
hasProp(v, 'contentLanguages') &&
Array.isArray(v.contentLanguages) &&
typeof v.contentLanguages.every(item => typeof item === 'string')
) {
this.contentLanguages = v.contentLanguages
} else {
// default to the device languages
this.contentLanguages = deviceLocales
}
if (hasProp(v, 'postLanguage') && typeof v.postLanguage === 'string') {
this.postLanguage = v.postLanguage
} else {
// default to the device languages
this.postLanguage = deviceLocales[0] || 'en'
}
if (
hasProp(v, 'postLanguageHistory') &&
Array.isArray(v.postLanguageHistory) &&
typeof v.postLanguageHistory.every(item => typeof item === 'string')
) {
this.postLanguageHistory = v.postLanguageHistory
.concat(DEFAULT_LANG_CODES)
.slice(0, 6)
} else {
// default to a starter set
this.postLanguageHistory = DEFAULT_LANG_CODES
}
// check if content labels in preferences exist, then hydrate
if (hasProp(v, 'contentLabels') && typeof v.contentLabels === 'object') {
Object.assign(this.contentLabels, v.contentLabels)
@@ -180,13 +128,6 @@ export class PreferencesModel {
) {
this.pinnedFeeds = v.pinnedFeeds
}
// check if requiring alt text is enabled in preferences, then hydrate
if (
hasProp(v, 'requireAltTextEnabled') &&
typeof v.requireAltTextEnabled === 'boolean'
) {
this.requireAltTextEnabled = v.requireAltTextEnabled
}
// grab legacy values
this.legacyPreferences = getLegacyPreferences(v)
}
@@ -271,9 +212,6 @@ export class PreferencesModel {
try {
runInAction(() => {
this.contentLabels = new LabelPreferencesModel()
this.contentLanguages = deviceLocales
this.postLanguage = deviceLocales ? deviceLocales.join(',') : 'en'
this.postLanguageHistory = DEFAULT_LANG_CODES
this.savedFeeds = []
this.pinnedFeeds = []
})
@@ -285,81 +223,6 @@ export class PreferencesModel {
}
}
// languages
// =
hasContentLanguage(code2: string) {
return this.contentLanguages.includes(code2)
}
toggleContentLanguage(code2: string) {
if (this.hasContentLanguage(code2)) {
this.contentLanguages = this.contentLanguages.filter(
lang => lang !== code2,
)
} else {
this.contentLanguages = this.contentLanguages.concat([code2])
}
}
/**
* A getter that splits `this.postLanguage` into an array of strings.
*
* This was previously the main field on this model, but now we're
* concatenating lang codes to make multi-selection a little better.
*/
get postLanguages() {
// filter out empty strings if exist
return this.postLanguage.split(',').filter(Boolean)
}
hasPostLanguage(code2: string) {
return this.postLanguages.includes(code2)
}
togglePostLanguage(code2: string) {
if (this.hasPostLanguage(code2)) {
this.postLanguage = this.postLanguages
.filter(lang => lang !== code2)
.join(',')
} else {
// sort alphabetically for deterministic comparison in context menu
this.postLanguage = this.postLanguages
.concat([code2])
.sort((a, b) => a.localeCompare(b))
.join(',')
}
}
setPostLanguage(commaSeparatedLangCodes: string) {
this.postLanguage = commaSeparatedLangCodes
}
/**
* Saves whatever language codes are currently selected into a history array,
* which is then used to populate the language selector menu.
*/
savePostLanguageToHistory() {
// filter out duplicate `this.postLanguage` if exists, and prepend
// value to start of array
this.postLanguageHistory = [this.postLanguage]
.concat(
this.postLanguageHistory.filter(
commaSeparatedLangCodes =>
commaSeparatedLangCodes !== this.postLanguage,
),
)
.slice(0, 6)
}
getReadablePostLanguages() {
const all = this.postLanguages.map(code2 => {
const lang = LANGUAGES.find(l => l.code2 === code2)
return lang ? lang.name : code2
})
return all.join(', ')
}
// moderation
// =
@@ -608,21 +471,13 @@ export class PreferencesModel {
}
}
toggleRequireAltTextEnabled() {
this.requireAltTextEnabled = !this.requireAltTextEnabled
}
setPrimaryLanguage(lang: string) {
this.primaryLanguage = lang
}
getFeedTuners(
feedType: 'home' | 'following' | 'author' | 'custom' | 'list' | 'likes',
) {
if (feedType === 'custom') {
return [
FeedTuner.dedupReposts,
FeedTuner.preferredLangOnly(this.contentLanguages),
FeedTuner.preferredLangOnly(getContentLanguages()),
]
}
if (feedType === 'list') {
-24
View File
@@ -1,24 +0,0 @@
import {makeAutoObservable} from 'mobx'
import {RootStoreModel} from '../root-store'
export class Reminders {
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(
this,
{serialize: false, hydrate: false},
{autoBind: true},
)
}
serialize() {
return {}
}
hydrate(_v: unknown) {}
get shouldRequestEmailConfirmation() {
return false
}
setEmailConfirmationRequested() {}
}
-64
View File
@@ -1,64 +0,0 @@
import {makeAutoObservable} from 'mobx'
import {isObj, hasProp} from 'lib/type-guards'
import {RootStoreModel} from '../root-store'
import {toHashCode} from 'lib/strings/helpers'
export class Reminders {
lastEmailConfirm: Date | null = null
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(
this,
{serialize: false, hydrate: false},
{autoBind: true},
)
}
serialize() {
return {
lastEmailConfirm: this.lastEmailConfirm
? this.lastEmailConfirm.toISOString()
: undefined,
}
}
hydrate(v: unknown) {
if (
isObj(v) &&
hasProp(v, 'lastEmailConfirm') &&
typeof v.lastEmailConfirm === 'string'
) {
this.lastEmailConfirm = new Date(v.lastEmailConfirm)
}
}
get shouldRequestEmailConfirmation() {
const sess = this.rootStore.session.currentSession
if (!sess) {
return false
}
if (sess.emailConfirmed) {
return false
}
if (this.rootStore.onboarding.isActive) {
return false
}
// only prompt once
if (this.lastEmailConfirm) {
return false
}
const today = new Date()
// shard the users into 2 day of the week buckets
// (this is to avoid a sudden influx of email updates when
// this feature rolls out)
const code = toHashCode(sess.did) % 7
if (code !== today.getDay() && code !== (today.getDay() + 1) % 7) {
return false
}
return true
}
setEmailConfirmationRequested() {
this.lastEmailConfirm = new Date()
}
}
+9 -223
View File
@@ -1,12 +1,12 @@
import {AppBskyEmbedRecord, AppBskyActorDefs, ModerationUI} from '@atproto/api'
import {AppBskyEmbedRecord} from '@atproto/api'
import {RootStoreModel} from '../root-store'
import {makeAutoObservable, runInAction} from 'mobx'
import {ProfileModel} from '../content/profile'
import {Image as RNImage} from 'react-native-image-crop-picker'
import {ImageModel} from '../media/image'
import {ListModel} from '../content/list'
import {GalleryModel} from '../media/gallery'
import {StyleProp, ViewStyle} from 'react-native'
import {
shouldRequestEmailConfirmation,
setEmailConfirmationRequested,
} from '#/state/shell/reminders'
import {unstable__openModal} from '#/state/modals'
export type ColorMode = 'system' | 'light' | 'dark'
@@ -14,200 +14,6 @@ export function isColorMode(v: unknown): v is ColorMode {
return v === 'system' || v === 'light' || v === 'dark'
}
export interface ConfirmModal {
name: 'confirm'
title: string
message: string | (() => JSX.Element)
onPressConfirm: () => void | Promise<void>
onPressCancel?: () => void | Promise<void>
confirmBtnText?: string
confirmBtnStyle?: StyleProp<ViewStyle>
cancelBtnText?: string
}
export interface EditProfileModal {
name: 'edit-profile'
profileView: ProfileModel
onUpdate?: () => void
}
export interface ProfilePreviewModal {
name: 'profile-preview'
did: string
}
export interface ServerInputModal {
name: 'server-input'
initialService: string
onSelect: (url: string) => void
}
export interface ModerationDetailsModal {
name: 'moderation-details'
context: 'account' | 'content'
moderation: ModerationUI
}
export type ReportModal = {
name: 'report'
} & (
| {
uri: string
cid: string
}
| {did: string}
)
export interface CreateOrEditListModal {
name: 'create-or-edit-list'
purpose?: string
list?: ListModel
onSave?: (uri: string) => void
}
export interface UserAddRemoveListsModal {
name: 'user-add-remove-lists'
subject: string
displayName: string
onAdd?: (listUri: string) => void
onRemove?: (listUri: string) => void
}
export interface ListAddUserModal {
name: 'list-add-user'
list: ListModel
onAdd?: (profile: AppBskyActorDefs.ProfileViewBasic) => void
}
export interface EditImageModal {
name: 'edit-image'
image: ImageModel
gallery: GalleryModel
}
export interface CropImageModal {
name: 'crop-image'
uri: string
onSelect: (img?: RNImage) => void
}
export interface AltTextImageModal {
name: 'alt-text-image'
image: ImageModel
}
export interface DeleteAccountModal {
name: 'delete-account'
}
export interface RepostModal {
name: 'repost'
onRepost: () => void
onQuote: () => void
isReposted: boolean
}
export interface SelfLabelModal {
name: 'self-label'
labels: string[]
hasMedia: boolean
onChange: (labels: string[]) => void
}
export interface ChangeHandleModal {
name: 'change-handle'
onChanged: () => void
}
export interface WaitlistModal {
name: 'waitlist'
}
export interface InviteCodesModal {
name: 'invite-codes'
}
export interface AddAppPasswordModal {
name: 'add-app-password'
}
export interface ContentFilteringSettingsModal {
name: 'content-filtering-settings'
}
export interface ContentLanguagesSettingsModal {
name: 'content-languages-settings'
}
export interface PostLanguagesSettingsModal {
name: 'post-languages-settings'
}
export interface BirthDateSettingsModal {
name: 'birth-date-settings'
}
export interface VerifyEmailModal {
name: 'verify-email'
showReminder?: boolean
}
export interface ChangeEmailModal {
name: 'change-email'
}
export interface SwitchAccountModal {
name: 'switch-account'
}
export interface LinkWarningModal {
name: 'link-warning'
text: string
href: string
}
export type Modal =
// Account
| AddAppPasswordModal
| ChangeHandleModal
| DeleteAccountModal
| EditProfileModal
| ProfilePreviewModal
| BirthDateSettingsModal
| VerifyEmailModal
| ChangeEmailModal
| SwitchAccountModal
// Curation
| ContentFilteringSettingsModal
| ContentLanguagesSettingsModal
| PostLanguagesSettingsModal
// Moderation
| ModerationDetailsModal
| ReportModal
// Lists
| CreateOrEditListModal
| UserAddRemoveListsModal
| ListAddUserModal
// Posts
| AltTextImageModal
| CropImageModal
| EditImageModal
| ServerInputModal
| RepostModal
| SelfLabelModal
// Bluesky access
| WaitlistModal
| InviteCodesModal
// Generic
| ConfirmModal
| LinkWarningModal
interface LightboxModel {}
export class ProfileImageLightbox implements LightboxModel {
@@ -263,8 +69,6 @@ export interface ComposerOpts {
}
export class ShellUiModel {
isModalActive = false
activeModals: Modal[] = []
isLightboxActive = false
activeLightbox: ProfileImageLightbox | ImagesLightbox | null = null
isComposerActive = false
@@ -289,10 +93,6 @@ export class ShellUiModel {
this.closeLightbox()
return true
}
if (this.isModalActive) {
this.closeModal()
return true
}
if (this.isComposerActive) {
this.closeComposer()
return true
@@ -307,25 +107,11 @@ export class ShellUiModel {
if (this.isLightboxActive) {
this.closeLightbox()
}
while (this.isModalActive) {
this.closeModal()
}
if (this.isComposerActive) {
this.closeComposer()
}
}
openModal(modal: Modal) {
this.rootStore.emitNavigation()
this.isModalActive = true
this.activeModals.push(modal)
}
closeModal() {
this.activeModals.pop()
this.isModalActive = this.activeModals.length > 0
}
openLightbox(lightbox: ProfileImageLightbox | ImagesLightbox) {
this.rootStore.emitNavigation()
this.isLightboxActive = true
@@ -358,9 +144,9 @@ export class ShellUiModel {
setupLoginModals() {
this.rootStore.onSessionReady(() => {
if (this.rootStore.reminders.shouldRequestEmailConfirmation) {
this.openModal({name: 'verify-email', showReminder: true})
this.rootStore.reminders.setEmailConfirmationRequested()
if (shouldRequestEmailConfirmation(this.rootStore.session)) {
unstable__openModal({name: 'verify-email', showReminder: true})
setEmailConfirmationRequested()
}
})
}
+59
View File
@@ -0,0 +1,59 @@
import React from 'react'
import * as persisted from '#/state/persisted'
type StateContext = persisted.Schema['mutedThreads']
type ToggleContext = (uri: string) => boolean
const stateContext = React.createContext<StateContext>(
persisted.defaults.mutedThreads,
)
const toggleContext = React.createContext<ToggleContext>((_: string) => false)
export function Provider({children}: React.PropsWithChildren<{}>) {
const [state, setState] = React.useState(persisted.get('mutedThreads'))
const toggleThreadMute = React.useCallback(
(uri: string) => {
let muted = false
setState((arr: string[]) => {
if (arr.includes(uri)) {
arr = arr.filter(v => v !== uri)
muted = false
} else {
arr = arr.concat([uri])
muted = true
}
persisted.write('mutedThreads', arr)
return arr
})
return muted
},
[setState],
)
React.useEffect(() => {
return persisted.onUpdate(() => {
setState(persisted.get('mutedThreads'))
})
}, [setState])
return (
<stateContext.Provider value={state}>
<toggleContext.Provider value={toggleThreadMute}>
{children}
</toggleContext.Provider>
</stateContext.Provider>
)
}
export function useMutedThreads() {
return React.useContext(stateContext)
}
export function useToggleThreadMute() {
return React.useContext(toggleContext)
}
export function isThreadMuted(uri: string) {
return persisted.get('mutedThreads').includes(uri)
}
+1 -1
View File
@@ -6,7 +6,7 @@ import * as store from '#/state/persisted/store'
import BroadcastChannel from '#/state/persisted/broadcast'
export type {Schema} from '#/state/persisted/schema'
export {defaults as schema} from '#/state/persisted/schema'
export {defaults} from '#/state/persisted/schema'
const broadcast = new BroadcastChannel('BSKY_BROADCAST_CHANNEL')
const UPDATE_EVENT = 'BSKY_UPDATE'
+4 -6
View File
@@ -76,9 +76,9 @@ export function transform(legacy: LegacySchema): Schema {
defaults.session.currentAccount,
},
reminders: {
lastEmailConfirmReminder:
lastEmailConfirm:
legacy.reminders.lastEmailConfirm ||
defaults.reminders.lastEmailConfirmReminder,
defaults.reminders.lastEmailConfirm,
},
languagePrefs: {
primaryLanguage:
@@ -97,11 +97,9 @@ export function transform(legacy: LegacySchema): Schema {
legacy.preferences.requireAltTextEnabled ||
defaults.requireAltTextEnabled,
mutedThreads: legacy.mutedThreads.uris || defaults.mutedThreads,
invitedUsers: {
seenDids: legacy.invitedUsers.seenDids || defaults.invitedUsers.seenDids,
invites: {
copiedInvites:
legacy.invitedUsers.copiedInvites ||
defaults.invitedUsers.copiedInvites,
legacy.invitedUsers.copiedInvites || defaults.invites.copiedInvites,
},
onboarding: {
step: legacy.onboarding.step || defaults.onboarding.step,
+7 -9
View File
@@ -7,9 +7,9 @@ const accountSchema = z.object({
did: z.string(),
refreshJwt: z.string().optional(),
accessJwt: z.string().optional(),
handle: z.string(),
displayName: z.string(),
aviUrl: z.string(),
handle: z.string().optional(),
displayName: z.string().optional(),
aviUrl: z.string().optional(),
})
export const schema = z.object({
@@ -19,7 +19,7 @@ export const schema = z.object({
currentAccount: accountSchema.optional(),
}),
reminders: z.object({
lastEmailConfirmReminder: z.string().optional(),
lastEmailConfirm: z.string().optional(),
}),
languagePrefs: z.object({
primaryLanguage: z.string(), // should move to server
@@ -29,8 +29,7 @@ export const schema = z.object({
}),
requireAltTextEnabled: z.boolean(), // should move to server
mutedThreads: z.array(z.string()), // should move to server
invitedUsers: z.object({
seenDids: z.array(z.string()),
invites: z.object({
copiedInvites: z.array(z.string()),
}),
onboarding: z.object({
@@ -46,7 +45,7 @@ export const defaults: Schema = {
currentAccount: undefined,
},
reminders: {
lastEmailConfirmReminder: undefined,
lastEmailConfirm: undefined,
},
languagePrefs: {
primaryLanguage: deviceLocales[0] || 'en',
@@ -58,8 +57,7 @@ export const defaults: Schema = {
},
requireAltTextEnabled: false,
mutedThreads: [],
invitedUsers: {
seenDids: [],
invites: {
copiedInvites: [],
},
onboarding: {
@@ -0,0 +1,48 @@
import React from 'react'
import * as persisted from '#/state/persisted'
type StateContext = persisted.Schema['requireAltTextEnabled']
type SetContext = (v: persisted.Schema['requireAltTextEnabled']) => void
const stateContext = React.createContext<StateContext>(
persisted.defaults.requireAltTextEnabled,
)
const setContext = React.createContext<SetContext>(
(_: persisted.Schema['requireAltTextEnabled']) => {},
)
export function Provider({children}: React.PropsWithChildren<{}>) {
const [state, setState] = React.useState(
persisted.get('requireAltTextEnabled'),
)
const setStateWrapped = React.useCallback(
(requireAltTextEnabled: persisted.Schema['requireAltTextEnabled']) => {
setState(requireAltTextEnabled)
persisted.write('requireAltTextEnabled', requireAltTextEnabled)
},
[setState],
)
React.useEffect(() => {
return persisted.onUpdate(() => {
setState(persisted.get('requireAltTextEnabled'))
})
}, [setStateWrapped])
return (
<stateContext.Provider value={state}>
<setContext.Provider value={setStateWrapped}>
{children}
</setContext.Provider>
</stateContext.Provider>
)
}
export function useRequireAltTextEnabled() {
return React.useContext(stateContext)
}
export function useSetRequireAltTextEnabled() {
return React.useContext(setContext)
}
+17
View File
@@ -0,0 +1,17 @@
import React from 'react'
import {Provider as LanguagesProvider} from './languages'
import {Provider as AltTextRequiredProvider} from '../preferences/alt-text-required'
export {useLanguagePrefs, useLanguagePrefsApi} from './languages'
export {
useRequireAltTextEnabled,
useSetRequireAltTextEnabled,
} from './alt-text-required'
export function Provider({children}: React.PropsWithChildren<{}>) {
return (
<LanguagesProvider>
<AltTextRequiredProvider>{children}</AltTextRequiredProvider>
</LanguagesProvider>
)
}
+137
View File
@@ -0,0 +1,137 @@
import React from 'react'
import * as persisted from '#/state/persisted'
type SetStateCb = (
s: persisted.Schema['languagePrefs'],
) => persisted.Schema['languagePrefs']
type StateContext = persisted.Schema['languagePrefs']
type ApiContext = {
setPrimaryLanguage: (code2: string) => void
setPostLanguage: (commaSeparatedLangCodes: string) => void
toggleContentLanguage: (code2: string) => void
togglePostLanguage: (code2: string) => void
savePostLanguageToHistory: () => void
}
const stateContext = React.createContext<StateContext>(
persisted.defaults.languagePrefs,
)
const apiContext = React.createContext<ApiContext>({
setPrimaryLanguage: (_: string) => {},
setPostLanguage: (_: string) => {},
toggleContentLanguage: (_: string) => {},
togglePostLanguage: (_: string) => {},
savePostLanguageToHistory: () => {},
})
export function Provider({children}: React.PropsWithChildren<{}>) {
const [state, setState] = React.useState(persisted.get('languagePrefs'))
const setStateWrapped = React.useCallback(
(fn: SetStateCb) => {
const s = fn(persisted.get('languagePrefs'))
setState(s)
persisted.write('languagePrefs', s)
},
[setState],
)
React.useEffect(() => {
return persisted.onUpdate(() => {
setState(persisted.get('languagePrefs'))
})
}, [setStateWrapped])
const api = React.useMemo(
() => ({
setPrimaryLanguage(code2: string) {
setStateWrapped(s => ({...s, primaryLanguage: code2}))
},
setPostLanguage(commaSeparatedLangCodes: string) {
setStateWrapped(s => ({...s, postLanguage: commaSeparatedLangCodes}))
},
toggleContentLanguage(code2: string) {
setStateWrapped(s => {
const exists = s.contentLanguages.includes(code2)
const next = exists
? s.contentLanguages.filter(lang => lang !== code2)
: s.contentLanguages.concat(code2)
return {
...s,
contentLanguages: next,
}
})
},
togglePostLanguage(code2: string) {
setStateWrapped(s => {
const exists = hasPostLanguage(state.postLanguage, code2)
let next = s.postLanguage
if (exists) {
next = toPostLanguages(s.postLanguage)
.filter(lang => lang !== code2)
.join(',')
} else {
// sort alphabetically for deterministic comparison in context menu
next = toPostLanguages(s.postLanguage)
.concat([code2])
.sort((a, b) => a.localeCompare(b))
.join(',')
}
return {
...s,
postLanguage: next,
}
})
},
/**
* Saves whatever language codes are currently selected into a history array,
* which is then used to populate the language selector menu.
*/
savePostLanguageToHistory() {
// filter out duplicate `this.postLanguage` if exists, and prepend
// value to start of array
setStateWrapped(s => ({
...s,
postLanguageHistory: [s.postLanguage]
.concat(
s.postLanguageHistory.filter(
commaSeparatedLangCodes =>
commaSeparatedLangCodes !== s.postLanguage,
),
)
.slice(0, 6),
}))
},
}),
[state, setStateWrapped],
)
return (
<stateContext.Provider value={state}>
<apiContext.Provider value={api}>{children}</apiContext.Provider>
</stateContext.Provider>
)
}
export function useLanguagePrefs() {
return React.useContext(stateContext)
}
export function useLanguagePrefsApi() {
return React.useContext(apiContext)
}
export function getContentLanguages() {
return persisted.get('languagePrefs').contentLanguages
}
export function toPostLanguages(postLanguage: string): string[] {
// filter out empty strings if exist
return postLanguage.split(',').filter(Boolean)
}
export function hasPostLanguage(postLanguage: string, code2: string): boolean {
return toPostLanguages(postLanguage).includes(code2)
}
+1 -1
View File
@@ -27,7 +27,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
setState(persisted.get('colorMode'))
updateDocument(persisted.get('colorMode'))
})
}, [setStateWrapped])
}, [setState])
return (
<stateContext.Provider value={state}>
+5 -1
View File
@@ -3,6 +3,7 @@ import {Provider as DrawerOpenProvider} from './drawer-open'
import {Provider as DrawerSwipableProvider} from './drawer-swipe-disabled'
import {Provider as MinimalModeProvider} from './minimal-mode'
import {Provider as ColorModeProvider} from './color-mode'
import {Provider as OnboardingProvider} from './onboarding'
export {useIsDrawerOpen, useSetDrawerOpen} from './drawer-open'
export {
@@ -11,13 +12,16 @@ export {
} from './drawer-swipe-disabled'
export {useMinimalShellMode, useSetMinimalShellMode} from './minimal-mode'
export {useColorMode, useSetColorMode} from './color-mode'
export {useOnboardingState, useOnboardingDispatch} from './onboarding'
export function Provider({children}: React.PropsWithChildren<{}>) {
return (
<DrawerOpenProvider>
<DrawerSwipableProvider>
<MinimalModeProvider>
<ColorModeProvider>{children}</ColorModeProvider>
<ColorModeProvider>
<OnboardingProvider>{children}</OnboardingProvider>
</ColorModeProvider>
</MinimalModeProvider>
</DrawerSwipableProvider>
</DrawerOpenProvider>
+119
View File
@@ -0,0 +1,119 @@
import React from 'react'
import * as persisted from '#/state/persisted'
import {track} from '#/lib/analytics/analytics'
export const OnboardingScreenSteps = {
Welcome: 'Welcome',
RecommendedFeeds: 'RecommendedFeeds',
RecommendedFollows: 'RecommendedFollows',
Home: 'Home',
} as const
type OnboardingStep =
(typeof OnboardingScreenSteps)[keyof typeof OnboardingScreenSteps]
const OnboardingStepsArray = Object.values(OnboardingScreenSteps)
type Action =
| {type: 'set'; step: OnboardingStep}
| {type: 'next'; currentStep?: OnboardingStep}
| {type: 'start'}
| {type: 'finish'}
| {type: 'skip'}
export type StateContext = persisted.Schema['onboarding'] & {
isComplete: boolean
isActive: boolean
}
export type DispatchContext = (action: Action) => void
const stateContext = React.createContext<StateContext>(
compute(persisted.defaults.onboarding),
)
const dispatchContext = React.createContext<DispatchContext>((_: Action) => {})
function reducer(state: StateContext, action: Action): StateContext {
switch (action.type) {
case 'set': {
if (OnboardingStepsArray.includes(action.step)) {
persisted.write('onboarding', {step: action.step})
return compute({...state, step: action.step})
}
return state
}
case 'next': {
const currentStep = action.currentStep || state.step
let nextStep = 'Home'
if (currentStep === 'Welcome') {
nextStep = 'RecommendedFeeds'
} else if (currentStep === 'RecommendedFeeds') {
nextStep = 'RecommendedFollows'
} else if (currentStep === 'RecommendedFollows') {
nextStep = 'Home'
}
persisted.write('onboarding', {step: nextStep})
return compute({...state, step: nextStep})
}
case 'start': {
track('Onboarding:Begin')
persisted.write('onboarding', {step: 'Welcome'})
return compute({...state, step: 'Welcome'})
}
case 'finish': {
track('Onboarding:Complete')
persisted.write('onboarding', {step: 'Home'})
return compute({...state, step: 'Home'})
}
case 'skip': {
track('Onboarding:Skipped')
persisted.write('onboarding', {step: 'Home'})
return compute({...state, step: 'Home'})
}
default: {
throw new Error('Invalid action')
}
}
}
export function Provider({children}: React.PropsWithChildren<{}>) {
const [state, dispatch] = React.useReducer(
reducer,
compute(persisted.get('onboarding')),
)
React.useEffect(() => {
return persisted.onUpdate(() => {
dispatch({
type: 'set',
step: persisted.get('onboarding').step as OnboardingStep,
})
})
}, [dispatch])
return (
<stateContext.Provider value={state}>
<dispatchContext.Provider value={dispatch}>
{children}
</dispatchContext.Provider>
</stateContext.Provider>
)
}
export function useOnboardingState() {
return React.useContext(stateContext)
}
export function useOnboardingDispatch() {
return React.useContext(dispatchContext)
}
export function isOnboardingActive() {
return compute(persisted.get('onboarding')).isActive
}
function compute(state: persisted.Schema['onboarding']): StateContext {
return {
...state,
isActive: state.step !== 'Home',
isComplete: state.step === 'Home',
}
}
+7
View File
@@ -0,0 +1,7 @@
import {SessionModel} from '../models/session'
export function shouldRequestEmailConfirmation(_session: SessionModel) {
return false
}
export function setEmailConfirmationRequested() {}
+37
View File
@@ -0,0 +1,37 @@
import * as persisted from '#/state/persisted'
import {SessionModel} from '../models/session'
import {toHashCode} from 'lib/strings/helpers'
import {isOnboardingActive} from './onboarding'
export function shouldRequestEmailConfirmation(session: SessionModel) {
const sess = session.currentSession
if (!sess) {
return false
}
if (sess.emailConfirmed) {
return false
}
if (isOnboardingActive()) {
return false
}
// only prompt once
if (persisted.get('reminders').lastEmailConfirm) {
return false
}
const today = new Date()
// shard the users into 2 day of the week buckets
// (this is to avoid a sudden influx of email updates when
// this feature rolls out)
const code = toHashCode(sess.did) % 7
if (code !== today.getDay() && code !== (today.getDay() + 1) % 7) {
return false
}
return true
}
export function setEmailConfirmationRequested() {
persisted.write('reminders', {
...persisted.get('reminders'),
lastEmailConfirm: new Date().toISOString(),
})
}
+8 -7
View File
@@ -4,34 +4,35 @@ import {observer} from 'mobx-react-lite'
import {ErrorBoundary} from 'view/com/util/ErrorBoundary'
import {s} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {useStores} from 'state/index'
import {Welcome} from './onboarding/Welcome'
import {RecommendedFeeds} from './onboarding/RecommendedFeeds'
import {RecommendedFollows} from './onboarding/RecommendedFollows'
import {useSetMinimalShellMode} from '#/state/shell/minimal-mode'
import {useOnboardingState, useOnboardingDispatch} from '#/state/shell'
export const Onboarding = observer(function OnboardingImpl() {
const pal = usePalette('default')
const store = useStores()
const setMinimalShellMode = useSetMinimalShellMode()
const onboardingState = useOnboardingState()
const onboardingDispatch = useOnboardingDispatch()
React.useEffect(() => {
setMinimalShellMode(true)
}, [setMinimalShellMode])
const next = () => store.onboarding.next()
const skip = () => store.onboarding.skip()
const next = () => onboardingDispatch({type: 'next'})
const skip = () => onboardingDispatch({type: 'skip'})
return (
<SafeAreaView testID="onboardingView" style={[s.hContentRegion, pal.view]}>
<ErrorBoundary>
{store.onboarding.step === 'Welcome' && (
{onboardingState.step === 'Welcome' && (
<Welcome skip={skip} next={next} />
)}
{store.onboarding.step === 'RecommendedFeeds' && (
{onboardingState.step === 'RecommendedFeeds' && (
<RecommendedFeeds next={next} />
)}
{store.onboarding.step === 'RecommendedFollows' && (
{onboardingState.step === 'RecommendedFollows' && (
<RecommendedFollows next={next} />
)}
</ErrorBoundary>
+4 -2
View File
@@ -17,6 +17,7 @@ import {CreateAccountModel} from 'state/models/ui/create-account'
import {usePalette} from 'lib/hooks/usePalette'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useOnboardingDispatch} from '#/state/shell'
import {Step1} from './Step1'
import {Step2} from './Step2'
@@ -32,6 +33,7 @@ export const CreateAccount = observer(function CreateAccountImpl({
const store = useStores()
const model = React.useMemo(() => new CreateAccountModel(store), [store])
const {_} = useLingui()
const onboardingDispatch = useOnboardingDispatch()
React.useEffect(() => {
screen('CreateAccount')
@@ -62,14 +64,14 @@ export const CreateAccount = observer(function CreateAccountImpl({
model.next()
} else {
try {
await model.submit()
await model.submit(onboardingDispatch)
} catch {
// dont need to handle here
} finally {
track('Try Create Account')
}
}
}, [model, track])
}, [model, track, onboardingDispatch])
return (
<LoggedOutLayout
+4 -4
View File
@@ -10,10 +10,10 @@ import {usePalette} from 'lib/hooks/usePalette'
import {TextInput} from '../util/TextInput'
import {Policies} from './Policies'
import {ErrorMessage} from 'view/com/util/error/ErrorMessage'
import {useStores} from 'state/index'
import {isWeb} from 'platform/detection'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
/** STEP 2: Your account
* @field Invite code or waitlist
@@ -30,12 +30,12 @@ export const Step2 = observer(function Step2Impl({
model: CreateAccountModel
}) {
const pal = usePalette('default')
const store = useStores()
const {_} = useLingui()
const {openModal} = useModalControls()
const onPressWaitlist = React.useCallback(() => {
store.shell.openModal({name: 'waitlist'})
}, [store])
openModal({name: 'waitlist'})
}, [openModal])
return (
<View>
+13 -10
View File
@@ -22,12 +22,12 @@ import {usePalette} from 'lib/hooks/usePalette'
import {useTheme} from 'lib/ThemeContext'
import {cleanError} from 'lib/strings/errors'
import {logger} from '#/logger'
import {msg} from '@lingui/macro'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {styles} from './styles'
import {useModalControls} from '#/state/modals'
export const ForgotPasswordForm = ({
store,
error,
serviceUrl,
serviceDescription,
@@ -51,13 +51,14 @@ export const ForgotPasswordForm = ({
const [email, setEmail] = useState<string>('')
const {screen} = useAnalytics()
const {_} = useLingui()
const {openModal} = useModalControls()
useEffect(() => {
screen('Signin:ForgotPassword')
}, [screen])
const onPressSelectService = () => {
store.shell.openModal({
openModal({
name: 'server-input',
initialService: serviceUrl,
onSelect: setServiceUrl,
@@ -94,11 +95,13 @@ export const ForgotPasswordForm = ({
<>
<View>
<Text type="title-lg" style={[pal.text, styles.screenTitle]}>
Reset password
<Trans>Reset password</Trans>
</Text>
<Text type="md" style={[pal.text, styles.instructions]}>
Enter the email you used to create your account. We'll send you a
"reset code" so you can set a new password.
<Trans>
Enter the email you used to create your account. We'll send you a
"reset code" so you can set a new password.
</Trans>
</Text>
<View
testID="forgotPasswordView"
@@ -160,7 +163,7 @@ export const ForgotPasswordForm = ({
<View style={[s.flexRow, s.alignCenter, s.pl20, s.pr20]}>
<TouchableOpacity onPress={onPressBack} accessibilityRole="button">
<Text type="xl" style={[pal.link, s.pl5]}>
Back
<Trans>Back</Trans>
</Text>
</TouchableOpacity>
<View style={s.flex1} />
@@ -168,7 +171,7 @@ export const ForgotPasswordForm = ({
<ActivityIndicator />
) : !email ? (
<Text type="xl-bold" style={[pal.link, s.pr5, styles.dimmed]}>
Next
<Trans>Next</Trans>
</Text>
) : (
<TouchableOpacity
@@ -178,13 +181,13 @@ export const ForgotPasswordForm = ({
accessibilityLabel={_(msg`Go to next`)}
accessibilityHint="Navigates to the next screen">
<Text type="xl-bold" style={[pal.link, s.pr5]}>
Next
<Trans>Next</Trans>
</Text>
</TouchableOpacity>
)}
{!serviceDescription || isProcessing ? (
<Text type="xl" style={[pal.textLight, s.pl10]}>
Processing...
<Trans>Processing...</Trans>
</Text>
) : undefined}
</View>
+3 -1
View File
@@ -25,6 +25,7 @@ import {logger} from '#/logger'
import {Trans, msg} from '@lingui/macro'
import {styles} from './styles'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const LoginForm = ({
store,
@@ -57,9 +58,10 @@ export const LoginForm = ({
const [password, setPassword] = useState<string>('')
const passwordInputRef = useRef<TextInput>(null)
const {_} = useLingui()
const {openModal} = useModalControls()
const onPressSelectService = () => {
store.shell.openModal({
openModal({
name: 'server-input',
initialService: serviceUrl,
onSelect: setServiceUrl,
@@ -11,6 +11,7 @@ import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {usePalette} from 'lib/hooks/usePalette'
import {useStores} from 'state/index'
import {RecommendedFollowsItem} from './RecommendedFollowsItem'
import {SuggestedActorsModel} from '#/state/models/discovery/suggested-actors'
type Props = {
next: () => void
@@ -21,16 +22,10 @@ export const RecommendedFollows = observer(function RecommendedFollowsImpl({
const store = useStores()
const pal = usePalette('default')
const {isTabletOrMobile} = useWebMediaQueries()
React.useEffect(() => {
// Load suggested actors if not already loaded
// prefetch should happen in the onboarding model
if (
!store.onboarding.suggestedActors.hasLoaded ||
store.onboarding.suggestedActors.isEmpty
) {
store.onboarding.suggestedActors.loadMore(true)
}
const suggestedActors = React.useMemo(() => {
const model = new SuggestedActorsModel(store)
model.refresh()
return model
}, [store])
const title = (
@@ -98,13 +93,19 @@ export const RecommendedFollows = observer(function RecommendedFollowsImpl({
horizontal
titleStyle={isTabletOrMobile ? undefined : {minWidth: 470}}
contentStyle={{paddingHorizontal: 0}}>
{store.onboarding.suggestedActors.isLoading ? (
{suggestedActors.isLoading ? (
<ActivityIndicator size="large" />
) : (
<FlatList
data={store.onboarding.suggestedActors.suggestions}
data={suggestedActors.suggestions}
renderItem={({item, index}) => (
<RecommendedFollowsItem item={item} index={index} />
<RecommendedFollowsItem
item={item}
index={index}
insertSuggestionsByActor={suggestedActors.insertSuggestionsByActor.bind(
suggestedActors,
)}
/>
)}
keyExtractor={(item, index) => item.did + index.toString()}
style={{flex: 1}}
@@ -126,13 +127,19 @@ export const RecommendedFollows = observer(function RecommendedFollowsImpl({
users.
</Text>
</View>
{store.onboarding.suggestedActors.isLoading ? (
{suggestedActors.isLoading ? (
<ActivityIndicator size="large" />
) : (
<FlatList
data={store.onboarding.suggestedActors.suggestions}
data={suggestedActors.suggestions}
renderItem={({item, index}) => (
<RecommendedFollowsItem item={item} index={index} />
<RecommendedFollowsItem
item={item}
index={index}
insertSuggestionsByActor={suggestedActors.insertSuggestionsByActor.bind(
suggestedActors,
)}
/>
)}
keyExtractor={(item, index) => item.did + index.toString()}
style={{flex: 1}}
@@ -1,4 +1,4 @@
import React, {useMemo} from 'react'
import React from 'react'
import {View, StyleSheet, ActivityIndicator} from 'react-native'
import {AppBskyActorDefs, moderateProfile} from '@atproto/api'
import {observer} from 'mobx-react-lite'
@@ -19,22 +19,19 @@ import {Trans} from '@lingui/macro'
type Props = {
item: SuggestedActor
index: number
insertSuggestionsByActor: (did: string, index: number) => Promise<void>
}
export const RecommendedFollowsItem: React.FC<Props> = ({item, index}) => {
export const RecommendedFollowsItem: React.FC<Props> = ({
item,
index,
insertSuggestionsByActor,
}) => {
const pal = usePalette('default')
const store = useStores()
const {isMobile} = useWebMediaQueries()
const delay = useMemo(() => {
return (
50 *
(Math.abs(store.onboarding.suggestedActors.lastInsertedAtIndex - index) %
5)
)
}, [index, store.onboarding.suggestedActors.lastInsertedAtIndex])
return (
<Animated.View
entering={FadeInRight.delay(delay).springify()}
entering={FadeInRight}
style={[
styles.cardContainer,
pal.view,
@@ -44,7 +41,12 @@ export const RecommendedFollowsItem: React.FC<Props> = ({item, index}) => {
borderRightWidth: isMobile ? undefined : 1,
},
]}>
<ProfileCard key={item.did} profile={item} index={index} />
<ProfileCard
key={item.did}
profile={item}
index={index}
insertSuggestionsByActor={insertSuggestionsByActor}
/>
</Animated.View>
)
}
@@ -52,9 +54,11 @@ export const RecommendedFollowsItem: React.FC<Props> = ({item, index}) => {
export const ProfileCard = observer(function ProfileCardImpl({
profile,
index,
insertSuggestionsByActor,
}: {
profile: AppBskyActorDefs.ProfileViewBasic
index: number
insertSuggestionsByActor: (did: string, index: number) => Promise<void>
}) {
const {track} = useAnalytics()
const store = useStores()
@@ -95,10 +99,7 @@ export const ProfileCard = observer(function ProfileCardImpl({
onToggleFollow={async isFollow => {
if (isFollow) {
setAddingMoreSuggestions(true)
await store.onboarding.suggestedActors.insertSuggestionsByActor(
profile.did,
index,
)
await insertSuggestionsByActor(profile.did, index)
setAddingMoreSuggestions(false)
track('Onboarding:SuggestedFollowFollowed')
}
+3 -1
View File
@@ -13,19 +13,21 @@ import {Onboarding} from './Onboarding'
import {Text} from '../util/text/Text'
import {usePalette} from 'lib/hooks/usePalette'
import {STATUS_PAGE_URL} from 'lib/constants'
import {useOnboardingState} from '#/state/shell'
export const withAuthRequired = <P extends object>(
Component: React.ComponentType<P>,
): React.FC<P> =>
observer(function AuthRequired(props: P) {
const store = useStores()
const onboardingState = useOnboardingState()
if (store.session.isResumingSession) {
return <Loading />
}
if (!store.session.hasSession) {
return <LoggedOut />
}
if (store.onboarding.isActive) {
if (onboardingState.isActive) {
return <Onboarding />
}
return <Component {...props} />
+23 -15
View File
@@ -51,6 +51,13 @@ import {EmojiPickerButton} from './text-input/web/EmojiPicker.web'
import {insertMentionAt} from 'lib/strings/mention-manip'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModals, useModalControls} from '#/state/modals'
import {useRequireAltTextEnabled} from '#/state/preferences'
import {
useLanguagePrefs,
useLanguagePrefsApi,
toPostLanguages,
} from '#/state/preferences/languages'
type Props = ComposerOpts
export const ComposePost = observer(function ComposePost({
@@ -59,11 +66,16 @@ export const ComposePost = observer(function ComposePost({
quote: initQuote,
mention: initMention,
}: Props) {
const {activeModals} = useModals()
const {openModal, closeModal} = useModalControls()
const {track} = useAnalytics()
const pal = usePalette('default')
const {isDesktop, isMobile} = useWebMediaQueries()
const store = useStores()
const {_} = useLingui()
const requireAltTextEnabled = useRequireAltTextEnabled()
const langPrefs = useLanguagePrefs()
const setLangPrefs = useLanguagePrefsApi()
const textInput = useRef<TextInputRef>(null)
const [isKeyboardVisible] = useIsKeyboardVisible({iosUseWillEvents: true})
const [isProcessing, setIsProcessing] = useState(false)
@@ -111,18 +123,18 @@ export const ComposePost = observer(function ComposePost({
const onPressCancel = useCallback(() => {
if (graphemeLength > 0 || !gallery.isEmpty) {
if (store.shell.activeModals.some(modal => modal.name === 'confirm')) {
store.shell.closeModal()
if (activeModals.some(modal => modal.name === 'confirm')) {
closeModal()
}
if (Keyboard) {
Keyboard.dismiss()
}
store.shell.openModal({
openModal({
name: 'confirm',
title: 'Discard draft',
onPressConfirm: onClose,
onPressCancel: () => {
store.shell.closeModal()
closeModal()
},
message: "Are you sure you'd like to discard this draft?",
confirmBtnText: 'Discard',
@@ -131,7 +143,7 @@ export const ComposePost = observer(function ComposePost({
} else {
onClose()
}
}, [store, onClose, graphemeLength, gallery])
}, [openModal, closeModal, activeModals, onClose, graphemeLength, gallery])
// android back button
useEffect(() => {
if (!isAndroid) {
@@ -190,7 +202,7 @@ export const ComposePost = observer(function ComposePost({
if (isProcessing || graphemeLength > MAX_GRAPHEME_LENGTH) {
return
}
if (store.preferences.requireAltTextEnabled && gallery.needsAltText) {
if (requireAltTextEnabled && gallery.needsAltText) {
return
}
@@ -213,7 +225,7 @@ export const ComposePost = observer(function ComposePost({
labels,
onStateChange: setProcessingState,
knownHandles: autocompleteView.knownHandles,
langs: store.preferences.postLanguages,
langs: toPostLanguages(langPrefs.postLanguage),
})
} catch (e: any) {
if (extLink) {
@@ -235,7 +247,7 @@ export const ComposePost = observer(function ComposePost({
if (!replyTo) {
store.me.mainFeed.onPostCreated()
}
store.preferences.savePostLanguageToHistory()
setLangPrefs.savePostLanguageToHistory()
onPost?.()
onClose()
Toast.show(`Your ${replyTo ? 'reply' : 'post'} has been published`)
@@ -244,12 +256,8 @@ export const ComposePost = observer(function ComposePost({
const canPost = useMemo(
() =>
graphemeLength <= MAX_GRAPHEME_LENGTH &&
(!store.preferences.requireAltTextEnabled || !gallery.needsAltText),
[
graphemeLength,
store.preferences.requireAltTextEnabled,
gallery.needsAltText,
],
(!requireAltTextEnabled || !gallery.needsAltText),
[graphemeLength, requireAltTextEnabled, gallery.needsAltText],
)
const selectTextInputPlaceholder = replyTo ? 'Write your reply' : `What's up?`
@@ -321,7 +329,7 @@ export const ComposePost = observer(function ComposePost({
</>
)}
</View>
{store.preferences.requireAltTextEnabled && gallery.needsAltText && (
{requireAltTextEnabled && gallery.needsAltText && (
<View style={[styles.reminderLine, pal.viewLight]}>
<View style={styles.errorIcon}>
<FontAwesomeIcon
+3 -3
View File
@@ -3,13 +3,13 @@ import {Keyboard, StyleSheet} from 'react-native'
import {observer} from 'mobx-react-lite'
import {Button} from 'view/com/util/forms/Button'
import {usePalette} from 'lib/hooks/usePalette'
import {useStores} from 'state/index'
import {ShieldExclamation} from 'lib/icons'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {FontAwesomeIconStyle} from '@fortawesome/react-native-fontawesome'
import {isNative} from 'platform/detection'
import {useLingui} from '@lingui/react'
import {msg} from '@lingui/macro'
import {useModalControls} from '#/state/modals'
export const LabelsBtn = observer(function LabelsBtn({
labels,
@@ -22,7 +22,7 @@ export const LabelsBtn = observer(function LabelsBtn({
}) {
const pal = usePalette('default')
const {_} = useLingui()
const store = useStores()
const {openModal} = useModalControls()
return (
<Button
@@ -37,7 +37,7 @@ export const LabelsBtn = observer(function LabelsBtn({
Keyboard.dismiss()
}
}
store.shell.openModal({name: 'self-label', labels, hasMedia, onChange})
openModal({name: 'self-label', labels, hasMedia, onChange})
}}>
<ShieldExclamation style={pal.link} size={26} />
{labels.length > 0 ? (
+22 -6
View File
@@ -7,13 +7,13 @@ import {s, colors} from 'lib/styles'
import {StyleSheet, TouchableOpacity, View} from 'react-native'
import {Image} from 'expo-image'
import {Text} from 'view/com/util/text/Text'
import {openAltTextModal} from 'lib/media/alt-text'
import {Dimensions} from 'lib/media/types'
import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
import {isNative} from 'platform/detection'
const IMAGE_GAP = 8
@@ -49,10 +49,10 @@ const GalleryInner = observer(function GalleryImpl({
gallery,
containerInfo,
}: GalleryInnerProps) {
const store = useStores()
const pal = usePalette('default')
const {_} = useLingui()
const {isMobile} = useWebMediaQueries()
const {openModal} = useModalControls()
let side: number
@@ -120,7 +120,10 @@ const GalleryInner = observer(function GalleryImpl({
accessibilityHint=""
onPress={() => {
Keyboard.dismiss()
openAltTextModal(store, image)
openModal({
name: 'alt-text-image',
image,
})
}}
style={[styles.altTextControl, altTextControlStyle]}>
<Text style={styles.altTextControlLabel} accessible={false}>
@@ -140,7 +143,17 @@ const GalleryInner = observer(function GalleryImpl({
accessibilityRole="button"
accessibilityLabel={_(msg`Edit image`)}
accessibilityHint=""
onPress={() => gallery.edit(image)}
onPress={() => {
if (isNative) {
gallery.crop(image)
} else {
openModal({
name: 'edit-image',
image,
gallery,
})
}
}}
style={styles.imageControl}>
<FontAwesomeIcon
icon="pen"
@@ -168,7 +181,10 @@ const GalleryInner = observer(function GalleryImpl({
accessibilityHint=""
onPress={() => {
Keyboard.dismiss()
openAltTextModal(store, image)
openModal({
name: 'alt-text-image',
image,
})
}}
style={styles.altTextHiddenRegion}
/>
@@ -12,16 +12,24 @@ import {
DropdownItemButton,
} from 'view/com/util/forms/DropdownButton'
import {usePalette} from 'lib/hooks/usePalette'
import {useStores} from 'state/index'
import {isNative} from 'platform/detection'
import {codeToLanguageName} from '../../../../locale/helpers'
import {useModalControls} from '#/state/modals'
import {
useLanguagePrefs,
useLanguagePrefsApi,
toPostLanguages,
hasPostLanguage,
} from '#/state/preferences/languages'
import {t, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
export const SelectLangBtn = observer(function SelectLangBtn() {
const pal = usePalette('default')
const store = useStores()
const {_} = useLingui()
const {openModal} = useModalControls()
const langPrefs = useLanguagePrefs()
const setLangPrefs = useLanguagePrefsApi()
const onPressMore = useCallback(async () => {
if (isNative) {
@@ -29,11 +37,10 @@ export const SelectLangBtn = observer(function SelectLangBtn() {
Keyboard.dismiss()
}
}
store.shell.openModal({name: 'post-languages-settings'})
}, [store])
openModal({name: 'post-languages-settings'})
}, [openModal])
const postLanguagesPref = store.preferences.postLanguages
const postLanguagePref = store.preferences.postLanguage
const postLanguagesPref = toPostLanguages(langPrefs.postLanguage)
const items: DropdownItem[] = useMemo(() => {
let arr: DropdownItemButton[] = []
@@ -52,13 +59,14 @@ export const SelectLangBtn = observer(function SelectLangBtn() {
arr.push({
icon:
langCodes.every(code => store.preferences.hasPostLanguage(code)) &&
langCodes.length === postLanguagesPref.length
langCodes.every(code =>
hasPostLanguage(langPrefs.postLanguage, code),
) && langCodes.length === postLanguagesPref.length
? ['fas', 'circle-dot']
: ['far', 'circle'],
label: langName,
onPress() {
store.preferences.setPostLanguage(commaSeparatedLangCodes)
setLangPrefs.setPostLanguage(commaSeparatedLangCodes)
},
})
}
@@ -68,11 +76,11 @@ export const SelectLangBtn = observer(function SelectLangBtn() {
* Re-join here after sanitization bc postLanguageHistory is an array of
* comma-separated strings too
*/
add(postLanguagePref)
add(langPrefs.postLanguage)
}
// comma-separted strings of lang codes that have been used in the past
for (const lang of store.preferences.postLanguageHistory) {
for (const lang of langPrefs.postLanguageHistory) {
add(lang)
}
@@ -85,7 +93,7 @@ export const SelectLangBtn = observer(function SelectLangBtn() {
onPress: onPressMore,
},
]
}, [store.preferences, onPressMore, postLanguagePref, postLanguagesPref])
}, [onPressMore, langPrefs, setLangPrefs, postLanguagesPref])
return (
<DropdownButton
+4 -4
View File
@@ -10,12 +10,12 @@ import {observer} from 'mobx-react-lite'
import {FeedSourceModel} from 'state/models/content/feed-source'
import {useNavigation} from '@react-navigation/native'
import {NavigationProp} from 'lib/routes/types'
import {useStores} from 'state/index'
import {pluralize} from 'lib/strings/helpers'
import {AtUri} from '@atproto/api'
import * as Toast from 'view/com/util/Toast'
import {sanitizeHandle} from 'lib/strings/handles'
import {logger} from '#/logger'
import {useModalControls} from '#/state/modals'
export const FeedSourceCard = observer(function FeedSourceCardImpl({
item,
@@ -30,13 +30,13 @@ export const FeedSourceCard = observer(function FeedSourceCardImpl({
showDescription?: boolean
showLikes?: boolean
}) {
const store = useStores()
const pal = usePalette('default')
const navigation = useNavigation<NavigationProp>()
const {openModal} = useModalControls()
const onToggleSaved = React.useCallback(async () => {
if (item.isSaved) {
store.shell.openModal({
openModal({
name: 'confirm',
title: 'Remove from my feeds',
message: `Remove ${item.displayName} from my feeds?`,
@@ -59,7 +59,7 @@ export const FeedSourceCard = observer(function FeedSourceCardImpl({
logger.error('Failed to save feed', {error: e})
}
}
}, [store, item])
}, [openModal, item])
return (
<Pressable
+4 -4
View File
@@ -17,11 +17,11 @@ import {Button} from '../util/forms/Button'
import {ListModel} from 'state/models/content/list'
import {useAnalytics} from 'lib/analytics/analytics'
import {usePalette} from 'lib/hooks/usePalette'
import {useStores} from 'state/index'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {s} from 'lib/styles'
import {OnScrollCb} from 'lib/hooks/useOnMainScroll'
import {logger} from '#/logger'
import {useModalControls} from '#/state/modals'
const LOADING_ITEM = {_reactKey: '__loading__'}
const EMPTY_ITEM = {_reactKey: '__empty__'}
@@ -54,10 +54,10 @@ export const ListItems = observer(function ListItemsImpl({
desktopFixedHeightOffset?: number
}) {
const pal = usePalette('default')
const store = useStores()
const {track} = useAnalytics()
const [isRefreshing, setIsRefreshing] = React.useState(false)
const {isMobile} = useWebMediaQueries()
const {openModal} = useModalControls()
const data = React.useMemo(() => {
let items: any[] = []
@@ -115,7 +115,7 @@ export const ListItems = observer(function ListItemsImpl({
const onPressEditMembership = React.useCallback(
(profile: AppBskyActorDefs.ProfileViewBasic) => {
store.shell.openModal({
openModal({
name: 'user-add-remove-lists',
subject: profile.did,
displayName: profile.displayName || profile.handle,
@@ -131,7 +131,7 @@ export const ListItems = observer(function ListItemsImpl({
},
})
},
[store, list],
[openModal, list],
)
// rendering
+4 -2
View File
@@ -15,6 +15,7 @@ import * as Toast from '../util/Toast'
import {logger} from '#/logger'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['70%']
@@ -57,6 +58,7 @@ export function Component({}: {}) {
const pal = usePalette('default')
const store = useStores()
const {_} = useLingui()
const {closeModal} = useModalControls()
const [name, setName] = useState(
shadesOfBlue[Math.floor(Math.random() * shadesOfBlue.length)],
)
@@ -72,8 +74,8 @@ export function Component({}: {}) {
}, [appPassword])
const onDone = React.useCallback(() => {
store.shell.closeModal()
}, [store])
closeModal()
}, [closeModal])
const createAppPassword = async () => {
// if name is all whitespace, we don't allow it
+5 -5
View File
@@ -17,11 +17,11 @@ import {MAX_ALT_TEXT} from 'lib/constants'
import {useTheme} from 'lib/ThemeContext'
import {Text} from '../util/text/Text'
import LinearGradient from 'react-native-linear-gradient'
import {useStores} from 'state/index'
import {isAndroid, isWeb} from 'platform/detection'
import {ImageModel} from 'state/models/media/image'
import {useLingui} from '@lingui/react'
import {Trans, msg} from '@lingui/macro'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['fullscreen']
@@ -31,11 +31,11 @@ interface Props {
export function Component({image}: Props) {
const pal = usePalette('default')
const store = useStores()
const theme = useTheme()
const {_} = useLingui()
const [altText, setAltText] = useState(image.altText)
const windim = useWindowDimensions()
const {closeModal} = useModalControls()
const imageStyles = useMemo<ImageStyle>(() => {
const maxWidth = isWeb ? 450 : windim.width
@@ -56,11 +56,11 @@ export function Component({image}: Props) {
const onPressSave = useCallback(() => {
image.setAltText(altText)
store.shell.closeModal()
}, [store, image, altText])
closeModal()
}, [closeModal, image, altText])
const onPressCancel = () => {
store.shell.closeModal()
closeModal()
}
return (
+3 -1
View File
@@ -17,6 +17,7 @@ import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {cleanError} from 'lib/strings/errors'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['50%']
@@ -24,6 +25,7 @@ export const Component = observer(function Component({}: {}) {
const pal = usePalette('default')
const store = useStores()
const {_} = useLingui()
const {closeModal} = useModalControls()
const [date, setDate] = useState<Date>(
store.preferences.birthDate || new Date(),
)
@@ -36,7 +38,7 @@ export const Component = observer(function Component({}: {}) {
setIsProcessing(true)
try {
await store.preferences.setBirthDate(date)
store.shell.closeModal()
closeModal()
} catch (e) {
setError(cleanError(String(e)))
} finally {
+5 -3
View File
@@ -14,6 +14,7 @@ import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {cleanError} from 'lib/strings/errors'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
enum Stages {
InputEmail,
@@ -35,6 +36,7 @@ export const Component = observer(function Component({}: {}) {
const [isProcessing, setIsProcessing] = useState<boolean>(false)
const [error, setError] = useState<string>('')
const {isMobile} = useWebMediaQueries()
const {openModal, closeModal} = useModalControls()
const onRequestChange = async () => {
if (email === store.session.currentSession?.email) {
@@ -95,8 +97,8 @@ export const Component = observer(function Component({}: {}) {
}
const onVerify = async () => {
store.shell.closeModal()
store.shell.openModal({name: 'verify-email'})
closeModal()
openModal({name: 'verify-email'})
}
return (
@@ -212,7 +214,7 @@ export const Component = observer(function Component({}: {}) {
<Button
testID="cancelBtn"
type="default"
onPress={() => store.shell.closeModal()}
onPress={() => closeModal()}
accessibilityLabel={_(msg`Cancel`)}
accessibilityHint=""
label={_(msg`Cancel`)}
+6 -3
View File
@@ -24,6 +24,7 @@ import {cleanError} from 'lib/strings/errors'
import {logger} from '#/logger'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['100%']
@@ -33,6 +34,7 @@ export function Component({onChanged}: {onChanged: () => void}) {
const pal = usePalette('default')
const {track} = useAnalytics()
const {_} = useLingui()
const {closeModal} = useModalControls()
const [isProcessing, setProcessing] = useState<boolean>(false)
const [retryDescribeTrigger, setRetryDescribeTrigger] = React.useState<any>(
@@ -88,8 +90,8 @@ export function Component({onChanged}: {onChanged: () => void}) {
// events
// =
const onPressCancel = React.useCallback(() => {
store.shell.closeModal()
}, [store])
closeModal()
}, [closeModal])
const onPressRetryConnect = React.useCallback(
() => setRetryDescribeTrigger({}),
[setRetryDescribeTrigger],
@@ -113,7 +115,7 @@ export function Component({onChanged}: {onChanged: () => void}) {
await store.agent.updateHandle({
handle: newHandle,
})
store.shell.closeModal()
closeModal()
onChanged()
} catch (err: any) {
setError(cleanError(err))
@@ -130,6 +132,7 @@ export function Component({onChanged}: {onChanged: () => void}) {
isCustom,
onChanged,
track,
closeModal,
])
// rendering
+4 -5
View File
@@ -6,15 +6,15 @@ import {
View,
} from 'react-native'
import {Text} from '../util/text/Text'
import {useStores} from 'state/index'
import {s, colors} from 'lib/styles'
import {ErrorMessage} from '../util/error/ErrorMessage'
import {cleanError} from 'lib/strings/errors'
import {usePalette} from 'lib/hooks/usePalette'
import {isWeb} from 'platform/detection'
import type {ConfirmModal} from 'state/models/ui/shell'
import {useLingui} from '@lingui/react'
import {msg} from '@lingui/macro'
import type {ConfirmModal} from '#/state/modals'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['50%']
@@ -28,9 +28,8 @@ export function Component({
cancelBtnText,
}: ConfirmModal) {
const pal = usePalette('default')
const store = useStores()
const {_} = useLingui()
const {closeModal} = useModalControls()
const [isProcessing, setIsProcessing] = useState<boolean>(false)
const [error, setError] = useState<string>('')
const onPress = async () => {
@@ -38,7 +37,7 @@ export function Component({
setIsProcessing(true)
try {
await onPressConfirm()
store.shell.closeModal()
closeModal()
return
} catch (e: any) {
setError(cleanError(e))
@@ -18,6 +18,7 @@ import * as Toast from '../util/Toast'
import {logger} from '#/logger'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['90%']
@@ -27,14 +28,15 @@ export const Component = observer(
const {isMobile} = useWebMediaQueries()
const pal = usePalette('default')
const {_} = useLingui()
const {closeModal} = useModalControls()
React.useEffect(() => {
store.preferences.sync()
}, [store])
const onPressDone = React.useCallback(() => {
store.shell.closeModal()
}, [store])
closeModal()
}, [closeModal])
return (
<View testID="contentFilteringModal" style={[pal.view, styles.container]}>
@@ -96,8 +98,9 @@ const AdultContentEnabledPref = observer(
function AdultContentEnabledPrefImpl() {
const store = useStores()
const pal = usePalette('default')
const {openModal} = useModalControls()
const onSetAge = () => store.shell.openModal({name: 'birth-date-settings'})
const onSetAge = () => openModal({name: 'birth-date-settings'})
const onToggleAdultContent = async () => {
if (isIOS) {
+6 -3
View File
@@ -26,6 +26,7 @@ import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {cleanError, isNetworkError} from 'lib/strings/errors'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
const MAX_NAME = 64 // todo
const MAX_DESCRIPTION = 300 // todo
@@ -42,6 +43,7 @@ export function Component({
list?: ListModel
}) {
const store = useStores()
const {closeModal} = useModalControls()
const {isMobile} = useWebMediaQueries()
const [error, setError] = useState<string>('')
const pal = usePalette('default')
@@ -70,8 +72,8 @@ export function Component({
const [newAvatar, setNewAvatar] = useState<RNImage | undefined | null>()
const onPressCancel = useCallback(() => {
store.shell.closeModal()
}, [store])
closeModal()
}, [closeModal])
const onSelectNewAvatar = useCallback(
async (img: RNImage | null) => {
@@ -126,7 +128,7 @@ export function Component({
Toast.show(`${purposeLabel} list created`)
onSave?.(res.uri)
}
store.shell.closeModal()
closeModal()
} catch (e: any) {
if (isNetworkError(e)) {
setError(
@@ -144,6 +146,7 @@ export function Component({
error,
onSave,
store,
closeModal,
activePurpose,
isCurateList,
purposeLabel,
+4 -2
View File
@@ -19,6 +19,7 @@ import {cleanError} from 'lib/strings/errors'
import {resetToTab} from '../../../Navigation'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['60%']
@@ -27,6 +28,7 @@ export function Component({}: {}) {
const theme = useTheme()
const store = useStores()
const {_} = useLingui()
const {closeModal} = useModalControls()
const {isMobile} = useWebMediaQueries()
const [isEmailSent, setIsEmailSent] = React.useState<boolean>(false)
const [confirmCode, setConfirmCode] = React.useState<string>('')
@@ -58,14 +60,14 @@ export function Component({}: {}) {
Toast.show('Your account has been deleted')
resetToTab('HomeTab')
store.session.clear()
store.shell.closeModal()
closeModal()
} catch (e: any) {
setError(cleanError(e))
}
setIsProcessing(false)
}
const onCancel = () => {
store.shell.closeModal()
closeModal()
}
return (
<View style={[styles.container, pal.view]}>
+4 -4
View File
@@ -6,7 +6,6 @@ import {gradients, s} from 'lib/styles'
import {useTheme} from 'lib/ThemeContext'
import {Text} from '../util/text/Text'
import LinearGradient from 'react-native-linear-gradient'
import {useStores} from 'state/index'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import ImageEditor, {Position} from 'react-avatar-editor'
import {TextInput} from './util'
@@ -21,6 +20,7 @@ import {observer} from 'mobx-react-lite'
import {getKeys} from 'lib/type-assertions'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['80%']
@@ -54,10 +54,10 @@ export const Component = observer(function EditImageImpl({
}: Props) {
const pal = usePalette('default')
const theme = useTheme()
const store = useStores()
const {_} = useLingui()
const windowDimensions = useWindowDimensions()
const {isMobile} = useWebMediaQueries()
const {closeModal} = useModalControls()
const {
aspectRatio,
@@ -131,8 +131,8 @@ export const Component = observer(function EditImageImpl({
}, [image])
const onCloseModal = useCallback(() => {
store.shell.closeModal()
}, [store.shell])
closeModal()
}, [closeModal])
const onPressCancel = useCallback(async () => {
await gallery.previous(image)
+5 -5
View File
@@ -13,7 +13,6 @@ import LinearGradient from 'react-native-linear-gradient'
import {Image as RNImage} from 'react-native-image-crop-picker'
import {Text} from '../util/text/Text'
import {ErrorMessage} from '../util/error/ErrorMessage'
import {useStores} from 'state/index'
import {ProfileModel} from 'state/models/content/profile'
import {s, colors, gradients} from 'lib/styles'
import {enforceLen} from 'lib/strings/helpers'
@@ -29,6 +28,7 @@ import Animated, {FadeOut} from 'react-native-reanimated'
import {isWeb} from 'platform/detection'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
const AnimatedTouchableOpacity =
Animated.createAnimatedComponent(TouchableOpacity)
@@ -42,12 +42,12 @@ export function Component({
profileView: ProfileModel
onUpdate?: () => void
}) {
const store = useStores()
const [error, setError] = useState<string>('')
const pal = usePalette('default')
const theme = useTheme()
const {track} = useAnalytics()
const {_} = useLingui()
const {closeModal} = useModalControls()
const [isProcessing, setProcessing] = useState<boolean>(false)
const [displayName, setDisplayName] = useState<string>(
@@ -69,7 +69,7 @@ export function Component({
RNImage | undefined | null
>()
const onPressCancel = () => {
store.shell.closeModal()
closeModal()
}
const onSelectNewAvatar = useCallback(
async (img: RNImage | null) => {
@@ -126,7 +126,7 @@ export function Component({
)
Toast.show('Profile updated')
onUpdate?.()
store.shell.closeModal()
closeModal()
} catch (e: any) {
if (isNetworkError(e)) {
setError(
@@ -144,7 +144,7 @@ export function Component({
error,
profileView,
onUpdate,
store,
closeModal,
displayName,
description,
newUserAvatar,
+83 -44
View File
@@ -1,6 +1,7 @@
import React from 'react'
import {StyleSheet, TouchableOpacity, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import {ComAtprotoServerDefs} from '@atproto/api'
import {
FontAwesomeIcon,
FontAwesomeIconStyle,
@@ -15,25 +16,33 @@ import {usePalette} from 'lib/hooks/usePalette'
import {isWeb} from 'platform/detection'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {Trans} from '@lingui/macro'
import {useModalControls} from '#/state/modals'
import {useInvitesState, useInvitesAPI} from '#/state/invites'
import {UserInfoText} from '../util/UserInfoText'
import {makeProfileLink} from '#/lib/routes/links'
import {Link} from '../util/Link'
export const snapPoints = ['70%']
export function Component({}: {}) {
const pal = usePalette('default')
const store = useStores()
const {closeModal} = useModalControls()
const {isTabletOrDesktop} = useWebMediaQueries()
const onClose = React.useCallback(() => {
store.shell.closeModal()
}, [store])
closeModal()
}, [closeModal])
if (store.me.invites.length === 0) {
return (
<View style={[styles.container, pal.view]} testID="inviteCodesModal">
<View style={[styles.empty, pal.viewLight]}>
<Text type="lg" style={[pal.text, styles.emptyText]}>
You don't have any invite codes yet! We'll send you some when you've
been on Bluesky for a little longer.
<Trans>
You don't have any invite codes yet! We'll send you some when
you've been on Bluesky for a little longer.
</Trans>
</Text>
</View>
<View style={styles.flex1} />
@@ -57,17 +66,19 @@ export function Component({}: {}) {
return (
<View style={[styles.container, pal.view]} testID="inviteCodesModal">
<Text type="title-xl" style={[styles.title, pal.text]}>
Invite a Friend
<Trans>Invite a Friend</Trans>
</Text>
<Text type="lg" style={[styles.description, pal.text]}>
Each code works once. You'll receive more invite codes periodically.
<Trans>
Each code works once. You'll receive more invite codes periodically.
</Trans>
</Text>
<ScrollView style={[styles.scrollContainer, pal.border]}>
{store.me.invites.map((invite, i) => (
<InviteCode
testID={`inviteCode-${i}`}
key={invite.code}
code={invite.code}
invite={invite}
used={invite.available - invite.uses.length <= 0 || invite.disabled}
/>
))}
@@ -88,54 +99,85 @@ export function Component({}: {}) {
const InviteCode = observer(function InviteCodeImpl({
testID,
code,
invite,
used,
}: {
testID: string
code: string
invite: ComAtprotoServerDefs.InviteCode
used?: boolean
}) {
const pal = usePalette('default')
const store = useStores()
const {invitesAvailable} = store.me
const invitesState = useInvitesState()
const {setInviteCopied} = useInvitesAPI()
const onPress = React.useCallback(() => {
Clipboard.setString(code)
Clipboard.setString(invite.code)
Toast.show('Copied to clipboard')
store.invitedUsers.setInviteCopied(code)
}, [store, code])
setInviteCopied(invite.code)
}, [setInviteCopied, invite])
return (
<TouchableOpacity
testID={testID}
style={[styles.inviteCode, pal.border]}
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={
invitesAvailable === 1
? 'Invite codes: 1 available'
: `Invite codes: ${invitesAvailable} available`
}
accessibilityHint="Opens list of invite codes">
<Text
testID={`${testID}-code`}
type={used ? 'md' : 'md-bold'}
style={used ? [pal.textLight, styles.strikeThrough] : pal.text}>
{code}
</Text>
<View style={styles.flex1} />
{!used && store.invitedUsers.isInviteCopied(code) && (
<Text style={[pal.textLight, styles.codeCopied]}>
<Trans>Copied</Trans>
<View
style={[
pal.border,
{borderBottomWidth: 1, paddingHorizontal: 20, paddingVertical: 14},
]}>
<TouchableOpacity
testID={testID}
style={[styles.inviteCode]}
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={
invitesAvailable === 1
? 'Invite codes: 1 available'
: `Invite codes: ${invitesAvailable} available`
}
accessibilityHint="Opens list of invite codes">
<Text
testID={`${testID}-code`}
type={used ? 'md' : 'md-bold'}
style={used ? [pal.textLight, styles.strikeThrough] : pal.text}>
{invite.code}
</Text>
)}
{!used && (
<FontAwesomeIcon
icon={['far', 'clone']}
style={pal.text as FontAwesomeIconStyle}
/>
)}
</TouchableOpacity>
<View style={styles.flex1} />
{!used && invitesState.copiedInvites.includes(invite.code) && (
<Text style={[pal.textLight, styles.codeCopied]}>
<Trans>Copied</Trans>
</Text>
)}
{!used && (
<FontAwesomeIcon
icon={['far', 'clone']}
style={pal.text as FontAwesomeIconStyle}
/>
)}
</TouchableOpacity>
{invite.uses.length > 0 ? (
<View
style={{
flexDirection: 'column',
gap: 8,
paddingTop: 6,
}}>
<Text style={pal.text}>
<Trans>Used by:</Trans>
</Text>
{invite.uses.map(use => (
<Link
key={use.usedBy}
href={makeProfileLink({handle: use.usedBy, did: ''})}
style={{
flexDirection: 'row',
}}>
<Text style={pal.text}> </Text>
<UserInfoText did={use.usedBy} style={pal.link} />
</Link>
))}
</View>
) : null}
</View>
)
})
@@ -179,9 +221,6 @@ const styles = StyleSheet.create({
inviteCode: {
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: 1,
paddingHorizontal: 20,
paddingVertical: 14,
},
codeCopied: {
marginRight: 8,
+4 -4
View File
@@ -5,7 +5,6 @@ import {observer} from 'mobx-react-lite'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {Text} from '../util/text/Text'
import {Button} from '../util/forms/Button'
import {useStores} from 'state/index'
import {s, colors} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {isWeb} from 'platform/detection'
@@ -13,6 +12,7 @@ import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {isPossiblyAUrl, splitApexDomain} from 'lib/strings/url-helpers'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['50%']
@@ -24,13 +24,13 @@ export const Component = observer(function Component({
href: string
}) {
const pal = usePalette('default')
const store = useStores()
const {closeModal} = useModalControls()
const {isMobile} = useWebMediaQueries()
const {_} = useLingui()
const potentiallyMisleading = isPossiblyAUrl(text)
const onPressVisit = () => {
store.shell.closeModal()
closeModal()
Linking.openURL(href)
}
@@ -86,7 +86,7 @@ export const Component = observer(function Component({
<Button
testID="cancelBtn"
type="default"
onPress={() => store.shell.closeModal()}
onPress={() => closeModal()}
accessibilityLabel={_(msg`Cancel`)}
accessibilityHint=""
label="Cancel"
+3 -1
View File
@@ -28,6 +28,7 @@ import {sanitizeHandle} from 'lib/strings/handles'
import {HITSLOP_20} from '#/lib/constants'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['90%']
@@ -41,6 +42,7 @@ export const Component = observer(function Component({
const pal = usePalette('default')
const store = useStores()
const {_} = useLingui()
const {closeModal} = useModalControls()
const {isMobile} = useWebMediaQueries()
const [query, setQuery] = useState('')
const autocompleteView = useMemo<UserAutocompleteModel>(
@@ -149,7 +151,7 @@ export const Component = observer(function Component({
<Button
testID="doneBtn"
type="default"
onPress={() => store.shell.closeModal()}
onPress={() => closeModal()}
accessibilityLabel={_(msg`Done`)}
accessibilityHint=""
label="Done"
+12 -12
View File
@@ -3,13 +3,13 @@ import {StyleSheet} from 'react-native'
import {SafeAreaView, useSafeAreaInsets} from 'react-native-safe-area-context'
import {observer} from 'mobx-react-lite'
import BottomSheet from '@gorhom/bottom-sheet'
import {useStores} from 'state/index'
import {createCustomBackdrop} from '../util/BottomSheetCustomBackdrop'
import {usePalette} from 'lib/hooks/usePalette'
import {timeout} from 'lib/async/timeout'
import {navigate} from '../../../Navigation'
import once from 'lodash.once'
import {useModals, useModalControls} from '#/state/modals'
import * as ConfirmModal from './Confirm'
import * as EditProfileModal from './EditProfile'
import * as ProfilePreviewModal from './ProfilePreview'
@@ -41,17 +41,17 @@ const DEFAULT_SNAPPOINTS = ['90%']
const HANDLE_HEIGHT = 24
export const ModalsContainer = observer(function ModalsContainer() {
const store = useStores()
const {isModalActive, activeModals} = useModals()
const {closeModal} = useModalControls()
const bottomSheetRef = useRef<BottomSheet>(null)
const pal = usePalette('default')
const safeAreaInsets = useSafeAreaInsets()
const activeModal =
store.shell.activeModals[store.shell.activeModals.length - 1]
const activeModal = activeModals[activeModals.length - 1]
const navigateOnce = once(navigate)
const onBottomSheetAnimate = (fromIndex: number, toIndex: number) => {
const onBottomSheetAnimate = (_fromIndex: number, toIndex: number) => {
if (activeModal?.name === 'profile-preview' && toIndex === 1) {
// begin loading the profile screen behind the scenes
navigateOnce('Profile', {name: activeModal.did})
@@ -59,7 +59,7 @@ export const ModalsContainer = observer(function ModalsContainer() {
}
const onBottomSheetChange = async (snapPoint: number) => {
if (snapPoint === -1) {
store.shell.closeModal()
closeModal()
} else if (activeModal?.name === 'profile-preview' && snapPoint === 1) {
await navigateOnce('Profile', {name: activeModal.did})
// There is no particular callback for when the view has actually been presented.
@@ -67,21 +67,21 @@ export const ModalsContainer = observer(function ModalsContainer() {
// It's acceptable because the data is already being fetched + it usually takes longer anyway.
// TODO: Figure out why avatar/cover don't always show instantly from cache.
await timeout(200)
store.shell.closeModal()
closeModal()
}
}
const onClose = () => {
bottomSheetRef.current?.close()
store.shell.closeModal()
closeModal()
}
useEffect(() => {
if (store.shell.isModalActive) {
if (isModalActive) {
bottomSheetRef.current?.expand()
} else {
bottomSheetRef.current?.close()
}
}, [store.shell.isModalActive, bottomSheetRef, activeModal?.name])
}, [isModalActive, bottomSheetRef, activeModal?.name])
let needsSafeTopInset = false
let snapPoints: (string | number)[] = DEFAULT_SNAPPOINTS
@@ -184,12 +184,12 @@ export const ModalsContainer = observer(function ModalsContainer() {
snapPoints={snapPoints}
topInset={topInset}
handleHeight={HANDLE_HEIGHT}
index={store.shell.isModalActive ? 0 : -1}
index={isModalActive ? 0 : -1}
enablePanDownToClose
android_keyboardInputMode="adjustResize"
keyboardBlurBehavior="restore"
backdropComponent={
store.shell.isModalActive ? createCustomBackdrop(onClose) : undefined
isModalActive ? createCustomBackdrop(onClose) : undefined
}
handleIndicatorStyle={{backgroundColor: pal.text.color}}
handleStyle={[styles.handle, pal.view]}
+9 -8
View File
@@ -1,11 +1,11 @@
import React from 'react'
import {TouchableWithoutFeedback, StyleSheet, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import type {Modal as ModalIface} from 'state/models/ui/shell'
import type {Modal as ModalIface} from '#/state/modals'
import {useModals, useModalControls} from '#/state/modals'
import * as ConfirmModal from './Confirm'
import * as EditProfileModal from './EditProfile'
import * as ProfilePreviewModal from './ProfilePreview'
@@ -34,15 +34,15 @@ import * as ChangeEmailModal from './ChangeEmail'
import * as LinkWarningModal from './LinkWarning'
export const ModalsContainer = observer(function ModalsContainer() {
const store = useStores()
const {isModalActive, activeModals} = useModals()
if (!store.shell.isModalActive) {
if (!isModalActive) {
return null
}
return (
<>
{store.shell.activeModals.map((modal, i) => (
{activeModals.map((modal, i) => (
<Modal key={`modal-${i}`} modal={modal} />
))}
</>
@@ -50,11 +50,12 @@ export const ModalsContainer = observer(function ModalsContainer() {
})
function Modal({modal}: {modal: ModalIface}) {
const store = useStores()
const {isModalActive} = useModals()
const {closeModal} = useModalControls()
const pal = usePalette('default')
const {isMobile} = useWebMediaQueries()
if (!store.shell.isModalActive) {
if (!isModalActive) {
return null
}
@@ -62,7 +63,7 @@ function Modal({modal}: {modal: ModalIface}) {
if (modal.name === 'crop-image' || modal.name === 'edit-image') {
return // dont close on mask presses during crop
}
store.shell.closeModal()
closeModal()
}
const onInnerPress = () => {
// TODO: can we use prevent default?
+3 -6
View File
@@ -1,7 +1,6 @@
import React from 'react'
import {StyleSheet, View} from 'react-native'
import {ModerationUI} from '@atproto/api'
import {useStores} from 'state/index'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {s} from 'lib/styles'
import {Text} from '../util/text/Text'
@@ -10,6 +9,7 @@ import {usePalette} from 'lib/hooks/usePalette'
import {isWeb} from 'platform/detection'
import {listUriToHref} from 'lib/strings/url-helpers'
import {Button} from '../util/forms/Button'
import {useModalControls} from '#/state/modals'
export const snapPoints = [300]
@@ -20,7 +20,7 @@ export function Component({
context: 'account' | 'content'
moderation: ModerationUI
}) {
const store = useStores()
const {closeModal} = useModalControls()
const {isMobile} = useWebMediaQueries()
const pal = usePalette('default')
@@ -99,10 +99,7 @@ export function Component({
{description}
</Text>
<View style={s.flex1} />
<Button
type="primary"
style={styles.btn}
onPress={() => store.shell.closeModal()}>
<Button type="primary" style={styles.btn} onPress={() => closeModal()}>
<Text type="button-lg" style={[pal.textLight, s.textCenter, s.white]}>
Okay
</Text>
+3 -4
View File
@@ -1,7 +1,6 @@
import React from 'react'
import {StyleSheet, TouchableOpacity, View} from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import {useStores} from 'state/index'
import {s, colors, gradients} from 'lib/styles'
import {Text} from '../util/text/Text'
import {usePalette} from 'lib/hooks/usePalette'
@@ -9,6 +8,7 @@ import {RepostIcon} from 'lib/icons'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = [250]
@@ -22,12 +22,11 @@ export function Component({
isReposted: boolean
// TODO: Add author into component
}) {
const store = useStores()
const pal = usePalette('default')
const {_} = useLingui()
const {closeModal} = useModalControls()
const onPress = async () => {
store.shell.closeModal()
closeModal()
}
return (
+3 -3
View File
@@ -2,7 +2,6 @@ import React, {useState} from 'react'
import {StyleSheet, TouchableOpacity, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import {Text} from '../util/text/Text'
import {useStores} from 'state/index'
import {s, colors} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
@@ -12,6 +11,7 @@ import {SelectableBtn} from '../util/forms/SelectableBtn'
import {ScrollView} from 'view/com/modals/util'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
const ADULT_CONTENT_LABELS = ['sexual', 'nudity', 'porn']
@@ -27,7 +27,7 @@ export const Component = observer(function Component({
onChange: (labels: string[]) => void
}) {
const pal = usePalette('default')
const store = useStores()
const {closeModal} = useModalControls()
const {isMobile} = useWebMediaQueries()
const [selected, setSelected] = useState(labels)
const {_} = useLingui()
@@ -148,7 +148,7 @@ export const Component = observer(function Component({
<TouchableOpacity
testID="confirmBtn"
onPress={() => {
store.shell.closeModal()
closeModal()
}}
style={styles.btn}
accessibilityRole="button"
+3 -3
View File
@@ -6,7 +6,6 @@ import {
} from '@fortawesome/react-native-fontawesome'
import {ScrollView, TextInput} from './util'
import {Text} from '../util/text/Text'
import {useStores} from 'state/index'
import {s, colors} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {useTheme} from 'lib/ThemeContext'
@@ -14,21 +13,22 @@ import {LOCAL_DEV_SERVICE, STAGING_SERVICE, PROD_SERVICE} from 'state/index'
import {LOGIN_INCLUDE_DEV_SERVERS} from 'lib/build-flags'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['80%']
export function Component({onSelect}: {onSelect: (url: string) => void}) {
const theme = useTheme()
const pal = usePalette('default')
const store = useStores()
const [customUrl, setCustomUrl] = useState<string>('')
const {_} = useLingui()
const {closeModal} = useModalControls()
const doSelect = (url: string) => {
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = `https://${url}`
}
store.shell.closeModal()
closeModal()
onSelect(url)
}
+6 -4
View File
@@ -23,6 +23,7 @@ import isEqual from 'lodash.isequal'
import {logger} from '#/logger'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['fullscreen']
@@ -38,6 +39,7 @@ export const Component = observer(function UserAddRemoveListsImpl({
onRemove?: (listUri: string) => void
}) {
const store = useStores()
const {closeModal} = useModalControls()
const pal = usePalette('default')
const {_} = useLingui()
const palPrimary = usePalette('primary')
@@ -72,8 +74,8 @@ export const Component = observer(function UserAddRemoveListsImpl({
}, [memberships, listsList, store, setSelected, setMembershipsLoaded])
const onPressCancel = useCallback(() => {
store.shell.closeModal()
}, [store])
closeModal()
}, [closeModal])
const onPressSave = useCallback(async () => {
let changes
@@ -90,8 +92,8 @@ export const Component = observer(function UserAddRemoveListsImpl({
for (const uri of changes.removed) {
onRemove?.(uri)
}
store.shell.closeModal()
}, [store, selected, memberships, onAdd, onRemove])
closeModal()
}, [closeModal, selected, memberships, onAdd, onRemove])
const onToggleSelected = useCallback(
(uri: string) => {
+6 -4
View File
@@ -22,6 +22,7 @@ import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {cleanError} from 'lib/strings/errors'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['90%']
@@ -46,6 +47,7 @@ export const Component = observer(function Component({
const [isProcessing, setIsProcessing] = useState<boolean>(false)
const [error, setError] = useState<string>('')
const {isMobile} = useWebMediaQueries()
const {openModal, closeModal} = useModalControls()
const onSendEmail = async () => {
setError('')
@@ -70,7 +72,7 @@ export const Component = observer(function Component({
})
store.session.updateLocalAccountData({emailConfirmed: true})
Toast.show('Email verified')
store.shell.closeModal()
closeModal()
} catch (e) {
setError(cleanError(String(e)))
} finally {
@@ -79,8 +81,8 @@ export const Component = observer(function Component({
}
const onEmailIncorrect = () => {
store.shell.closeModal()
store.shell.openModal({name: 'change-email'})
closeModal()
openModal({name: 'change-email'})
}
return (
@@ -227,7 +229,7 @@ export const Component = observer(function Component({
<Button
testID="cancelBtn"
type="default"
onPress={() => store.shell.closeModal()}
onPress={() => closeModal()}
accessibilityLabel={
stage === Stages.Reminder ? 'Not right now' : 'Cancel'
}
+3 -3
View File
@@ -12,7 +12,6 @@ import {
} from '@fortawesome/react-native-fontawesome'
import LinearGradient from 'react-native-linear-gradient'
import {Text} from '../util/text/Text'
import {useStores} from 'state/index'
import {s, gradients} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {useTheme} from 'lib/ThemeContext'
@@ -20,14 +19,15 @@ import {ErrorMessage} from '../util/error/ErrorMessage'
import {cleanError} from 'lib/strings/errors'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export const snapPoints = ['80%']
export function Component({}: {}) {
const pal = usePalette('default')
const theme = useTheme()
const store = useStores()
const {_} = useLingui()
const {closeModal} = useModalControls()
const [email, setEmail] = React.useState<string>('')
const [isEmailSent, setIsEmailSent] = React.useState<boolean>(false)
const [isProcessing, setIsProcessing] = React.useState<boolean>(false)
@@ -57,7 +57,7 @@ export function Component({}: {}) {
setIsProcessing(false)
}
const onCancel = () => {
store.shell.closeModal()
closeModal()
}
return (
@@ -7,12 +7,12 @@ import {Text} from 'view/com/util/text/Text'
import {Dimensions} from 'lib/media/types'
import {getDataUriSize} from 'lib/media/util'
import {s, gradients} from 'lib/styles'
import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette'
import {SquareIcon, RectWideIcon, RectTallIcon} from 'lib/icons'
import {Image as RNImage} from 'react-native-image-crop-picker'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
enum AspectRatio {
Square = 'square',
@@ -35,7 +35,7 @@ export function Component({
uri: string
onSelect: (img?: RNImage) => void
}) {
const store = useStores()
const {closeModal} = useModalControls()
const pal = usePalette('default')
const {_} = useLingui()
const [as, setAs] = React.useState<AspectRatio>(AspectRatio.Square)
@@ -46,7 +46,7 @@ export function Component({
const onPressCancel = () => {
onSelect(undefined)
store.shell.closeModal()
closeModal()
}
const onPressDone = () => {
const canvas = editorRef.current?.getImageScaledToCanvas()
@@ -62,7 +62,7 @@ export function Component({
} else {
onSelect(undefined)
}
store.shell.closeModal()
closeModal()
}
let cropperStyle
@@ -1,7 +1,6 @@
import React from 'react'
import {StyleSheet, View} from 'react-native'
import {ScrollView} from '../util'
import {useStores} from 'state/index'
import {Text} from '../../util/text/Text'
import {usePalette} from 'lib/hooks/usePalette'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
@@ -10,16 +9,23 @@ import {LANGUAGES, LANGUAGES_MAP_CODE2} from '../../../../locale/languages'
import {LanguageToggle} from './LanguageToggle'
import {ConfirmLanguagesButton} from './ConfirmLanguagesButton'
import {Trans} from '@lingui/macro'
import {useModalControls} from '#/state/modals'
import {
useLanguagePrefs,
useLanguagePrefsApi,
} from '#/state/preferences/languages'
export const snapPoints = ['100%']
export function Component({}: {}) {
const store = useStores()
const {closeModal} = useModalControls()
const langPrefs = useLanguagePrefs()
const setLangPrefs = useLanguagePrefsApi()
const pal = usePalette('default')
const {isMobile} = useWebMediaQueries()
const onPressDone = React.useCallback(() => {
store.shell.closeModal()
}, [store])
closeModal()
}, [closeModal])
const languages = React.useMemo(() => {
const langs = LANGUAGES.filter(
@@ -30,23 +36,23 @@ export function Component({}: {}) {
// sort so that device & selected languages are on top, then alphabetically
langs.sort((a, b) => {
const hasA =
store.preferences.hasContentLanguage(a.code2) ||
langPrefs.contentLanguages.includes(a.code2) ||
deviceLocales.includes(a.code2)
const hasB =
store.preferences.hasContentLanguage(b.code2) ||
langPrefs.contentLanguages.includes(b.code2) ||
deviceLocales.includes(b.code2)
if (hasA === hasB) return a.name.localeCompare(b.name)
if (hasA) return -1
return 1
})
return langs
}, [store])
}, [langPrefs])
const onPress = React.useCallback(
(code2: string) => {
store.preferences.toggleContentLanguage(code2)
setLangPrefs.toggleContentLanguage(code2)
},
[store],
[setLangPrefs],
)
return (
@@ -3,7 +3,7 @@ import {StyleSheet} from 'react-native'
import {usePalette} from 'lib/hooks/usePalette'
import {observer} from 'mobx-react-lite'
import {ToggleButton} from 'view/com/util/forms/ToggleButton'
import {useStores} from 'state/index'
import {useLanguagePrefs, toPostLanguages} from '#/state/preferences/languages'
export const LanguageToggle = observer(function LanguageToggleImpl({
code2,
@@ -17,17 +17,17 @@ export const LanguageToggle = observer(function LanguageToggleImpl({
langType: 'contentLanguages' | 'postLanguages'
}) {
const pal = usePalette('default')
const store = useStores()
const langPrefs = useLanguagePrefs()
const isSelected = store.preferences[langType].includes(code2)
const values =
langType === 'contentLanguages'
? langPrefs.contentLanguages
: toPostLanguages(langPrefs.postLanguage)
const isSelected = values.includes(code2)
// enforce a max of 3 selections for post languages
let isDisabled = false
if (
langType === 'postLanguages' &&
store.preferences[langType].length >= 3 &&
!isSelected
) {
if (langType === 'postLanguages' && values.length >= 3 && !isSelected) {
isDisabled = true
}
@@ -2,7 +2,6 @@ import React from 'react'
import {StyleSheet, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import {ScrollView} from '../util'
import {useStores} from 'state/index'
import {Text} from '../../util/text/Text'
import {usePalette} from 'lib/hooks/usePalette'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
@@ -11,16 +10,24 @@ import {LANGUAGES, LANGUAGES_MAP_CODE2} from '../../../../locale/languages'
import {ConfirmLanguagesButton} from './ConfirmLanguagesButton'
import {ToggleButton} from 'view/com/util/forms/ToggleButton'
import {Trans} from '@lingui/macro'
import {useModalControls} from '#/state/modals'
import {
useLanguagePrefs,
useLanguagePrefsApi,
hasPostLanguage,
} from '#/state/preferences/languages'
export const snapPoints = ['100%']
export const Component = observer(function PostLanguagesSettingsImpl() {
const store = useStores()
const {closeModal} = useModalControls()
const langPrefs = useLanguagePrefs()
const setLangPrefs = useLanguagePrefsApi()
const pal = usePalette('default')
const {isMobile} = useWebMediaQueries()
const onPressDone = React.useCallback(() => {
store.shell.closeModal()
}, [store])
closeModal()
}, [closeModal])
const languages = React.useMemo(() => {
const langs = LANGUAGES.filter(
@@ -31,23 +38,23 @@ export const Component = observer(function PostLanguagesSettingsImpl() {
// sort so that device & selected languages are on top, then alphabetically
langs.sort((a, b) => {
const hasA =
store.preferences.hasPostLanguage(a.code2) ||
hasPostLanguage(langPrefs.postLanguage, a.code2) ||
deviceLocales.includes(a.code2)
const hasB =
store.preferences.hasPostLanguage(b.code2) ||
hasPostLanguage(langPrefs.postLanguage, b.code2) ||
deviceLocales.includes(b.code2)
if (hasA === hasB) return a.name.localeCompare(b.name)
if (hasA) return -1
return 1
})
return langs
}, [store])
}, [langPrefs])
const onPress = React.useCallback(
(code2: string) => {
store.preferences.togglePostLanguage(code2)
setLangPrefs.togglePostLanguage(code2)
},
[store],
[setLangPrefs],
)
return (
@@ -73,14 +80,11 @@ export const Component = observer(function PostLanguagesSettingsImpl() {
</Text>
<ScrollView style={styles.scrollContainer}>
{languages.map(lang => {
const isSelected = store.preferences.hasPostLanguage(lang.code2)
const isSelected = hasPostLanguage(langPrefs.postLanguage, lang.code2)
// enforce a max of 3 selections for post languages
let isDisabled = false
if (
store.preferences.postLanguage.split(',').length >= 3 &&
!isSelected
) {
if (langPrefs.postLanguage.split(',').length >= 3 && !isSelected) {
isDisabled = true
}
+4 -2
View File
@@ -16,6 +16,7 @@ import {ReportReasonOptions} from './ReasonOptions'
import {CollectionId} from './types'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
const DMCA_LINK = 'https://blueskyweb.xyz/support/copyright'
@@ -39,6 +40,7 @@ type ReportComponentProps =
export function Component(content: ReportComponentProps) {
const store = useStores()
const {closeModal} = useModalControls()
const pal = usePalette('default')
const {isMobile} = useWebMediaQueries()
const [isProcessing, setIsProcessing] = useState(false)
@@ -62,7 +64,7 @@ export function Component(content: ReportComponentProps) {
try {
if (issue === '__copyright__') {
Linking.openURL(DMCA_LINK)
store.shell.closeModal()
closeModal()
return
}
const $type = !isAccountReport
@@ -78,7 +80,7 @@ export function Component(content: ReportComponentProps) {
})
Toast.show("Thank you for your report! We'll look into it promptly.")
store.shell.closeModal()
closeModal()
return
} catch (e: any) {
setError(cleanError(e))
-114
View File
@@ -1,114 +0,0 @@
import React from 'react'
import {
FontAwesomeIcon,
FontAwesomeIconStyle,
} from '@fortawesome/react-native-fontawesome'
import {StyleSheet, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import {AppBskyActorDefs} from '@atproto/api'
import {UserAvatar} from '../util/UserAvatar'
import {Text} from '../util/text/Text'
import {Link, TextLink} from '../util/Link'
import {Button} from '../util/forms/Button'
import {FollowButton} from '../profile/FollowButton'
import {CenteredView} from '../util/Views.web'
import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette'
import {s} from 'lib/styles'
import {sanitizeDisplayName} from 'lib/strings/display-names'
import {makeProfileLink} from 'lib/routes/links'
export const InvitedUsers = observer(function InvitedUsersImpl() {
const store = useStores()
return (
<CenteredView>
{store.invitedUsers.profiles.map(profile => (
<InvitedUser key={profile.did} profile={profile} />
))}
</CenteredView>
)
})
function InvitedUser({
profile,
}: {
profile: AppBskyActorDefs.ProfileViewDetailed
}) {
const pal = usePalette('default')
const store = useStores()
const onPressDismiss = React.useCallback(() => {
store.invitedUsers.markSeen(profile.did)
}, [store, profile])
return (
<View
testID="invitedUser"
style={[
styles.layout,
{
backgroundColor: pal.colors.unreadNotifBg,
borderColor: pal.colors.unreadNotifBorder,
},
]}>
<View style={styles.layoutIcon}>
<FontAwesomeIcon
icon="user-plus"
size={24}
style={[styles.icon, s.blue3 as FontAwesomeIconStyle]}
/>
</View>
<View style={s.flex1}>
<Link href={makeProfileLink(profile)}>
<UserAvatar avatar={profile.avatar} size={35} />
</Link>
<Text style={[styles.desc, pal.text]}>
<TextLink
type="md-bold"
style={pal.text}
href={makeProfileLink(profile)}
text={sanitizeDisplayName(profile.displayName || profile.handle)}
/>{' '}
joined using your invite code!
</Text>
<View style={styles.btns}>
<FollowButton
unfollowedType="primary"
followedType="primary-light"
profile={profile}
/>
<Button
testID="dismissBtn"
type="primary-light"
label="Dismiss"
onPress={onPressDismiss}
/>
</View>
</View>
</View>
)
}
const styles = StyleSheet.create({
layout: {
flexDirection: 'row',
borderTopWidth: 1,
padding: 10,
},
layoutIcon: {
width: 70,
alignItems: 'flex-end',
paddingTop: 2,
},
icon: {
marginRight: 10,
marginTop: 4,
},
desc: {
paddingVertical: 6,
},
btns: {
flexDirection: 'row',
gap: 10,
},
})
+16 -11
View File
@@ -38,6 +38,8 @@ import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {MAX_POST_LINES} from 'lib/constants'
import {logger} from '#/logger'
import {Trans} from '@lingui/macro'
import {useMutedThreads, useToggleThreadMute} from '#/state/muted-threads'
import {useLanguagePrefs} from '#/state/preferences'
export const PostThreadItem = observer(function PostThreadItem({
item,
@@ -52,6 +54,9 @@ export const PostThreadItem = observer(function PostThreadItem({
}) {
const pal = usePalette('default')
const store = useStores()
const mutedThreads = useMutedThreads()
const toggleThreadMute = useToggleThreadMute()
const langPrefs = useLanguagePrefs()
const [deleted, setDeleted] = React.useState(false)
const [limitLines, setLimitLines] = React.useState(
countLines(item.richText?.text) >= MAX_POST_LINES,
@@ -83,15 +88,15 @@ export const PostThreadItem = observer(function PostThreadItem({
const translatorUrl = getTranslatorLink(
record?.text || '',
store.preferences.primaryLanguage,
langPrefs.primaryLanguage,
)
const needsTranslation = useMemo(
() =>
Boolean(
store.preferences.primaryLanguage &&
!isPostInLanguage(item.post, [store.preferences.primaryLanguage]),
langPrefs.primaryLanguage &&
!isPostInLanguage(item.post, [langPrefs.primaryLanguage]),
),
[item.post, store.preferences.primaryLanguage],
[item.post, langPrefs.primaryLanguage],
)
const onPressReply = React.useCallback(() => {
@@ -131,10 +136,10 @@ export const PostThreadItem = observer(function PostThreadItem({
Linking.openURL(translatorUrl)
}, [translatorUrl])
const onToggleThreadMute = React.useCallback(async () => {
const onToggleThreadMute = React.useCallback(() => {
try {
await item.toggleThreadMute()
if (item.isThreadMuted) {
const muted = toggleThreadMute(item.data.rootUri)
if (muted) {
Toast.show('You will no longer receive notifications for this thread')
} else {
Toast.show('You will now receive notifications for this thread')
@@ -142,7 +147,7 @@ export const PostThreadItem = observer(function PostThreadItem({
} catch (e) {
logger.error('Failed to toggle thread mute', {error: e})
}
}, [item])
}, [item, toggleThreadMute])
const onDeletePost = React.useCallback(() => {
item.delete().then(
@@ -287,7 +292,7 @@ export const PostThreadItem = observer(function PostThreadItem({
itemHref={itemHref}
itemTitle={itemTitle}
isAuthor={item.post.author.did === store.me.did}
isThreadMuted={item.isThreadMuted}
isThreadMuted={mutedThreads.includes(item.data.rootUri)}
onCopyPostText={onCopyPostText}
onOpenTranslate={onOpenTranslate}
onToggleThreadMute={onToggleThreadMute}
@@ -394,7 +399,7 @@ export const PostThreadItem = observer(function PostThreadItem({
isAuthor={item.post.author.did === store.me.did}
isReposted={!!item.post.viewer?.repost}
isLiked={!!item.post.viewer?.like}
isThreadMuted={item.isThreadMuted}
isThreadMuted={mutedThreads.includes(item.data.rootUri)}
onPressReply={onPressReply}
onPressToggleRepost={onPressToggleRepost}
onPressToggleLike={onPressToggleLike}
@@ -537,7 +542,7 @@ export const PostThreadItem = observer(function PostThreadItem({
likeCount={item.post.likeCount}
isReposted={!!item.post.viewer?.repost}
isLiked={!!item.post.viewer?.like}
isThreadMuted={item.isThreadMuted}
isThreadMuted={mutedThreads.includes(item.data.rootUri)}
onPressReply={onPressReply}
onPressToggleRepost={onPressToggleRepost}
onPressToggleLike={onPressToggleLike}
+11 -6
View File
@@ -33,6 +33,8 @@ import {makeProfileLink} from 'lib/routes/links'
import {MAX_POST_LINES} from 'lib/constants'
import {countLines} from 'lib/strings/helpers'
import {logger} from '#/logger'
import {useMutedThreads, useToggleThreadMute} from '#/state/muted-threads'
import {useLanguagePrefs} from '#/state/preferences'
export const Post = observer(function PostImpl({
view,
@@ -106,6 +108,9 @@ const PostLoaded = observer(function PostLoadedImpl({
}) {
const pal = usePalette('default')
const store = useStores()
const mutedThreads = useMutedThreads()
const toggleThreadMute = useToggleThreadMute()
const langPrefs = useLanguagePrefs()
const [limitLines, setLimitLines] = React.useState(
countLines(item.richText?.text) >= MAX_POST_LINES,
)
@@ -122,7 +127,7 @@ const PostLoaded = observer(function PostLoadedImpl({
const translatorUrl = getTranslatorLink(
record?.text || '',
store.preferences.primaryLanguage,
langPrefs.primaryLanguage,
)
const onPressReply = React.useCallback(() => {
@@ -161,10 +166,10 @@ const PostLoaded = observer(function PostLoadedImpl({
Linking.openURL(translatorUrl)
}, [translatorUrl])
const onToggleThreadMute = React.useCallback(async () => {
const onToggleThreadMute = React.useCallback(() => {
try {
await item.toggleThreadMute()
if (item.isThreadMuted) {
const muted = toggleThreadMute(item.data.rootUri)
if (muted) {
Toast.show('You will no longer receive notifications for this thread')
} else {
Toast.show('You will now receive notifications for this thread')
@@ -172,7 +177,7 @@ const PostLoaded = observer(function PostLoadedImpl({
} catch (e) {
logger.error('Failed to toggle thread mute', {error: e})
}
}, [item])
}, [item, toggleThreadMute])
const onDeletePost = React.useCallback(() => {
item.delete().then(
@@ -286,7 +291,7 @@ const PostLoaded = observer(function PostLoadedImpl({
likeCount={item.post.likeCount}
isReposted={!!item.post.viewer?.repost}
isLiked={!!item.post.viewer?.like}
isThreadMuted={item.isThreadMuted}
isThreadMuted={mutedThreads.includes(item.data.rootUri)}
onPressReply={onPressReply}
onPressToggleRepost={onPressToggleRepost}
onPressToggleLike={onPressToggleLike}
+5 -3
View File
@@ -11,6 +11,7 @@ import {useNavigation} from '@react-navigation/native'
import {NavigationProp} from 'lib/routes/types'
import {useStores} from 'state/index'
import {logger} from '#/logger'
import {useModalControls} from '#/state/modals'
const MESSAGES = {
[KnownError.Unknown]: '',
@@ -57,13 +58,14 @@ function FeedgenErrorMessage({
const msg = MESSAGES[knownError]
const uri = (feed.params as GetCustomFeed.QueryParams).feed
const [ownerDid] = safeParseFeedgenUri(uri)
const {openModal, closeModal} = useModalControls()
const onViewProfile = React.useCallback(() => {
navigation.navigate('Profile', {name: ownerDid})
}, [navigation, ownerDid])
const onRemoveFeed = React.useCallback(async () => {
store.shell.openModal({
openModal({
name: 'confirm',
title: 'Remove feed',
message: 'Remove this feed from your saved feeds?',
@@ -78,10 +80,10 @@ function FeedgenErrorMessage({
}
},
onPressCancel() {
store.shell.closeModal()
closeModal()
},
})
}, [store, uri])
}, [store, openModal, closeModal, uri])
return (
<View
+11 -6
View File
@@ -33,6 +33,8 @@ import {isEmbedByEmbedder} from 'lib/embeds'
import {MAX_POST_LINES} from 'lib/constants'
import {countLines} from 'lib/strings/helpers'
import {logger} from '#/logger'
import {useMutedThreads, useToggleThreadMute} from '#/state/muted-threads'
import {useLanguagePrefs} from '#/state/preferences'
export const FeedItem = observer(function FeedItemImpl({
item,
@@ -49,7 +51,10 @@ export const FeedItem = observer(function FeedItemImpl({
showReplyLine?: boolean
}) {
const store = useStores()
const langPrefs = useLanguagePrefs()
const pal = usePalette('default')
const mutedThreads = useMutedThreads()
const toggleThreadMute = useToggleThreadMute()
const {track} = useAnalytics()
const [deleted, setDeleted] = useState(false)
const [limitLines, setLimitLines] = useState(
@@ -72,7 +77,7 @@ export const FeedItem = observer(function FeedItemImpl({
}, [record?.reply])
const translatorUrl = getTranslatorLink(
record?.text || '',
store.preferences.primaryLanguage,
langPrefs.primaryLanguage,
)
const onPressReply = React.useCallback(() => {
@@ -114,11 +119,11 @@ export const FeedItem = observer(function FeedItemImpl({
Linking.openURL(translatorUrl)
}, [translatorUrl])
const onToggleThreadMute = React.useCallback(async () => {
const onToggleThreadMute = React.useCallback(() => {
track('FeedItem:ThreadMute')
try {
await item.toggleThreadMute()
if (item.isThreadMuted) {
const muted = toggleThreadMute(item.rootUri)
if (muted) {
Toast.show('You will no longer receive notifications for this thread')
} else {
Toast.show('You will now receive notifications for this thread')
@@ -126,7 +131,7 @@ export const FeedItem = observer(function FeedItemImpl({
} catch (e) {
logger.error('Failed to toggle thread mute', {error: e})
}
}, [track, item])
}, [track, toggleThreadMute, item])
const onDeletePost = React.useCallback(() => {
track('FeedItem:PostDelete')
@@ -360,7 +365,7 @@ export const FeedItem = observer(function FeedItemImpl({
likeCount={item.post.likeCount}
isReposted={!!item.post.viewer?.repost}
isLiked={!!item.post.viewer?.like}
isThreadMuted={item.isThreadMuted}
isThreadMuted={mutedThreads.includes(item.rootUri)}
onPressReply={onPressReply}
onPressToggleRepost={onPressToggleRepost}
onPressToggleLike={onPressToggleLike}
+12 -10
View File
@@ -42,6 +42,7 @@ import {ProfileHeaderSuggestedFollows} from './ProfileHeaderSuggestedFollows'
import {logger} from '#/logger'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
interface Props {
view: ProfileModel
@@ -116,6 +117,7 @@ const ProfileHeaderLoaded = observer(function ProfileHeaderLoadedImpl({
const palInverted = usePalette('inverted')
const store = useStores()
const {_} = useLingui()
const {openModal} = useModalControls()
const navigation = useNavigation<NavigationProp>()
const {track} = useAnalytics()
const invalidHandle = isInvalidHandle(view.handle)
@@ -160,12 +162,12 @@ const ProfileHeaderLoaded = observer(function ProfileHeaderLoadedImpl({
const onPressEditProfile = React.useCallback(() => {
track('ProfileHeader:EditProfileButtonClicked')
store.shell.openModal({
openModal({
name: 'edit-profile',
profileView: view,
onUpdate: onRefreshAll,
})
}, [track, store, view, onRefreshAll])
}, [track, openModal, view, onRefreshAll])
const trackPress = React.useCallback(
(f: 'Followers' | 'Follows') => {
@@ -184,12 +186,12 @@ const ProfileHeaderLoaded = observer(function ProfileHeaderLoadedImpl({
const onPressAddRemoveLists = React.useCallback(() => {
track('ProfileHeader:AddToListsButtonClicked')
store.shell.openModal({
openModal({
name: 'user-add-remove-lists',
subject: view.did,
displayName: view.displayName || view.handle,
})
}, [track, view, store])
}, [track, view, openModal])
const onPressMuteAccount = React.useCallback(async () => {
track('ProfileHeader:MuteAccountButtonClicked')
@@ -215,7 +217,7 @@ const ProfileHeaderLoaded = observer(function ProfileHeaderLoadedImpl({
const onPressBlockAccount = React.useCallback(async () => {
track('ProfileHeader:BlockAccountButtonClicked')
store.shell.openModal({
openModal({
name: 'confirm',
title: 'Block Account',
message:
@@ -231,11 +233,11 @@ const ProfileHeaderLoaded = observer(function ProfileHeaderLoadedImpl({
}
},
})
}, [track, view, store, onRefreshAll])
}, [track, view, openModal, onRefreshAll])
const onPressUnblockAccount = React.useCallback(async () => {
track('ProfileHeader:UnblockAccountButtonClicked')
store.shell.openModal({
openModal({
name: 'confirm',
title: 'Unblock Account',
message:
@@ -251,15 +253,15 @@ const ProfileHeaderLoaded = observer(function ProfileHeaderLoadedImpl({
}
},
})
}, [track, view, store, onRefreshAll])
}, [track, view, openModal, onRefreshAll])
const onPressReportAccount = React.useCallback(() => {
track('ProfileHeader:ReportAccountButtonClicked')
store.shell.openModal({
openModal({
name: 'report',
did: view.did,
})
}, [track, store, view])
}, [track, openModal, view])
const isMe = React.useMemo(
() => store.me.did === view.did,
+3 -1
View File
@@ -2,6 +2,7 @@ import React from 'react'
import {Pressable, View} from 'react-native'
import {useStores} from 'state/index'
import {navigate} from '../../../Navigation'
import {useModalControls} from '#/state/modals'
/**
* This utility component is only included in the test simulator
@@ -13,6 +14,7 @@ const BTN = {height: 1, width: 1, backgroundColor: 'red'}
export function TestCtrls() {
const store = useStores()
const {openModal} = useModalControls()
const onPressSignInAlice = async () => {
await store.session.login({
service: 'http://localhost:3000',
@@ -85,7 +87,7 @@ export function TestCtrls() {
/>
<Pressable
testID="e2eOpenInviteCodesModal"
onPress={() => store.shell.openModal({name: 'invite-codes'})}
onPress={() => openModal({name: 'invite-codes'})}
accessibilityRole="button"
style={BTN}
/>
+18 -10
View File
@@ -21,7 +21,6 @@ import {Text} from './text/Text'
import {TypographyVariant} from 'lib/ThemeContext'
import {NavigationProp} from 'lib/routes/types'
import {router} from '../../../routes'
import {useStores, RootStoreModel} from 'state/index'
import {
convertBskyAppUrlIfNeeded,
isExternalUrl,
@@ -31,6 +30,7 @@ import {isAndroid, isWeb} from 'platform/detection'
import {sanitizeUrl} from '@braintree/sanitize-url'
import {PressableWithHover} from './PressableWithHover'
import FixedTouchableHighlight from '../pager/FixedTouchableHighlight'
import {useModalControls} from '#/state/modals'
type Event =
| React.MouseEvent<HTMLAnchorElement, MouseEvent>
@@ -60,17 +60,17 @@ export const Link = memo(function Link({
anchorNoUnderline,
...props
}: Props) {
const store = useStores()
const {closeModal} = useModalControls()
const navigation = useNavigation<NavigationProp>()
const anchorHref = asAnchor ? sanitizeUrl(href) : undefined
const onPress = React.useCallback(
(e?: Event) => {
if (typeof href === 'string') {
return onPressInner(store, navigation, sanitizeUrl(href), e)
return onPressInner(closeModal, navigation, sanitizeUrl(href), e)
}
},
[store, navigation, href],
[closeModal, navigation, href],
)
if (noFeedback) {
@@ -160,8 +160,8 @@ export const TextLink = memo(function TextLink({
warnOnMismatchingLabel?: boolean
} & TextProps) {
const {...props} = useLinkProps({to: sanitizeUrl(href)})
const store = useStores()
const navigation = useNavigation<NavigationProp>()
const {openModal, closeModal} = useModalControls()
if (warnOnMismatchingLabel && typeof text !== 'string') {
console.error('Unable to detect mismatching label')
@@ -174,7 +174,7 @@ export const TextLink = memo(function TextLink({
linkRequiresWarning(href, typeof text === 'string' ? text : '')
if (requiresWarning) {
e?.preventDefault?.()
store.shell.openModal({
openModal({
name: 'link-warning',
text: typeof text === 'string' ? text : '',
href,
@@ -185,9 +185,17 @@ export const TextLink = memo(function TextLink({
// @ts-ignore function signature differs by platform -prf
return onPress()
}
return onPressInner(store, navigation, sanitizeUrl(href), e)
return onPressInner(closeModal, navigation, sanitizeUrl(href), e)
},
[onPress, store, navigation, href, text, warnOnMismatchingLabel],
[
onPress,
closeModal,
openModal,
navigation,
href,
text,
warnOnMismatchingLabel,
],
)
const hrefAttrs = useMemo(() => {
const isExternal = isExternalUrl(href)
@@ -285,7 +293,7 @@ export const TextLinkOnWebOnly = memo(function DesktopWebTextLink({
// needed customizations
// -prf
function onPressInner(
store: RootStoreModel,
closeModal = () => {},
navigation: NavigationProp,
href: string,
e?: Event,
@@ -318,7 +326,7 @@ function onPressInner(
if (newTab || href.startsWith('http') || href.startsWith('mailto')) {
Linking.openURL(href)
} else {
store.shell.closeModal() // close any active modals
closeModal() // close any active modals
// @ts-ignore we're not able to type check on this one -prf
navigation.dispatch(StackActions.push(...router.matchPath(href)))
+3 -3
View File
@@ -1,9 +1,9 @@
import React from 'react'
import {Pressable, StyleProp, ViewStyle} from 'react-native'
import {useStores} from 'state/index'
import {Link} from './Link'
import {isWeb} from 'platform/detection'
import {makeProfileLink} from 'lib/routes/links'
import {useModalControls} from '#/state/modals'
interface UserPreviewLinkProps {
did: string
@@ -13,7 +13,7 @@ interface UserPreviewLinkProps {
export function UserPreviewLink(
props: React.PropsWithChildren<UserPreviewLinkProps>,
) {
const store = useStores()
const {openModal} = useModalControls()
if (isWeb) {
return (
@@ -29,7 +29,7 @@ export function UserPreviewLink(
return (
<Pressable
onPress={() =>
store.shell.openModal({
openModal({
name: 'profile-preview',
did: props.did,
})
+4 -4
View File
@@ -2,7 +2,6 @@ import React from 'react'
import {StyleProp, View, ViewStyle} from 'react-native'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {toShareUrl} from 'lib/strings/url-helpers'
import {useStores} from 'state/index'
import {useTheme} from 'lib/ThemeContext'
import {shareUrl} from 'lib/sharing'
import {
@@ -12,6 +11,7 @@ import {
import {EventStopper} from '../EventStopper'
import {useLingui} from '@lingui/react'
import {msg} from '@lingui/macro'
import {useModalControls} from '#/state/modals'
export function PostDropdownBtn({
testID,
@@ -39,10 +39,10 @@ export function PostDropdownBtn({
onDeletePost: () => void
style?: StyleProp<ViewStyle>
}) {
const store = useStores()
const theme = useTheme()
const {_} = useLingui()
const defaultCtrlColor = theme.palette.default.postCtrl
const {openModal} = useModalControls()
const dropdownItems: NativeDropdownItem[] = [
{
@@ -111,7 +111,7 @@ export function PostDropdownBtn({
!isAuthor && {
label: 'Report post',
onPress() {
store.shell.openModal({
openModal({
name: 'report',
uri: itemUri,
cid: itemCid,
@@ -132,7 +132,7 @@ export function PostDropdownBtn({
isAuthor && {
label: 'Delete post',
onPress() {
store.shell.openModal({
openModal({
name: 'confirm',
title: 'Delete this post?',
message: 'Are you sure? This can not be undone.',
@@ -6,9 +6,9 @@ import {ModerationUI} from '@atproto/api'
import {Text} from '../text/Text'
import {ShieldExclamation} from 'lib/icons'
import {describeModerationCause} from 'lib/moderation'
import {useStores} from 'state/index'
import {useLingui} from '@lingui/react'
import {msg} from '@lingui/macro'
import {useModalControls} from '#/state/modals'
export function ContentHider({
testID,
@@ -24,11 +24,11 @@ export function ContentHider({
style?: StyleProp<ViewStyle>
childContainerStyle?: StyleProp<ViewStyle>
}>) {
const store = useStores()
const pal = usePalette('default')
const {_} = useLingui()
const {isMobile} = useWebMediaQueries()
const [override, setOverride] = React.useState(false)
const {openModal} = useModalControls()
if (!moderation.blur || (ignoreMute && moderation.cause?.type === 'muted')) {
return (
@@ -46,7 +46,7 @@ export function ContentHider({
if (!moderation.noOverride) {
setOverride(v => !v)
} else {
store.shell.openModal({
openModal({
name: 'moderation-details',
context: 'content',
moderation,
@@ -65,7 +65,7 @@ export function ContentHider({
]}>
<Pressable
onPress={() => {
store.shell.openModal({
openModal({
name: 'moderation-details',
context: 'content',
moderation,
+3 -3
View File
@@ -5,9 +5,9 @@ import {Text} from '../text/Text'
import {usePalette} from 'lib/hooks/usePalette'
import {ShieldExclamation} from 'lib/icons'
import {describeModerationCause} from 'lib/moderation'
import {useStores} from 'state/index'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export function PostAlerts({
moderation,
@@ -17,9 +17,9 @@ export function PostAlerts({
includeMute?: boolean
style?: StyleProp<ViewStyle>
}) {
const store = useStores()
const pal = usePalette('default')
const {_} = useLingui()
const {openModal} = useModalControls()
const shouldAlert = !!moderation.cause && moderation.alert
if (!shouldAlert) {
@@ -30,7 +30,7 @@ export function PostAlerts({
return (
<Pressable
onPress={() => {
store.shell.openModal({
openModal({
name: 'moderation-details',
context: 'content',
moderation,
+3 -3
View File
@@ -8,9 +8,9 @@ import {Text} from '../text/Text'
import {addStyle} from 'lib/styles'
import {describeModerationCause} from 'lib/moderation'
import {ShieldExclamation} from 'lib/icons'
import {useStores} from 'state/index'
import {useLingui} from '@lingui/react'
import {msg} from '@lingui/macro'
import {useModalControls} from '#/state/modals'
interface Props extends ComponentProps<typeof Link> {
// testID?: string
@@ -27,11 +27,11 @@ export function PostHider({
children,
...props
}: Props) {
const store = useStores()
const pal = usePalette('default')
const {_} = useLingui()
const {isMobile} = useWebMediaQueries()
const [override, setOverride] = React.useState(false)
const {openModal} = useModalControls()
if (!moderation.blur) {
return (
@@ -66,7 +66,7 @@ export function PostHider({
]}>
<Pressable
onPress={() => {
store.shell.openModal({
openModal({
name: 'moderation-details',
context: 'content',
moderation,
@@ -8,9 +8,9 @@ import {
describeModerationCause,
getProfileModerationCauses,
} from 'lib/moderation'
import {useStores} from 'state/index'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
export function ProfileHeaderAlerts({
moderation,
@@ -19,9 +19,9 @@ export function ProfileHeaderAlerts({
moderation: ProfileModeration
style?: StyleProp<ViewStyle>
}) {
const store = useStores()
const pal = usePalette('default')
const {_} = useLingui()
const {openModal} = useModalControls()
const causes = getProfileModerationCauses(moderation)
if (!causes.length) {
@@ -37,7 +37,7 @@ export function ProfileHeaderAlerts({
testID="profileHeaderAlert"
key={desc.name}
onPress={() => {
store.shell.openModal({
openModal({
name: 'moderation-details',
context: 'content',
moderation: {cause},
+7 -7
View File
@@ -18,9 +18,10 @@ import {NavigationProp} from 'lib/routes/types'
import {Text} from '../text/Text'
import {Button} from '../forms/Button'
import {describeModerationCause} from 'lib/moderation'
import {useStores} from 'state/index'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useModalControls} from '#/state/modals'
import {s} from '#/lib/styles'
export function ScreenHider({
testID,
@@ -36,13 +37,13 @@ export function ScreenHider({
style?: StyleProp<ViewStyle>
containerStyle?: StyleProp<ViewStyle>
}>) {
const store = useStores()
const pal = usePalette('default')
const palInverted = usePalette('inverted')
const {_} = useLingui()
const [override, setOverride] = React.useState(false)
const navigation = useNavigation<NavigationProp>()
const {isMobile} = useWebMediaQueries()
const {openModal} = useModalControls()
if (!moderation.blur || override) {
return (
@@ -68,14 +69,13 @@ export function ScreenHider({
<Trans>Content Warning</Trans>
</Text>
<Text type="2xl" style={[styles.description, pal.textLight]}>
<Trans>This {screenDescription} has been flagged: </Trans>
<Text type="2xl-medium" style={pal.text}>
{desc.name}
<Trans>This {screenDescription} has been flagged:</Trans>
<Text type="2xl-medium" style={[pal.text, s.ml5]}>
{desc.name}.
</Text>
.{' '}
<TouchableWithoutFeedback
onPress={() => {
store.shell.openModal({
openModal({
name: 'moderation-details',
context: 'account',
moderation,
+6 -3
View File
@@ -16,6 +16,7 @@ import {useStores} from 'state/index'
import {RepostButton} from './RepostButton'
import {Haptics} from 'lib/haptics'
import {HITSLOP_10, HITSLOP_20} from 'lib/constants'
import {useModalControls} from '#/state/modals'
interface PostCtrlsOpts {
itemUri: string
@@ -51,6 +52,7 @@ interface PostCtrlsOpts {
export function PostCtrls(opts: PostCtrlsOpts) {
const store = useStores()
const theme = useTheme()
const {closeModal} = useModalControls()
const defaultCtrlColor = React.useMemo(
() => ({
color: theme.palette.default.postCtrl,
@@ -58,17 +60,17 @@ export function PostCtrls(opts: PostCtrlsOpts) {
[theme],
) as StyleProp<ViewStyle>
const onRepost = useCallback(() => {
store.shell.closeModal()
closeModal()
if (!opts.isReposted) {
Haptics.default()
opts.onPressToggleRepost().catch(_e => undefined)
} else {
opts.onPressToggleRepost().catch(_e => undefined)
}
}, [opts, store.shell])
}, [opts, closeModal])
const onQuote = useCallback(() => {
store.shell.closeModal()
closeModal()
store.shell.openComposer({
quote: {
uri: opts.itemUri,
@@ -86,6 +88,7 @@ export function PostCtrls(opts: PostCtrlsOpts) {
opts.itemUri,
opts.text,
store.shell,
closeModal,
])
const onPressToggleLikeWrapper = async () => {
@@ -5,8 +5,8 @@ import {s, colors} from 'lib/styles'
import {useTheme} from 'lib/ThemeContext'
import {Text} from '../text/Text'
import {pluralize} from 'lib/strings/helpers'
import {useStores} from 'state/index'
import {HITSLOP_10, HITSLOP_20} from 'lib/constants'
import {useModalControls} from '#/state/modals'
interface Props {
isReposted: boolean
@@ -23,8 +23,8 @@ export const RepostButton = ({
onRepost,
onQuote,
}: Props) => {
const store = useStores()
const theme = useTheme()
const {openModal} = useModalControls()
const defaultControlColor = React.useMemo(
() => ({
@@ -34,13 +34,13 @@ export const RepostButton = ({
)
const onPressToggleRepostWrapper = useCallback(() => {
store.shell.openModal({
openModal({
name: 'repost',
onRepost: onRepost,
onQuote: onQuote,
isReposted,
})
}, [onRepost, onQuote, isReposted, store.shell])
}, [onRepost, onQuote, isReposted, openModal])
return (
<TouchableOpacity
+9 -6
View File
@@ -19,6 +19,8 @@ import {CenteredView} from 'view/com/util/Views'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useSetMinimalShellMode} from '#/state/shell'
import {useModalControls} from '#/state/modals'
import {useLanguagePrefs} from '#/state/preferences'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'AppPasswords'>
export const AppPasswords = withAuthRequired(
@@ -28,6 +30,7 @@ export const AppPasswords = withAuthRequired(
const setMinimalShellMode = useSetMinimalShellMode()
const {screen} = useAnalytics()
const {isTabletOrDesktop} = useWebMediaQueries()
const {openModal} = useModalControls()
useFocusEffect(
React.useCallback(() => {
@@ -37,8 +40,8 @@ export const AppPasswords = withAuthRequired(
)
const onAdd = React.useCallback(async () => {
store.shell.openModal({name: 'add-app-password'})
}, [store])
openModal({name: 'add-app-password'})
}, [openModal])
// no app passwords (empty) state
if (store.me.appPasswords.length === 0) {
@@ -168,9 +171,11 @@ function AppPassword({
const pal = usePalette('default')
const store = useStores()
const {_} = useLingui()
const {openModal} = useModalControls()
const {contentLanguages} = useLanguagePrefs()
const onDelete = React.useCallback(async () => {
store.shell.openModal({
openModal({
name: 'confirm',
title: 'Delete App Password',
message: `Are you sure you want to delete the app password "${name}"?`,
@@ -179,9 +184,7 @@ function AppPassword({
Toast.show('App password deleted')
},
})
}, [store, name])
const {contentLanguages} = store.preferences
}, [store, openModal, name])
const primaryLocale =
contentLanguages.length > 0 ? contentLanguages[0] : 'en-US'
+14 -9
View File
@@ -2,7 +2,6 @@ import React from 'react'
import {StyleSheet, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import {Text} from '../com/util/text/Text'
import {useStores} from 'state/index'
import {s} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
@@ -19,6 +18,8 @@ import {useFocusEffect} from '@react-navigation/native'
import {LANGUAGES} from 'lib/../locale/languages'
import RNPickerSelect, {PickerSelectProps} from 'react-native-picker-select'
import {useSetMinimalShellMode} from '#/state/shell'
import {useModalControls} from '#/state/modals'
import {useLanguagePrefs, useLanguagePrefsApi} from '#/state/preferences'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'LanguageSettings'>
@@ -26,10 +27,12 @@ export const LanguageSettingsScreen = observer(function LanguageSettingsImpl(
_: Props,
) {
const pal = usePalette('default')
const store = useStores()
const langPrefs = useLanguagePrefs()
const setLangPrefs = useLanguagePrefsApi()
const {isTabletOrDesktop} = useWebMediaQueries()
const {screen, track} = useAnalytics()
const setMinimalShellMode = useSetMinimalShellMode()
const {openModal} = useModalControls()
useFocusEffect(
React.useCallback(() => {
@@ -40,26 +43,28 @@ export const LanguageSettingsScreen = observer(function LanguageSettingsImpl(
const onPressContentLanguages = React.useCallback(() => {
track('Settings:ContentlanguagesButtonClicked')
store.shell.openModal({name: 'content-languages-settings'})
}, [track, store])
openModal({name: 'content-languages-settings'})
}, [track, openModal])
const onChangePrimaryLanguage = React.useCallback(
(value: Parameters<PickerSelectProps['onValueChange']>[0]) => {
store.preferences.setPrimaryLanguage(value)
if (langPrefs.primaryLanguage !== value) {
setLangPrefs.setPrimaryLanguage(value)
}
},
[store.preferences],
[langPrefs, setLangPrefs],
)
const myLanguages = React.useMemo(() => {
return (
store.preferences.contentLanguages
langPrefs.contentLanguages
.map(lang => LANGUAGES.find(l => l.code2 === lang))
.filter(Boolean)
// @ts-ignore
.map(l => l.name)
.join(', ')
)
}, [store.preferences.contentLanguages])
}, [langPrefs.contentLanguages])
return (
<CenteredView
@@ -82,7 +87,7 @@ export const LanguageSettingsScreen = observer(function LanguageSettingsImpl(
<View style={{position: 'relative'}}>
<RNPickerSelect
value={store.preferences.primaryLanguage}
value={langPrefs.primaryLanguage}
onValueChange={onChangePrimaryLanguage}
items={LANGUAGES.filter(l => Boolean(l.code2)).map(l => ({
label: l.name,
+4 -2
View File
@@ -17,6 +17,7 @@ import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {SimpleViewHeader} from 'view/com/util/SimpleViewHeader'
import {s} from 'lib/styles'
import {useSetMinimalShellMode} from '#/state/shell'
import {useModalControls} from '#/state/modals'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'Lists'>
export const ListsScreen = withAuthRequired(
@@ -26,6 +27,7 @@ export const ListsScreen = withAuthRequired(
const setMinimalShellMode = useSetMinimalShellMode()
const {isMobile} = useWebMediaQueries()
const navigation = useNavigation<NavigationProp>()
const {openModal} = useModalControls()
const listsLists: ListsListModel = React.useMemo(
() => new ListsListModel(store, 'my-curatelists'),
@@ -40,7 +42,7 @@ export const ListsScreen = withAuthRequired(
)
const onPressNewList = React.useCallback(() => {
store.shell.openModal({
openModal({
name: 'create-or-edit-list',
purpose: 'app.bsky.graph.defs#curatelist',
onSave: (uri: string) => {
@@ -53,7 +55,7 @@ export const ListsScreen = withAuthRequired(
} catch {}
},
})
}, [store, navigation])
}, [openModal, navigation])
return (
<View style={s.hContentRegion} testID="listsScreen">
+4 -4
View File
@@ -8,7 +8,6 @@ import {
import {observer} from 'mobx-react-lite'
import {NativeStackScreenProps, CommonNavigatorParams} from 'lib/routes/types'
import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {useStores} from 'state/index'
import {s} from 'lib/styles'
import {CenteredView} from '../com/util/Views'
import {ViewHeader} from '../com/util/ViewHeader'
@@ -18,15 +17,16 @@ import {usePalette} from 'lib/hooks/usePalette'
import {useAnalytics} from 'lib/analytics/analytics'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {useSetMinimalShellMode} from '#/state/shell'
import {useModalControls} from '#/state/modals'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'Moderation'>
export const ModerationScreen = withAuthRequired(
observer(function Moderation({}: Props) {
const pal = usePalette('default')
const store = useStores()
const setMinimalShellMode = useSetMinimalShellMode()
const {screen, track} = useAnalytics()
const {isTabletOrDesktop} = useWebMediaQueries()
const {openModal} = useModalControls()
useFocusEffect(
React.useCallback(() => {
@@ -37,8 +37,8 @@ export const ModerationScreen = withAuthRequired(
const onPressContentFiltering = React.useCallback(() => {
track('Moderation:ContentfilteringButtonClicked')
store.shell.openModal({name: 'content-filtering-settings'})
}, [track, store])
openModal({name: 'content-filtering-settings'})
}, [track, openModal])
return (
<CenteredView
+4 -2
View File
@@ -17,6 +17,7 @@ import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {SimpleViewHeader} from 'view/com/util/SimpleViewHeader'
import {s} from 'lib/styles'
import {useSetMinimalShellMode} from '#/state/shell'
import {useModalControls} from '#/state/modals'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'ModerationModlists'>
export const ModerationModlistsScreen = withAuthRequired(
@@ -26,6 +27,7 @@ export const ModerationModlistsScreen = withAuthRequired(
const setMinimalShellMode = useSetMinimalShellMode()
const {isMobile} = useWebMediaQueries()
const navigation = useNavigation<NavigationProp>()
const {openModal} = useModalControls()
const mutelists: ListsListModel = React.useMemo(
() => new ListsListModel(store, 'my-modlists'),
@@ -40,7 +42,7 @@ export const ModerationModlistsScreen = withAuthRequired(
)
const onPressNewList = React.useCallback(() => {
store.shell.openModal({
openModal({
name: 'create-or-edit-list',
purpose: 'app.bsky.graph.defs#modlist',
onSave: (uri: string) => {
@@ -53,7 +55,7 @@ export const ModerationModlistsScreen = withAuthRequired(
} catch {}
},
})
}, [store, navigation])
}, [openModal, navigation])
return (
<View style={s.hContentRegion} testID="moderationModlistsScreen">
-2
View File
@@ -10,7 +10,6 @@ import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {ViewHeader} from '../com/util/ViewHeader'
import {Feed} from '../com/notifications/Feed'
import {TextLink} from 'view/com/util/Link'
import {InvitedUsers} from '../com/notifications/InvitedUsers'
import {LoadLatestBtn} from 'view/com/util/load-latest/LoadLatestBtn'
import {useStores} from 'state/index'
import {useOnMainScroll} from 'lib/hooks/useOnMainScroll'
@@ -145,7 +144,6 @@ export const NotificationsScreen = withAuthRequired(
return (
<View testID="notificationsScreen" style={s.hContentRegion}>
<ViewHeader title="Notifications" canGoBack={false} />
<InvitedUsers />
<Feed
view={store.me.notifications}
onPressTryAgain={onPressTryAgain}

Some files were not shown because too many files have changed in this diff Show More