Merge remote-tracking branch 'origin/main' into eric/app-864-integrate-post-tags-into-app

* origin/main: (40 commits)
  1.52
  README: tweaks to high-level context (#1625)
  Fix stuck lightbox header after double tap (#1627)
  Fix: add padding to the spinner bottom while loading threads (#1626)
  Rewrite Android lightbox (#1624)
  Dont trim before posting (close #1621) (#1622)
  Only listen to back button on android (#1623)
  Improve typeahead search with inclusion of followed users (temporary solution) (#1612)
  Slightly smaller highlighted post text (#1608)
  Pull upstream bugfixes to bottom-sheet (#1606)
  Fix animations and gestures getting reset on state updates in the lightbox (#1618)
  Remove unused lightbox options (#1616)
  Profile UI tweaks (#1607)
  Fix invite codes flash on desktop, use loading placeholder (#1591)
  Update to react-native@0.72.5 (#1599)
  Fixed a typo on the onboarding recommended screen (#1604)
  Onboarding & feed fixes (#1602)
  Improve time to content in the search page (#1603)
  Fix a potential reference error in bottombarweb (#1600)
  Fix: only use scroll-positioning control on thread when looking at replies (#1587)
  ...
This commit is contained in:
Eric Bailey
2023-10-09 11:02:43 -05:00
108 changed files with 3705 additions and 2167 deletions
+86 -78
View File
@@ -6,7 +6,8 @@ import {ErrorBoundary} from 'view/com/util/ErrorBoundary'
import {s, colors} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {CenteredView} from '../util/Views'
import {isMobileWeb} from 'platform/detection'
import {isWeb} from 'platform/detection'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
export const SplashScreen = ({
onPressSignin,
@@ -16,6 +17,9 @@ export const SplashScreen = ({
onPressCreateAccount: () => void
}) => {
const pal = usePalette('default')
const {isTabletOrMobile} = useWebMediaQueries()
const styles = useStyles()
const isMobileWeb = isWeb && isTabletOrMobile
return (
<CenteredView style={[styles.container, pal.view]}>
@@ -55,13 +59,14 @@ export const SplashScreen = ({
</View>
</ErrorBoundary>
</View>
<Footer />
<Footer styles={styles} />
</CenteredView>
)
}
function Footer() {
function Footer({styles}: {styles: ReturnType<typeof useStyles>}) {
const pal = usePalette('default')
return (
<View style={[styles.footer, pal.view, pal.border]}>
<TextLink
@@ -82,78 +87,81 @@ function Footer() {
</View>
)
}
const styles = StyleSheet.create({
container: {
height: '100%',
},
containerInner: {
height: '100%',
justifyContent: 'center',
// @ts-ignore web only
paddingBottom: '20vh',
paddingHorizontal: 20,
},
containerInnerMobile: {
paddingBottom: 50,
},
title: {
textAlign: 'center',
color: colors.blue3,
fontSize: 68,
fontWeight: 'bold',
paddingBottom: 10,
},
titleMobile: {
textAlign: 'center',
color: colors.blue3,
fontSize: 58,
fontWeight: 'bold',
},
subtitle: {
textAlign: 'center',
color: colors.gray5,
fontSize: 52,
fontWeight: 'bold',
paddingBottom: 30,
},
subtitleMobile: {
textAlign: 'center',
color: colors.gray5,
fontSize: 42,
fontWeight: 'bold',
paddingBottom: 30,
},
btns: {
flexDirection: isMobileWeb ? 'column' : 'row',
gap: 20,
justifyContent: 'center',
paddingBottom: 40,
},
btn: {
borderRadius: 30,
paddingHorizontal: 24,
paddingVertical: 12,
minWidth: 220,
},
btnLabel: {
textAlign: 'center',
fontSize: 18,
},
notice: {
paddingHorizontal: 40,
textAlign: 'center',
},
footer: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
padding: 20,
borderTopWidth: 1,
flexDirection: 'row',
},
footerLink: {
marginRight: 20,
},
})
const useStyles = () => {
const {isTabletOrMobile} = useWebMediaQueries()
const isMobileWeb = isWeb && isTabletOrMobile
return StyleSheet.create({
container: {
height: '100%',
},
containerInner: {
height: '100%',
justifyContent: 'center',
// @ts-ignore web only
paddingBottom: '20vh',
paddingHorizontal: 20,
},
containerInnerMobile: {
paddingBottom: 50,
},
title: {
textAlign: 'center',
color: colors.blue3,
fontSize: 68,
fontWeight: 'bold',
paddingBottom: 10,
},
titleMobile: {
textAlign: 'center',
color: colors.blue3,
fontSize: 58,
fontWeight: 'bold',
},
subtitle: {
textAlign: 'center',
color: colors.gray5,
fontSize: 52,
fontWeight: 'bold',
paddingBottom: 30,
},
subtitleMobile: {
textAlign: 'center',
color: colors.gray5,
fontSize: 42,
fontWeight: 'bold',
paddingBottom: 30,
},
btns: {
flexDirection: isMobileWeb ? 'column' : 'row',
gap: 20,
justifyContent: 'center',
paddingBottom: 40,
},
btn: {
borderRadius: 30,
paddingHorizontal: 24,
paddingVertical: 12,
minWidth: 220,
},
btnLabel: {
textAlign: 'center',
fontSize: 18,
},
notice: {
paddingHorizontal: 40,
textAlign: 'center',
},
footer: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
padding: 20,
borderTopWidth: 1,
flexDirection: 'row',
},
footerLink: {
marginRight: 20,
},
})
}
@@ -65,7 +65,7 @@ export const RecommendedFeeds = observer(function RecommendedFeedsImpl({
tdStyles.title2,
isTabletOrMobile && tdStyles.title2Small,
]}>
Recomended
Recommended
</Text>
<Text
style={[
@@ -30,7 +30,6 @@ export const RecommendedFeedsItem = observer(function RecommendedFeedsItemImpl({
}
} else {
try {
await item.save()
await item.pin()
} catch (e) {
Toast.show('There was an issue contacting your server')
@@ -89,7 +89,7 @@ export const ProfileCard = observer(function ProfileCardImpl({
</View>
<FollowButton
did={profile.did}
profile={profile}
labelStyle={styles.followButton}
onToggleFollow={async isFollow => {
if (isFollow) {
+22 -5
View File
@@ -2,6 +2,7 @@ import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'
import {observer} from 'mobx-react-lite'
import {
ActivityIndicator,
BackHandler,
Keyboard,
KeyboardAvoidingView,
Platform,
@@ -51,14 +52,10 @@ import {EmojiPickerButton} from './text-input/web/EmojiPicker.web'
import {insertMentionAt} from 'lib/strings/mention-manip'
import {TagInput} from './TagInput'
type Props = ComposerOpts & {
onClose: () => void
}
type Props = ComposerOpts
export const ComposePost = observer(function ComposePost({
replyTo,
onPost,
onClose,
quote: initQuote,
mention: initMention,
}: Props) {
@@ -93,6 +90,9 @@ export const ComposePost = observer(function ComposePost({
const [suggestedLinks, setSuggestedLinks] = useState<Set<string>>(new Set())
const gallery = useMemo(() => new GalleryModel(store), [store])
const [tags, setTags] = useState<string[]>([])
const onClose = useCallback(() => {
store.shell.closeComposer()
}, [store])
const autocompleteView = useMemo<UserAutocompleteModel>(
() => new UserAutocompleteModel(store),
@@ -136,6 +136,23 @@ export const ComposePost = observer(function ComposePost({
onClose()
}
}, [store, onClose, graphemeLength, gallery])
// android back button
useEffect(() => {
if (!isAndroid) {
return
}
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
() => {
onPressCancel()
return true
},
)
return () => {
backHandler.remove()
}
}, [onPressCancel])
// initial setup
useEffect(() => {
@@ -7,11 +7,11 @@ import {
import {usePalette} from 'lib/hooks/usePalette'
import {useAnalytics} from 'lib/analytics/analytics'
import {useStores} from 'state/index'
import {isDesktopWeb} from 'platform/detection'
import {openCamera} from 'lib/media/picker'
import {useCameraPermission} from 'lib/hooks/usePermissions'
import {HITSLOP_10, POST_IMG_MAX} from 'lib/constants'
import {GalleryModel} from 'state/models/media/gallery'
import {isMobileWeb, isNative} from 'platform/detection'
type Props = {
gallery: GalleryModel
@@ -43,7 +43,8 @@ export function OpenCameraBtn({gallery}: Props) {
}
}, [gallery, track, store, requestCameraAccessIfNeeded])
if (isDesktopWeb) {
const shouldShowCameraButton = isNative || isMobileWeb
if (!shouldShowCameraButton) {
return null
}
@@ -6,10 +6,10 @@ import {
} from '@fortawesome/react-native-fontawesome'
import {usePalette} from 'lib/hooks/usePalette'
import {useAnalytics} from 'lib/analytics/analytics'
import {isDesktopWeb} from 'platform/detection'
import {usePhotoLibraryPermission} from 'lib/hooks/usePermissions'
import {GalleryModel} from 'state/models/media/gallery'
import {HITSLOP_10} from 'lib/constants'
import {isNative} from 'platform/detection'
type Props = {
gallery: GalleryModel
@@ -23,12 +23,12 @@ export function SelectPhotoBtn({gallery}: Props) {
const onPressSelectPhotos = useCallback(async () => {
track('Composer:GalleryOpened')
if (!isDesktopWeb && !(await requestPhotoAccessIfNeeded())) {
if (isNative && !(await requestPhotoAccessIfNeeded())) {
return
}
gallery.pick()
}, [track, gallery, requestPhotoAccessIfNeeded])
}, [track, requestPhotoAccessIfNeeded, gallery])
return (
<TouchableOpacity
@@ -132,7 +132,7 @@ export const TextInput = React.forwardRef(function TextInputImpl(
onUpdate({editor: editorProp}) {
const json = editorProp.getJSON()
const newRt = new RichText({text: editorJsonToText(json).trim()})
const newRt = new RichText({text: editorJsonToText(json).trimEnd()})
newRt.detectFacetsWithoutResolution()
setRichText(newRt)
@@ -1,157 +1,403 @@
/**
* Copyright (c) JOB TODAY S.A. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import React, {MutableRefObject, useState} from 'react'
import React, {useCallback, useRef, useState} from 'react'
import {
Animated,
ScrollView,
Dimensions,
StyleSheet,
NativeScrollEvent,
NativeSyntheticEvent,
NativeMethodsMixin,
} from 'react-native'
import {ActivityIndicator, Dimensions, StyleSheet} from 'react-native'
import {Image} from 'expo-image'
import Animated, {
measure,
runOnJS,
useAnimatedRef,
useAnimatedStyle,
useAnimatedReaction,
useSharedValue,
withDecay,
withSpring,
} from 'react-native-reanimated'
import {
GestureDetector,
Gesture,
GestureType,
} from 'react-native-gesture-handler'
import useImageDimensions from '../../hooks/useImageDimensions'
import usePanResponder from '../../hooks/usePanResponder'
import {
createTransform,
readTransform,
applyRounding,
prependPan,
prependPinch,
prependTransform,
TransformMatrix,
} from '../../transforms'
import type {ImageSource, Dimensions as ImageDimensions} from '../../@types'
import {getImageStyles, getImageTransform} from '../../utils'
import {ImageSource} from '../../@types'
import {ImageLoading} from './ImageLoading'
const SWIPE_CLOSE_OFFSET = 75
const SWIPE_CLOSE_VELOCITY = 1.75
const SCREEN = Dimensions.get('window')
const SCREEN_WIDTH = SCREEN.width
const SCREEN_HEIGHT = SCREEN.height
const MIN_DOUBLE_TAP_SCALE = 2
const MAX_ORIGINAL_IMAGE_ZOOM = 2
const AnimatedImage = Animated.createAnimatedComponent(Image)
const initialTransform = createTransform()
type Props = {
imageSrc: ImageSource
onRequestClose: () => void
onZoom: (isZoomed: boolean) => void
onLongPress: (image: ImageSource) => void
delayLongPress: number
swipeToCloseEnabled?: boolean
doubleTapToZoomEnabled?: boolean
pinchGestureRef: MutableRefObject<GestureType | undefined>
isScrollViewBeingDragged: boolean
}
const AnimatedImage = Animated.createAnimatedComponent(Image)
const ImageItem = ({
imageSrc,
onZoom,
onRequestClose,
onLongPress,
delayLongPress,
swipeToCloseEnabled = true,
doubleTapToZoomEnabled = true,
isScrollViewBeingDragged,
pinchGestureRef,
}: Props) => {
const imageContainer = useRef<ScrollView & NativeMethodsMixin>(null)
const [isScaled, setIsScaled] = useState(false)
const [isLoaded, setIsLoaded] = useState(false)
const imageDimensions = useImageDimensions(imageSrc)
const [translate, scale] = getImageTransform(imageDimensions, SCREEN)
const scrollValueY = new Animated.Value(0)
const [isLoaded, setLoadEnd] = useState(false)
const committedTransform = useSharedValue(initialTransform)
const panTranslation = useSharedValue({x: 0, y: 0})
const pinchOrigin = useSharedValue({x: 0, y: 0})
const pinchScale = useSharedValue(1)
const pinchTranslation = useSharedValue({x: 0, y: 0})
const dismissSwipeTranslateY = useSharedValue(0)
const containerRef = useAnimatedRef()
const onLoaded = useCallback(() => setLoadEnd(true), [])
const onZoomPerformed = useCallback(
(isZoomed: boolean) => {
onZoom(isZoomed)
if (imageContainer?.current) {
imageContainer.current.setNativeProps({
scrollEnabled: !isZoomed,
})
// Keep track of when we're entering or leaving scaled rendering.
// Note: DO NOT move any logic reading animated values outside this function.
useAnimatedReaction(
() => {
if (pinchScale.value !== 1) {
// We're currently pinching.
return true
}
const [, , committedScale] = readTransform(committedTransform.value)
if (committedScale !== 1) {
// We started from a pinched in state.
return true
}
// We're at rest.
return false
},
(nextIsScaled, prevIsScaled) => {
if (nextIsScaled !== prevIsScaled) {
runOnJS(handleZoom)(nextIsScaled)
}
},
[onZoom],
)
const onLongPressHandler = useCallback(() => {
onLongPress(imageSrc)
}, [imageSrc, onLongPress])
function handleZoom(nextIsScaled: boolean) {
setIsScaled(nextIsScaled)
onZoom(nextIsScaled)
}
const [panHandlers, scaleValue, translateValue] = usePanResponder({
initialScale: scale || 1,
initialTranslate: translate || {x: 0, y: 0},
onZoom: onZoomPerformed,
doubleTapToZoomEnabled,
onLongPress: onLongPressHandler,
delayLongPress,
})
const animatedStyle = useAnimatedStyle(() => {
// Apply the active adjustments on top of the committed transform before the gestures.
// This is matrix multiplication, so operations are applied in the reverse order.
let t = createTransform()
prependPan(t, panTranslation.value)
prependPinch(t, pinchScale.value, pinchOrigin.value, pinchTranslation.value)
prependTransform(t, committedTransform.value)
const [translateX, translateY, scale] = readTransform(t)
const imagesStyles = getImageStyles(
imageDimensions,
translateValue,
scaleValue,
)
const imageOpacity = scrollValueY.interpolate({
inputRange: [-SWIPE_CLOSE_OFFSET, 0, SWIPE_CLOSE_OFFSET],
outputRange: [0.7, 1, 0.7],
})
const imageStylesWithOpacity = {...imagesStyles, opacity: imageOpacity}
const onScrollEndDrag = ({
nativeEvent,
}: NativeSyntheticEvent<NativeScrollEvent>) => {
const velocityY = nativeEvent?.velocity?.y ?? 0
const offsetY = nativeEvent?.contentOffset?.y ?? 0
if (
(Math.abs(velocityY) > SWIPE_CLOSE_VELOCITY &&
offsetY > SWIPE_CLOSE_OFFSET) ||
offsetY > SCREEN_HEIGHT / 2
) {
onRequestClose()
const dismissDistance = dismissSwipeTranslateY.value
const dismissProgress = Math.min(
Math.abs(dismissDistance) / (SCREEN.height / 2),
1,
)
return {
opacity: 1 - dismissProgress,
transform: [
{translateX},
{translateY: translateY + dismissDistance},
{scale},
],
}
})
// On Android, stock apps prevent going "out of bounds" on pan or pinch. You should "bump" into edges.
// If the user tried to pan too hard, this function will provide the negative panning to stay in bounds.
function getExtraTranslationToStayInBounds(
candidateTransform: TransformMatrix,
) {
'worklet'
if (!imageDimensions) {
return [0, 0]
}
const [nextTranslateX, nextTranslateY, nextScale] =
readTransform(candidateTransform)
const scaledDimensions = getScaledDimensions(imageDimensions, nextScale)
const clampedTranslateX = clampTranslation(
nextTranslateX,
scaledDimensions.width,
SCREEN.width,
)
const clampedTranslateY = clampTranslation(
nextTranslateY,
scaledDimensions.height,
SCREEN.height,
)
const dx = clampedTranslateX - nextTranslateX
const dy = clampedTranslateY - nextTranslateY
return [dx, dy]
}
const onScroll = ({nativeEvent}: NativeSyntheticEvent<NativeScrollEvent>) => {
const offsetY = nativeEvent?.contentOffset?.y ?? 0
// This is a hack.
// We need to disallow any gestures (and let the native parent scroll view scroll) while you're scrolling it.
// However, there is no great reliable way to coordinate this yet in RGNH.
// This "fake" manual gesture handler whenever you're trying to touch something while the parent scrollview is not at rest.
const consumeHScroll = Gesture.Manual().onTouchesDown((e, manager) => {
if (isScrollViewBeingDragged) {
// Steal the gesture (and do nothing, so native ScrollView does its thing).
manager.activate()
return
}
const measurement = measure(containerRef)
if (!measurement || measurement.pageX !== 0) {
// Steal the gesture (and do nothing, so native ScrollView does its thing).
manager.activate()
return
}
// Fail this "fake" gesture so that the gestures after it can proceed.
manager.fail()
})
scrollValueY.setValue(offsetY)
}
const pinch = Gesture.Pinch()
.withRef(pinchGestureRef)
.onStart(e => {
pinchOrigin.value = {
x: e.focalX - SCREEN.width / 2,
y: e.focalY - SCREEN.height / 2,
}
})
.onChange(e => {
if (!imageDimensions) {
return
}
// Don't let the picture zoom in so close that it gets blurry.
// Also, like in stock Android apps, don't let the user zoom out further than 1:1.
const [, , committedScale] = readTransform(committedTransform.value)
const maxCommittedScale =
(imageDimensions.width / SCREEN.width) * MAX_ORIGINAL_IMAGE_ZOOM
const minPinchScale = 1 / committedScale
const maxPinchScale = maxCommittedScale / committedScale
const nextPinchScale = Math.min(
Math.max(minPinchScale, e.scale),
maxPinchScale,
)
pinchScale.value = nextPinchScale
// Zooming out close to the corner could push us out of bounds, which we don't want on Android.
// Calculate where we'll end up so we know how much to translate back to stay in bounds.
const t = createTransform()
prependPan(t, panTranslation.value)
prependPinch(t, nextPinchScale, pinchOrigin.value, pinchTranslation.value)
prependTransform(t, committedTransform.value)
const [dx, dy] = getExtraTranslationToStayInBounds(t)
if (dx !== 0 || dy !== 0) {
pinchTranslation.value = {
x: pinchTranslation.value.x + dx,
y: pinchTranslation.value.y + dy,
}
}
})
.onEnd(() => {
// Commit just the pinch.
let t = createTransform()
prependPinch(
t,
pinchScale.value,
pinchOrigin.value,
pinchTranslation.value,
)
prependTransform(t, committedTransform.value)
applyRounding(t)
committedTransform.value = t
// Reset just the pinch.
pinchScale.value = 1
pinchOrigin.value = {x: 0, y: 0}
pinchTranslation.value = {x: 0, y: 0}
})
const pan = Gesture.Pan()
.averageTouches(true)
// Unlike .enabled(isScaled), this ensures that an initial pinch can turn into a pan midway:
.minPointers(isScaled ? 1 : 2)
.onChange(e => {
if (!imageDimensions) {
return
}
const nextPanTranslation = {x: e.translationX, y: e.translationY}
let t = createTransform()
prependPan(t, nextPanTranslation)
prependPinch(
t,
pinchScale.value,
pinchOrigin.value,
pinchTranslation.value,
)
prependTransform(t, committedTransform.value)
// Prevent panning from going out of bounds.
const [dx, dy] = getExtraTranslationToStayInBounds(t)
nextPanTranslation.x += dx
nextPanTranslation.y += dy
panTranslation.value = nextPanTranslation
})
.onEnd(() => {
// Commit just the pan.
let t = createTransform()
prependPan(t, panTranslation.value)
prependTransform(t, committedTransform.value)
applyRounding(t)
committedTransform.value = t
// Reset just the pan.
panTranslation.value = {x: 0, y: 0}
})
const doubleTap = Gesture.Tap()
.numberOfTaps(2)
.onEnd(e => {
if (!imageDimensions) {
return
}
const [, , committedScale] = readTransform(committedTransform.value)
if (committedScale !== 1) {
// Go back to 1:1 using the identity vector.
let t = createTransform()
committedTransform.value = withClampedSpring(t)
return
}
// Try to zoom in so that we get rid of the black bars (whatever the orientation was).
const imageAspect = imageDimensions.width / imageDimensions.height
const screenAspect = SCREEN.width / SCREEN.height
const candidateScale = Math.max(
imageAspect / screenAspect,
screenAspect / imageAspect,
MIN_DOUBLE_TAP_SCALE,
)
// But don't zoom in so close that the picture gets blurry.
const maxScale =
(imageDimensions.width / SCREEN.width) * MAX_ORIGINAL_IMAGE_ZOOM
const scale = Math.min(candidateScale, maxScale)
// Calculate where we would be if the user pinched into the double tapped point.
// We won't use this transform directly because it may go out of bounds.
const candidateTransform = createTransform()
const origin = {
x: e.absoluteX - SCREEN.width / 2,
y: e.absoluteY - SCREEN.height / 2,
}
prependPinch(candidateTransform, scale, origin, {x: 0, y: 0})
// Now we know how much we went out of bounds, so we can shoot correctly.
const [dx, dy] = getExtraTranslationToStayInBounds(candidateTransform)
const finalTransform = createTransform()
prependPinch(finalTransform, scale, origin, {x: dx, y: dy})
committedTransform.value = withClampedSpring(finalTransform)
})
const dismissSwipePan = Gesture.Pan()
.enabled(!isScaled)
.activeOffsetY([-10, 10])
.failOffsetX([-10, 10])
.maxPointers(1)
.onUpdate(e => {
dismissSwipeTranslateY.value = e.translationY
})
.onEnd(e => {
if (Math.abs(e.velocityY) > 1000) {
dismissSwipeTranslateY.value = withDecay({velocity: e.velocityY})
runOnJS(onRequestClose)()
} else {
dismissSwipeTranslateY.value = withSpring(0, {
stiffness: 700,
damping: 50,
})
}
})
const isLoading = !isLoaded || !imageDimensions
return (
<ScrollView
ref={imageContainer}
style={styles.listItem}
pagingEnabled
nestedScrollEnabled
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
contentContainerStyle={styles.imageScrollContainer}
scrollEnabled={swipeToCloseEnabled}
{...(swipeToCloseEnabled && {
onScroll,
onScrollEndDrag,
})}>
<AnimatedImage
{...panHandlers}
source={imageSrc}
style={imageStylesWithOpacity}
onLoad={onLoaded}
accessibilityLabel={imageSrc.alt}
accessibilityHint=""
/>
{(!isLoaded || !imageDimensions) && <ImageLoading />}
</ScrollView>
<Animated.View ref={containerRef} style={styles.container}>
{isLoading && (
<ActivityIndicator size="small" color="#FFF" style={styles.loading} />
)}
<GestureDetector
gesture={Gesture.Exclusive(
consumeHScroll,
dismissSwipePan,
Gesture.Simultaneous(pinch, pan),
doubleTap,
)}>
<AnimatedImage
source={imageSrc}
contentFit="contain"
style={[styles.image, animatedStyle]}
accessibilityLabel={imageSrc.alt}
accessibilityHint=""
onLoad={() => setIsLoaded(true)}
/>
</GestureDetector>
</Animated.View>
)
}
const styles = StyleSheet.create({
listItem: {
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT,
container: {
width: SCREEN.width,
height: SCREEN.height,
overflow: 'hidden',
},
imageScrollContainer: {
height: SCREEN_HEIGHT * 2,
image: {
flex: 1,
},
loading: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
},
})
function getScaledDimensions(
imageDimensions: ImageDimensions,
scale: number,
): ImageDimensions {
'worklet'
const imageAspect = imageDimensions.width / imageDimensions.height
const screenAspect = SCREEN.width / SCREEN.height
const isLandscape = imageAspect > screenAspect
if (isLandscape) {
return {
width: scale * SCREEN.width,
height: (scale * SCREEN.width) / imageAspect,
}
} else {
return {
width: scale * SCREEN.height * imageAspect,
height: scale * SCREEN.height,
}
}
}
function clampTranslation(
value: number,
scaledSize: number,
screenSize: number,
): number {
'worklet'
// Figure out how much the user should be allowed to pan, and constrain the translation.
const panDistance = Math.max(0, (scaledSize - screenSize) / 2)
const clampedValue = Math.min(Math.max(-panDistance, value), panDistance)
return clampedValue
}
function withClampedSpring(value: any) {
'worklet'
return withSpring(value, {overshootClamping: true})
}
export default React.memo(ImageItem)
@@ -6,7 +6,7 @@
*
*/
import React, {useCallback, useRef, useState} from 'react'
import React, {MutableRefObject, useCallback, useRef, useState} from 'react'
import {
Animated,
@@ -16,71 +16,52 @@ import {
View,
NativeScrollEvent,
NativeSyntheticEvent,
NativeTouchEvent,
TouchableWithoutFeedback,
} from 'react-native'
import {Image} from 'expo-image'
import {GestureType} from 'react-native-gesture-handler'
import useDoubleTapToZoom from '../../hooks/useDoubleTapToZoom'
import useImageDimensions from '../../hooks/useImageDimensions'
import {getImageStyles, getImageTransform} from '../../utils'
import {ImageSource} from '../../@types'
import {ImageSource, Dimensions as ImageDimensions} from '../../@types'
import {ImageLoading} from './ImageLoading'
const DOUBLE_TAP_DELAY = 300
const SWIPE_CLOSE_OFFSET = 75
const SWIPE_CLOSE_VELOCITY = 1
const SCREEN = Dimensions.get('screen')
const SCREEN_WIDTH = SCREEN.width
const SCREEN_HEIGHT = SCREEN.height
const MIN_ZOOM = 2
const MAX_SCALE = 2
type Props = {
imageSrc: ImageSource
onRequestClose: () => void
onZoom: (scaled: boolean) => void
onLongPress: (image: ImageSource) => void
delayLongPress: number
swipeToCloseEnabled?: boolean
doubleTapToZoomEnabled?: boolean
pinchGestureRef: MutableRefObject<GestureType>
isScrollViewBeingDragged: boolean
}
const AnimatedImage = Animated.createAnimatedComponent(Image)
const ImageItem = ({
imageSrc,
onZoom,
onRequestClose,
onLongPress,
delayLongPress,
swipeToCloseEnabled = true,
doubleTapToZoomEnabled = true,
}: Props) => {
let lastTapTS: number | null = null
const ImageItem = ({imageSrc, onZoom, onRequestClose}: Props) => {
const scrollViewRef = useRef<ScrollView>(null)
const [loaded, setLoaded] = useState(false)
const [scaled, setScaled] = useState(false)
const imageDimensions = useImageDimensions(imageSrc)
const handleDoubleTap = useDoubleTapToZoom(
scrollViewRef,
scaled,
SCREEN,
imageDimensions,
)
const [translate, scale] = getImageTransform(imageDimensions, SCREEN)
const scrollValueY = new Animated.Value(0)
const scaleValue = new Animated.Value(scale || 1)
const translateValue = new Animated.ValueXY(translate)
const [scrollValueY] = useState(() => new Animated.Value(0))
const maxScrollViewZoom = MAX_SCALE / (scale || 1)
const imageOpacity = scrollValueY.interpolate({
inputRange: [-SWIPE_CLOSE_OFFSET, 0, SWIPE_CLOSE_OFFSET],
outputRange: [0.5, 1, 0.5],
})
const imagesStyles = getImageStyles(
imageDimensions,
translateValue,
scaleValue,
)
const imagesStyles = getImageStyles(imageDimensions, translate, scale || 1)
const imageStylesWithOpacity = {...imagesStyles, opacity: imageOpacity}
const onScrollEndDrag = useCallback(
@@ -91,15 +72,11 @@ const ImageItem = ({
onZoom(currentScaled)
setScaled(currentScaled)
if (
!currentScaled &&
swipeToCloseEnabled &&
Math.abs(velocityY) > SWIPE_CLOSE_VELOCITY
) {
if (!currentScaled && Math.abs(velocityY) > SWIPE_CLOSE_VELOCITY) {
onRequestClose()
}
},
[onRequestClose, onZoom, swipeToCloseEnabled],
[onRequestClose, onZoom],
)
const onScroll = ({nativeEvent}: NativeSyntheticEvent<NativeScrollEvent>) => {
@@ -112,9 +89,40 @@ const ImageItem = ({
scrollValueY.setValue(offsetY)
}
const onLongPressHandler = useCallback(() => {
onLongPress(imageSrc)
}, [imageSrc, onLongPress])
const handleDoubleTap = useCallback(
(event: NativeSyntheticEvent<NativeTouchEvent>) => {
const nowTS = new Date().getTime()
const scrollResponderRef = scrollViewRef?.current?.getScrollResponder()
if (lastTapTS && nowTS - lastTapTS < DOUBLE_TAP_DELAY) {
let nextZoomRect = {
x: 0,
y: 0,
width: SCREEN.width,
height: SCREEN.height,
}
const willZoom = !scaled
if (willZoom) {
const {pageX, pageY} = event.nativeEvent
nextZoomRect = getZoomRectAfterDoubleTap(
imageDimensions,
pageX,
pageY,
)
}
// @ts-ignore
scrollResponderRef?.scrollResponderZoomTo({
...nextZoomRect, // This rect is in screen coordinates
animated: true,
})
} else {
lastTapTS = nowTS
}
},
[imageDimensions, scaled],
)
return (
<View>
@@ -126,17 +134,13 @@ const ImageItem = ({
showsVerticalScrollIndicator={false}
maximumZoomScale={maxScrollViewZoom}
contentContainerStyle={styles.imageScrollContainer}
scrollEnabled={swipeToCloseEnabled}
scrollEnabled={true}
onScroll={onScroll}
onScrollEndDrag={onScrollEndDrag}
scrollEventThrottle={1}
{...(swipeToCloseEnabled && {
onScroll,
})}>
scrollEventThrottle={1}>
{(!loaded || !imageDimensions) && <ImageLoading />}
<TouchableWithoutFeedback
onPress={doubleTapToZoomEnabled ? handleDoubleTap : undefined}
onLongPress={onLongPressHandler}
delayLongPress={delayLongPress}
onPress={handleDoubleTap}
accessibilityRole="image"
accessibilityLabel={imageSrc.alt}
accessibilityHint="">
@@ -161,4 +165,149 @@ const styles = StyleSheet.create({
},
})
const getZoomRectAfterDoubleTap = (
imageDimensions: ImageDimensions | null,
touchX: number,
touchY: number,
): {
x: number
y: number
width: number
height: number
} => {
if (!imageDimensions) {
return {
x: 0,
y: 0,
width: SCREEN.width,
height: SCREEN.height,
}
}
// First, let's figure out how much we want to zoom in.
// We want to try to zoom in at least close enough to get rid of black bars.
const imageAspect = imageDimensions.width / imageDimensions.height
const screenAspect = SCREEN.width / SCREEN.height
const zoom = Math.max(
imageAspect / screenAspect,
screenAspect / imageAspect,
MIN_ZOOM,
)
// Unlike in the Android version, we don't constrain the *max* zoom level here.
// Instead, this is done in the ScrollView props so that it constraints pinch too.
// Next, we'll be calculating the rectangle to "zoom into" in screen coordinates.
// We already know the zoom level, so this gives us the rectangle size.
let rectWidth = SCREEN.width / zoom
let rectHeight = SCREEN.height / zoom
// Before we settle on the zoomed rect, figure out the safe area it has to be inside.
// We don't want to introduce new black bars or make existing black bars unbalanced.
let minX = 0
let minY = 0
let maxX = SCREEN.width - rectWidth
let maxY = SCREEN.height - rectHeight
if (imageAspect >= screenAspect) {
// The image has horizontal black bars. Exclude them from the safe area.
const renderedHeight = SCREEN.width / imageAspect
const horizontalBarHeight = (SCREEN.height - renderedHeight) / 2
minY += horizontalBarHeight
maxY -= horizontalBarHeight
} else {
// The image has vertical black bars. Exclude them from the safe area.
const renderedWidth = SCREEN.height * imageAspect
const verticalBarWidth = (SCREEN.width - renderedWidth) / 2
minX += verticalBarWidth
maxX -= verticalBarWidth
}
// Finally, we can position the rect according to its size and the safe area.
let rectX
if (maxX >= minX) {
// Content fills the screen horizontally so we have horizontal wiggle room.
// Try to keep the tapped point under the finger after zoom.
rectX = touchX - touchX / zoom
rectX = Math.min(rectX, maxX)
rectX = Math.max(rectX, minX)
} else {
// Keep the rect centered on the screen so that black bars are balanced.
rectX = SCREEN.width / 2 - rectWidth / 2
}
let rectY
if (maxY >= minY) {
// Content fills the screen vertically so we have vertical wiggle room.
// Try to keep the tapped point under the finger after zoom.
rectY = touchY - touchY / zoom
rectY = Math.min(rectY, maxY)
rectY = Math.max(rectY, minY)
} else {
// Keep the rect centered on the screen so that black bars are balanced.
rectY = SCREEN.height / 2 - rectHeight / 2
}
return {
x: rectX,
y: rectY,
height: rectHeight,
width: rectWidth,
}
}
const getImageStyles = (
image: ImageDimensions | null,
translate: {readonly x: number; readonly y: number} | undefined,
scale?: number,
) => {
if (!image?.width || !image?.height) {
return {width: 0, height: 0}
}
const transform = []
if (translate) {
transform.push({translateX: translate.x})
transform.push({translateY: translate.y})
}
if (scale) {
// @ts-ignore TODO - is scale incorrect? might need to remove -prf
transform.push({scale}, {perspective: new Animated.Value(1000)})
}
return {
width: image.width,
height: image.height,
transform,
}
}
const getImageTransform = (
image: ImageDimensions | null,
screen: ImageDimensions,
) => {
if (!image?.width || !image?.height) {
return [] as const
}
const wScale = screen.width / image.width
const hScale = screen.height / image.height
const scale = Math.min(wScale, hScale)
const {x, y} = getImageTranslate(image, screen)
return [{x, y}, scale] as const
}
const getImageTranslate = (
image: ImageDimensions,
screen: ImageDimensions,
): {x: number; y: number} => {
const getTranslateForAxis = (axis: 'x' | 'y'): number => {
const imageSize = axis === 'x' ? image.width : image.height
const screenSize = axis === 'x' ? screen.width : screen.height
return (screenSize - imageSize) / 2
}
return {
x: getTranslateForAxis('x'),
y: getTranslateForAxis('y'),
}
}
export default React.memo(ImageItem)
@@ -1,17 +1,16 @@
// default implementation fallback for web
import React from 'react'
import React, {MutableRefObject} from 'react'
import {View} from 'react-native'
import {GestureType} from 'react-native-gesture-handler'
import {ImageSource} from '../../@types'
type Props = {
imageSrc: ImageSource
onRequestClose: () => void
onZoom: (scaled: boolean) => void
onLongPress: (image: ImageSource) => void
delayLongPress: number
swipeToCloseEnabled?: boolean
doubleTapToZoomEnabled?: boolean
pinchGestureRef: MutableRefObject<GestureType | undefined>
isScrollViewBeingDragged: boolean
}
const ImageItem = (_props: Props) => {
@@ -1,47 +0,0 @@
/**
* Copyright (c) JOB TODAY S.A. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {Animated} from 'react-native'
const INITIAL_POSITION = {x: 0, y: 0}
const ANIMATION_CONFIG = {
duration: 200,
useNativeDriver: true,
}
const useAnimatedComponents = () => {
const headerTranslate = new Animated.ValueXY(INITIAL_POSITION)
const footerTranslate = new Animated.ValueXY(INITIAL_POSITION)
const toggleVisible = (isVisible: boolean) => {
if (isVisible) {
Animated.parallel([
Animated.timing(headerTranslate.y, {...ANIMATION_CONFIG, toValue: 0}),
Animated.timing(footerTranslate.y, {...ANIMATION_CONFIG, toValue: 0}),
]).start()
} else {
Animated.parallel([
Animated.timing(headerTranslate.y, {
...ANIMATION_CONFIG,
toValue: -300,
}),
Animated.timing(footerTranslate.y, {
...ANIMATION_CONFIG,
toValue: 300,
}),
]).start()
}
}
const headerTransform = headerTranslate.getTranslateTransform()
const footerTransform = footerTranslate.getTranslateTransform()
return [headerTransform, footerTransform, toggleVisible] as const
}
export default useAnimatedComponents
@@ -1,150 +0,0 @@
/**
* Copyright (c) JOB TODAY S.A. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import React, {useCallback} from 'react'
import {ScrollView, NativeTouchEvent, NativeSyntheticEvent} from 'react-native'
import {Dimensions} from '../@types'
const DOUBLE_TAP_DELAY = 300
const MIN_ZOOM = 2
let lastTapTS: number | null = null
/**
* This is iOS only.
* Same functionality for Android implemented inside usePanResponder hook.
*/
function useDoubleTapToZoom(
scrollViewRef: React.RefObject<ScrollView>,
scaled: boolean,
screen: Dimensions,
imageDimensions: Dimensions | null,
) {
const handleDoubleTap = useCallback(
(event: NativeSyntheticEvent<NativeTouchEvent>) => {
const nowTS = new Date().getTime()
const scrollResponderRef = scrollViewRef?.current?.getScrollResponder()
const getZoomRectAfterDoubleTap = (
touchX: number,
touchY: number,
): {
x: number
y: number
width: number
height: number
} => {
if (!imageDimensions) {
return {
x: 0,
y: 0,
width: screen.width,
height: screen.height,
}
}
// First, let's figure out how much we want to zoom in.
// We want to try to zoom in at least close enough to get rid of black bars.
const imageAspect = imageDimensions.width / imageDimensions.height
const screenAspect = screen.width / screen.height
const zoom = Math.max(
imageAspect / screenAspect,
screenAspect / imageAspect,
MIN_ZOOM,
)
// Unlike in the Android version, we don't constrain the *max* zoom level here.
// Instead, this is done in the ScrollView props so that it constraints pinch too.
// Next, we'll be calculating the rectangle to "zoom into" in screen coordinates.
// We already know the zoom level, so this gives us the rectangle size.
let rectWidth = screen.width / zoom
let rectHeight = screen.height / zoom
// Before we settle on the zoomed rect, figure out the safe area it has to be inside.
// We don't want to introduce new black bars or make existing black bars unbalanced.
let minX = 0
let minY = 0
let maxX = screen.width - rectWidth
let maxY = screen.height - rectHeight
if (imageAspect >= screenAspect) {
// The image has horizontal black bars. Exclude them from the safe area.
const renderedHeight = screen.width / imageAspect
const horizontalBarHeight = (screen.height - renderedHeight) / 2
minY += horizontalBarHeight
maxY -= horizontalBarHeight
} else {
// The image has vertical black bars. Exclude them from the safe area.
const renderedWidth = screen.height * imageAspect
const verticalBarWidth = (screen.width - renderedWidth) / 2
minX += verticalBarWidth
maxX -= verticalBarWidth
}
// Finally, we can position the rect according to its size and the safe area.
let rectX
if (maxX >= minX) {
// Content fills the screen horizontally so we have horizontal wiggle room.
// Try to keep the tapped point under the finger after zoom.
rectX = touchX - touchX / zoom
rectX = Math.min(rectX, maxX)
rectX = Math.max(rectX, minX)
} else {
// Keep the rect centered on the screen so that black bars are balanced.
rectX = screen.width / 2 - rectWidth / 2
}
let rectY
if (maxY >= minY) {
// Content fills the screen vertically so we have vertical wiggle room.
// Try to keep the tapped point under the finger after zoom.
rectY = touchY - touchY / zoom
rectY = Math.min(rectY, maxY)
rectY = Math.max(rectY, minY)
} else {
// Keep the rect centered on the screen so that black bars are balanced.
rectY = screen.height / 2 - rectHeight / 2
}
return {
x: rectX,
y: rectY,
height: rectHeight,
width: rectWidth,
}
}
if (lastTapTS && nowTS - lastTapTS < DOUBLE_TAP_DELAY) {
let nextZoomRect = {
x: 0,
y: 0,
width: screen.width,
height: screen.height,
}
const willZoom = !scaled
if (willZoom) {
const {pageX, pageY} = event.nativeEvent
nextZoomRect = getZoomRectAfterDoubleTap(pageX, pageY)
}
// @ts-ignore
scrollResponderRef?.scrollResponderZoomTo({
...nextZoomRect, // This rect is in screen coordinates
animated: true,
})
} else {
lastTapTS = nowTS
}
},
[imageDimensions, scaled, screen.height, screen.width, scrollViewRef],
)
return handleDoubleTap
}
export default useDoubleTapToZoom
@@ -8,11 +8,29 @@
import {useEffect, useState} from 'react'
import {Image, ImageURISource} from 'react-native'
import {createCache} from '../utils'
import {Dimensions, ImageSource} from '../@types'
const CACHE_SIZE = 50
type CacheStorageItem = {key: string; value: any}
const createCache = (cacheSize: number) => ({
_storage: [] as CacheStorageItem[],
get(key: string): any {
const {value} =
this._storage.find(({key: storageKey}) => storageKey === key) || {}
return value
},
set(key: string, value: any) {
if (this._storage.length >= cacheSize) {
this._storage.shift()
}
this._storage.push({key, value})
},
})
const imageDimensionsCache = createCache(CACHE_SIZE)
const useImageDimensions = (image: ImageSource): Dimensions | null => {
@@ -1,32 +0,0 @@
/**
* Copyright (c) JOB TODAY S.A. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {useState} from 'react'
import {NativeSyntheticEvent, NativeScrollEvent} from 'react-native'
import {Dimensions} from '../@types'
const useImageIndexChange = (imageIndex: number, screen: Dimensions) => {
const [currentImageIndex, setImageIndex] = useState(imageIndex)
const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
const {
nativeEvent: {
contentOffset: {x: scrollX},
},
} = event
if (screen.width) {
const nextIndex = Math.round(scrollX / screen.width)
setImageIndex(nextIndex < 0 ? 0 : nextIndex)
}
}
return [currentImageIndex, onScroll] as const
}
export default useImageIndexChange
@@ -1,25 +0,0 @@
/**
* Copyright (c) JOB TODAY S.A. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {useEffect} from 'react'
import {Image} from 'react-native'
import {ImageSource} from '../@types'
const useImagePrefetch = (images: ImageSource[]) => {
useEffect(() => {
images.forEach(image => {
//@ts-ignore
if (image.uri) {
//@ts-ignore
return Image.prefetch(image.uri)
}
})
}, [images])
}
export default useImagePrefetch
@@ -1,431 +0,0 @@
/**
* Copyright (c) JOB TODAY S.A. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {useEffect} from 'react'
import {
Animated,
Dimensions,
GestureResponderEvent,
GestureResponderHandlers,
NativeTouchEvent,
PanResponder,
PanResponderGestureState,
} from 'react-native'
import {Position} from '../@types'
import {
getDistanceBetweenTouches,
getImageTranslate,
getImageDimensionsByTranslate,
} from '../utils'
const SCREEN = Dimensions.get('window')
const SCREEN_WIDTH = SCREEN.width
const SCREEN_HEIGHT = SCREEN.height
const MIN_DIMENSION = Math.min(SCREEN_WIDTH, SCREEN_HEIGHT)
const ANDROID_BAR_HEIGHT = 24
const MIN_ZOOM = 2
const MAX_SCALE = 2
const DOUBLE_TAP_DELAY = 300
const OUT_BOUND_MULTIPLIER = 0.75
type Props = {
initialScale: number
initialTranslate: Position
onZoom: (isZoomed: boolean) => void
doubleTapToZoomEnabled: boolean
onLongPress: () => void
delayLongPress: number
}
const usePanResponder = ({
initialScale,
initialTranslate,
onZoom,
doubleTapToZoomEnabled,
onLongPress,
delayLongPress,
}: Props): Readonly<
[GestureResponderHandlers, Animated.Value, Animated.ValueXY]
> => {
let numberInitialTouches = 1
let initialTouches: NativeTouchEvent[] = []
let currentScale = initialScale
let currentTranslate = initialTranslate
let tmpScale = 0
let tmpTranslate: Position | null = null
let isDoubleTapPerformed = false
let lastTapTS: number | null = null
let longPressHandlerRef: NodeJS.Timeout | null = null
const meaningfulShift = MIN_DIMENSION * 0.01
const scaleValue = new Animated.Value(initialScale)
const translateValue = new Animated.ValueXY(initialTranslate)
const imageDimensions = getImageDimensionsByTranslate(
initialTranslate,
SCREEN,
)
const getBounds = (scale: number) => {
const scaledImageDimensions = {
width: imageDimensions.width * scale,
height: imageDimensions.height * scale,
}
const translateDelta = getImageTranslate(scaledImageDimensions, SCREEN)
const left = initialTranslate.x - translateDelta.x
const right = left - (scaledImageDimensions.width - SCREEN.width)
const top = initialTranslate.y - translateDelta.y
const bottom = top - (scaledImageDimensions.height - SCREEN.height)
return [top, left, bottom, right]
}
const getTransformAfterDoubleTap = (
touchX: number,
touchY: number,
): [number, Position] => {
let nextScale = initialScale
let nextTranslateX = initialTranslate.x
let nextTranslateY = initialTranslate.y
// First, let's figure out how much we want to zoom in.
// We want to try to zoom in at least close enough to get rid of black bars.
const imageAspect = imageDimensions.width / imageDimensions.height
const screenAspect = SCREEN.width / SCREEN.height
let zoom = Math.max(
imageAspect / screenAspect,
screenAspect / imageAspect,
MIN_ZOOM,
)
// Don't zoom so hard that the original image's pixels become blurry.
zoom = Math.min(zoom, MAX_SCALE / initialScale)
nextScale = initialScale * zoom
// Next, let's see if we need to adjust the scaled image translation.
// Ideally, we want the tapped point to stay under the finger after the scaling.
const dx = SCREEN.width / 2 - touchX
const dy = SCREEN.height / 2 - (touchY - ANDROID_BAR_HEIGHT)
// Before we try to adjust the translation, check how much wiggle room we have.
// We don't want to introduce new black bars or make existing black bars unbalanced.
const [topBound, leftBound, bottomBound, rightBound] = getBounds(nextScale)
if (leftBound > rightBound) {
// Content fills the screen horizontally so we have horizontal wiggle room.
// Try to keep the tapped point under the finger after zoom.
nextTranslateX += dx * zoom - dx
nextTranslateX = Math.min(nextTranslateX, leftBound)
nextTranslateX = Math.max(nextTranslateX, rightBound)
}
if (topBound > bottomBound) {
// Content fills the screen vertically so we have vertical wiggle room.
// Try to keep the tapped point under the finger after zoom.
nextTranslateY += dy * zoom - dy
nextTranslateY = Math.min(nextTranslateY, topBound)
nextTranslateY = Math.max(nextTranslateY, bottomBound)
}
return [
nextScale,
{
x: nextTranslateX,
y: nextTranslateY,
},
]
}
const fitsScreenByWidth = () =>
imageDimensions.width * currentScale < SCREEN_WIDTH
const fitsScreenByHeight = () =>
imageDimensions.height * currentScale < SCREEN_HEIGHT
useEffect(() => {
scaleValue.addListener(({value}) => {
if (typeof onZoom === 'function') {
onZoom(value !== initialScale)
}
})
return () => scaleValue.removeAllListeners()
})
const cancelLongPressHandle = () => {
longPressHandlerRef && clearTimeout(longPressHandlerRef)
}
const panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onStartShouldSetPanResponderCapture: () => true,
onMoveShouldSetPanResponder: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (
_: GestureResponderEvent,
gestureState: PanResponderGestureState,
) => {
numberInitialTouches = gestureState.numberActiveTouches
if (gestureState.numberActiveTouches > 1) {
return
}
longPressHandlerRef = setTimeout(onLongPress, delayLongPress)
},
onPanResponderStart: (
event: GestureResponderEvent,
gestureState: PanResponderGestureState,
) => {
initialTouches = event.nativeEvent.touches
numberInitialTouches = gestureState.numberActiveTouches
if (gestureState.numberActiveTouches > 1) {
return
}
const tapTS = Date.now()
// Handle double tap event by calculating diff between first and second taps timestamps
isDoubleTapPerformed = Boolean(
lastTapTS && tapTS - lastTapTS < DOUBLE_TAP_DELAY,
)
if (doubleTapToZoomEnabled && isDoubleTapPerformed) {
let nextScale = initialScale
let nextTranslate = initialTranslate
const willZoom = currentScale === initialScale
if (willZoom) {
const {pageX: touchX, pageY: touchY} = event.nativeEvent.touches[0]
;[nextScale, nextTranslate] = getTransformAfterDoubleTap(
touchX,
touchY,
)
}
onZoom(willZoom)
Animated.parallel(
[
Animated.timing(translateValue.x, {
toValue: nextTranslate.x,
duration: 300,
useNativeDriver: true,
}),
Animated.timing(translateValue.y, {
toValue: nextTranslate.y,
duration: 300,
useNativeDriver: true,
}),
Animated.timing(scaleValue, {
toValue: nextScale,
duration: 300,
useNativeDriver: true,
}),
],
{stopTogether: false},
).start(() => {
currentScale = nextScale
currentTranslate = nextTranslate
})
lastTapTS = null
} else {
lastTapTS = Date.now()
}
},
onPanResponderMove: (
event: GestureResponderEvent,
gestureState: PanResponderGestureState,
) => {
const {dx, dy} = gestureState
if (Math.abs(dx) >= meaningfulShift || Math.abs(dy) >= meaningfulShift) {
cancelLongPressHandle()
}
// Don't need to handle move because double tap in progress (was handled in onStart)
if (doubleTapToZoomEnabled && isDoubleTapPerformed) {
cancelLongPressHandle()
return
}
if (
numberInitialTouches === 1 &&
gestureState.numberActiveTouches === 2
) {
numberInitialTouches = 2
initialTouches = event.nativeEvent.touches
}
const isTapGesture =
numberInitialTouches === 1 && gestureState.numberActiveTouches === 1
const isPinchGesture =
numberInitialTouches === 2 && gestureState.numberActiveTouches === 2
if (isPinchGesture) {
cancelLongPressHandle()
const initialDistance = getDistanceBetweenTouches(initialTouches)
const currentDistance = getDistanceBetweenTouches(
event.nativeEvent.touches,
)
let nextScale = (currentDistance / initialDistance) * currentScale
/**
* In case image is scaling smaller than initial size ->
* slow down this transition by applying OUT_BOUND_MULTIPLIER
*/
if (nextScale < initialScale) {
nextScale =
nextScale + (initialScale - nextScale) * OUT_BOUND_MULTIPLIER
}
/**
* In case image is scaling down -> move it in direction of initial position
*/
if (currentScale > initialScale && currentScale > nextScale) {
const k = (currentScale - initialScale) / (currentScale - nextScale)
const nextTranslateX =
nextScale < initialScale
? initialTranslate.x
: currentTranslate.x -
(currentTranslate.x - initialTranslate.x) / k
const nextTranslateY =
nextScale < initialScale
? initialTranslate.y
: currentTranslate.y -
(currentTranslate.y - initialTranslate.y) / k
translateValue.x.setValue(nextTranslateX)
translateValue.y.setValue(nextTranslateY)
tmpTranslate = {x: nextTranslateX, y: nextTranslateY}
}
scaleValue.setValue(nextScale)
tmpScale = nextScale
}
if (isTapGesture && currentScale > initialScale) {
const {x, y} = currentTranslate
// eslint-disable-next-line @typescript-eslint/no-shadow
const {dx, dy} = gestureState
const [topBound, leftBound, bottomBound, rightBound] =
getBounds(currentScale)
let nextTranslateX = x + dx
let nextTranslateY = y + dy
if (nextTranslateX > leftBound) {
nextTranslateX =
nextTranslateX - (nextTranslateX - leftBound) * OUT_BOUND_MULTIPLIER
}
if (nextTranslateX < rightBound) {
nextTranslateX =
nextTranslateX -
(nextTranslateX - rightBound) * OUT_BOUND_MULTIPLIER
}
if (nextTranslateY > topBound) {
nextTranslateY =
nextTranslateY - (nextTranslateY - topBound) * OUT_BOUND_MULTIPLIER
}
if (nextTranslateY < bottomBound) {
nextTranslateY =
nextTranslateY -
(nextTranslateY - bottomBound) * OUT_BOUND_MULTIPLIER
}
if (fitsScreenByWidth()) {
nextTranslateX = x
}
if (fitsScreenByHeight()) {
nextTranslateY = y
}
translateValue.x.setValue(nextTranslateX)
translateValue.y.setValue(nextTranslateY)
tmpTranslate = {x: nextTranslateX, y: nextTranslateY}
}
},
onPanResponderRelease: () => {
cancelLongPressHandle()
if (isDoubleTapPerformed) {
isDoubleTapPerformed = false
}
if (tmpScale > 0) {
if (tmpScale < initialScale || tmpScale > MAX_SCALE) {
tmpScale = tmpScale < initialScale ? initialScale : MAX_SCALE
Animated.timing(scaleValue, {
toValue: tmpScale,
duration: 100,
useNativeDriver: true,
}).start()
}
currentScale = tmpScale
tmpScale = 0
}
if (tmpTranslate) {
const {x, y} = tmpTranslate
const [topBound, leftBound, bottomBound, rightBound] =
getBounds(currentScale)
let nextTranslateX = x
let nextTranslateY = y
if (!fitsScreenByWidth()) {
if (nextTranslateX > leftBound) {
nextTranslateX = leftBound
} else if (nextTranslateX < rightBound) {
nextTranslateX = rightBound
}
}
if (!fitsScreenByHeight()) {
if (nextTranslateY > topBound) {
nextTranslateY = topBound
} else if (nextTranslateY < bottomBound) {
nextTranslateY = bottomBound
}
}
Animated.parallel([
Animated.timing(translateValue.x, {
toValue: nextTranslateX,
duration: 100,
useNativeDriver: true,
}),
Animated.timing(translateValue.y, {
toValue: nextTranslateY,
duration: 100,
useNativeDriver: true,
}),
]).start()
currentTranslate = {x: nextTranslateX, y: nextTranslateY}
tmpTranslate = null
}
},
onPanResponderTerminationRequest: () => false,
onShouldBlockNativeResponder: () => false,
})
return [panResponder.panHandlers, scaleValue, translateValue]
}
export default usePanResponder
@@ -1,24 +0,0 @@
/**
* Copyright (c) JOB TODAY S.A. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {useState} from 'react'
const useRequestClose = (onRequestClose: () => void) => {
const [opacity, setOpacity] = useState(1)
return [
opacity,
() => {
setOpacity(0)
onRequestClose()
setTimeout(() => setOpacity(1), 0)
},
] as const
}
export default useRequestClose
+95 -38
View File
@@ -10,14 +10,17 @@
import React, {
ComponentType,
createRef,
useCallback,
useRef,
useEffect,
useMemo,
useState,
} from 'react'
import {
Animated,
Dimensions,
NativeSyntheticEvent,
NativeScrollEvent,
StyleSheet,
View,
VirtualizedList,
@@ -29,10 +32,8 @@ import {ModalsContainer} from '../../modals/Modal'
import ImageItem from './components/ImageItem/ImageItem'
import ImageDefaultHeader from './components/ImageDefaultHeader'
import useAnimatedComponents from './hooks/useAnimatedComponents'
import useImageIndexChange from './hooks/useImageIndexChange'
import useRequestClose from './hooks/useRequestClose'
import {ImageSource} from './@types'
import {ScrollView, GestureType} from 'react-native-gesture-handler'
import {Edge, SafeAreaView} from 'react-native-safe-area-context'
type Props = {
@@ -41,22 +42,21 @@ type Props = {
imageIndex: number
visible: boolean
onRequestClose: () => void
onLongPress?: (image: ImageSource) => void
onImageIndexChange?: (imageIndex: number) => void
presentationStyle?: ModalProps['presentationStyle']
animationType?: ModalProps['animationType']
backgroundColor?: string
swipeToCloseEnabled?: boolean
doubleTapToZoomEnabled?: boolean
delayLongPress?: number
HeaderComponent?: ComponentType<{imageIndex: number}>
FooterComponent?: ComponentType<{imageIndex: number}>
}
const DEFAULT_BG_COLOR = '#000'
const DEFAULT_DELAY_LONG_PRESS = 800
const SCREEN = Dimensions.get('screen')
const SCREEN_WIDTH = SCREEN.width
const INITIAL_POSITION = {x: 0, y: 0}
const ANIMATION_CONFIG = {
duration: 200,
useNativeDriver: true,
}
function ImageViewing({
images,
@@ -64,35 +64,65 @@ function ImageViewing({
imageIndex,
visible,
onRequestClose,
onLongPress = () => {},
onImageIndexChange,
backgroundColor = DEFAULT_BG_COLOR,
swipeToCloseEnabled,
doubleTapToZoomEnabled,
delayLongPress = DEFAULT_DELAY_LONG_PRESS,
HeaderComponent,
FooterComponent,
}: Props) {
const imageList = useRef<VirtualizedList<ImageSource>>(null)
const [opacity, onRequestCloseEnhanced] = useRequestClose(onRequestClose)
const [currentImageIndex, onScroll] = useImageIndexChange(imageIndex, SCREEN)
const [headerTransform, footerTransform, toggleBarsVisible] =
useAnimatedComponents()
useEffect(() => {
if (onImageIndexChange) {
onImageIndexChange(currentImageIndex)
}
}, [currentImageIndex, onImageIndexChange])
const onZoom = useCallback(
(isScaled: boolean) => {
// @ts-ignore
imageList?.current?.setNativeProps({scrollEnabled: !isScaled})
toggleBarsVisible(!isScaled)
},
[toggleBarsVisible],
const [isScaled, setIsScaled] = useState(false)
const [isDragging, setIsDragging] = useState(false)
const [opacity, setOpacity] = useState(1)
const [currentImageIndex, setImageIndex] = useState(imageIndex)
const [headerTranslate] = useState(
() => new Animated.ValueXY(INITIAL_POSITION),
)
const [footerTranslate] = useState(
() => new Animated.ValueXY(INITIAL_POSITION),
)
const toggleBarsVisible = (isVisible: boolean) => {
if (isVisible) {
Animated.parallel([
Animated.timing(headerTranslate.y, {...ANIMATION_CONFIG, toValue: 0}),
Animated.timing(footerTranslate.y, {...ANIMATION_CONFIG, toValue: 0}),
]).start()
} else {
Animated.parallel([
Animated.timing(headerTranslate.y, {
...ANIMATION_CONFIG,
toValue: -300,
}),
Animated.timing(footerTranslate.y, {
...ANIMATION_CONFIG,
toValue: 300,
}),
]).start()
}
}
const onRequestCloseEnhanced = () => {
setOpacity(0)
onRequestClose()
setTimeout(() => setOpacity(1), 0)
}
const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
const {
nativeEvent: {
contentOffset: {x: scrollX},
},
} = event
if (SCREEN.width) {
const nextIndex = Math.round(scrollX / SCREEN.width)
setImageIndex(nextIndex < 0 ? 0 : nextIndex)
}
}
const onZoom = (nextIsScaled: boolean) => {
toggleBarsVisible(!nextIsScaled)
setIsScaled(false)
}
const edges = useMemo(() => {
if (Platform.OS === 'android') {
@@ -107,10 +137,23 @@ function ImageViewing({
}
}, [imageList, imageIndex])
// This is a hack.
// RNGH doesn't have an easy way to express that pinch of individual items
// should "steal" all pinches from the scroll view. So we're keeping a ref
// to all pinch gestures so that we may give them to <ScrollView waitFor={...}>.
const [pinchGestureRefs] = useState(new Map())
for (let imageSrc of images) {
if (!pinchGestureRefs.get(imageSrc)) {
pinchGestureRefs.set(imageSrc, createRef<GestureType | undefined>())
}
}
if (!visible) {
return null
}
const headerTransform = headerTranslate.getTranslateTransform()
const footerTransform = footerTranslate.getTranslateTransform()
return (
<SafeAreaView
style={styles.screen}
@@ -134,6 +177,7 @@ function ImageViewing({
data={images}
horizontal
pagingEnabled
scrollEnabled={!isScaled || isDragging}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
getItem={(_, index) => images[index]}
@@ -148,13 +192,26 @@ function ImageViewing({
onZoom={onZoom}
imageSrc={imageSrc}
onRequestClose={onRequestCloseEnhanced}
onLongPress={onLongPress}
delayLongPress={delayLongPress}
swipeToCloseEnabled={swipeToCloseEnabled}
doubleTapToZoomEnabled={doubleTapToZoomEnabled}
pinchGestureRef={pinchGestureRefs.get(imageSrc)}
isScrollViewBeingDragged={isDragging}
/>
)}
onMomentumScrollEnd={onScroll}
renderScrollComponent={props => (
<ScrollView
{...props}
waitFor={Array.from(pinchGestureRefs.values())}
/>
)}
onScrollBeginDrag={() => {
setIsDragging(true)
}}
onScrollEndDrag={() => {
setIsDragging(false)
}}
onMomentumScrollEnd={e => {
setIsScaled(false)
onScroll(e)
}}
//@ts-ignore
keyExtractor={(imageSrc, index) =>
keyExtractor
@@ -0,0 +1,98 @@
import type {Position} from './@types'
export type TransformMatrix = [
number,
number,
number,
number,
number,
number,
number,
number,
number,
]
// These are affine transforms. See explanation of every cell here:
// https://en.wikipedia.org/wiki/Transformation_matrix#/media/File:2D_affine_transformation_matrix.svg
export function createTransform(): TransformMatrix {
'worklet'
return [1, 0, 0, 0, 1, 0, 0, 0, 1]
}
export function applyRounding(t: TransformMatrix) {
'worklet'
t[2] = Math.round(t[2])
t[5] = Math.round(t[5])
// For example: 0.985, 0.99, 0.995, then 1:
t[0] = Math.round(t[0] * 200) / 200
t[4] = Math.round(t[0] * 200) / 200
}
// We're using a limited subset (always scaling and translating while keeping aspect ratio) so
// we can assume the transform doesn't encode have skew, rotation, or non-uniform stretching.
// All write operations are applied in-place to avoid unnecessary allocations.
export function readTransform(t: TransformMatrix): [number, number, number] {
'worklet'
const scale = t[0]
const translateX = t[2]
const translateY = t[5]
return [translateX, translateY, scale]
}
export function prependTranslate(t: TransformMatrix, x: number, y: number) {
'worklet'
t[2] += t[0] * x + t[1] * y
t[5] += t[3] * x + t[4] * y
}
export function prependScale(t: TransformMatrix, value: number) {
'worklet'
t[0] *= value
t[1] *= value
t[3] *= value
t[4] *= value
}
export function prependTransform(ta: TransformMatrix, tb: TransformMatrix) {
'worklet'
// In-place matrix multiplication.
const a00 = ta[0],
a01 = ta[1],
a02 = ta[2]
const a10 = ta[3],
a11 = ta[4],
a12 = ta[5]
const a20 = ta[6],
a21 = ta[7],
a22 = ta[8]
ta[0] = a00 * tb[0] + a01 * tb[3] + a02 * tb[6]
ta[1] = a00 * tb[1] + a01 * tb[4] + a02 * tb[7]
ta[2] = a00 * tb[2] + a01 * tb[5] + a02 * tb[8]
ta[3] = a10 * tb[0] + a11 * tb[3] + a12 * tb[6]
ta[4] = a10 * tb[1] + a11 * tb[4] + a12 * tb[7]
ta[5] = a10 * tb[2] + a11 * tb[5] + a12 * tb[8]
ta[6] = a20 * tb[0] + a21 * tb[3] + a22 * tb[6]
ta[7] = a20 * tb[1] + a21 * tb[4] + a22 * tb[7]
ta[8] = a20 * tb[2] + a21 * tb[5] + a22 * tb[8]
}
export function prependPan(t: TransformMatrix, translation: Position) {
'worklet'
prependTranslate(t, translation.x, translation.y)
}
export function prependPinch(
t: TransformMatrix,
scale: number,
origin: Position,
translation: Position,
) {
'worklet'
prependTranslate(t, translation.x, translation.y)
prependTranslate(t, origin.x, origin.y)
prependScale(t, scale)
prependTranslate(t, -origin.x, -origin.y)
}
-139
View File
@@ -1,139 +0,0 @@
/**
* Copyright (c) JOB TODAY S.A. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import {Animated, NativeTouchEvent} from 'react-native'
import {Dimensions, Position} from './@types'
type CacheStorageItem = {key: string; value: any}
export const createCache = (cacheSize: number) => ({
_storage: [] as CacheStorageItem[],
get(key: string): any {
const {value} =
this._storage.find(({key: storageKey}) => storageKey === key) || {}
return value
},
set(key: string, value: any) {
if (this._storage.length >= cacheSize) {
this._storage.shift()
}
this._storage.push({key, value})
},
})
export const splitArrayIntoBatches = (arr: any[], batchSize: number): any[] =>
arr.reduce((result, item) => {
const batch = result.pop() || []
if (batch.length < batchSize) {
batch.push(item)
result.push(batch)
} else {
result.push(batch, [item])
}
return result
}, [])
export const getImageTransform = (
image: Dimensions | null,
screen: Dimensions,
) => {
if (!image?.width || !image?.height) {
return [] as const
}
const wScale = screen.width / image.width
const hScale = screen.height / image.height
const scale = Math.min(wScale, hScale)
const {x, y} = getImageTranslate(image, screen)
return [{x, y}, scale] as const
}
export const getImageStyles = (
image: Dimensions | null,
translate: Animated.ValueXY,
scale?: Animated.Value,
) => {
if (!image?.width || !image?.height) {
return {width: 0, height: 0}
}
const transform = translate.getTranslateTransform()
if (scale) {
// @ts-ignore TODO - is scale incorrect? might need to remove -prf
transform.push({scale}, {perspective: new Animated.Value(1000)})
}
return {
width: image.width,
height: image.height,
transform,
}
}
export const getImageTranslate = (
image: Dimensions,
screen: Dimensions,
): Position => {
const getTranslateForAxis = (axis: 'x' | 'y'): number => {
const imageSize = axis === 'x' ? image.width : image.height
const screenSize = axis === 'x' ? screen.width : screen.height
return (screenSize - imageSize) / 2
}
return {
x: getTranslateForAxis('x'),
y: getTranslateForAxis('y'),
}
}
export const getImageDimensionsByTranslate = (
translate: Position,
screen: Dimensions,
): Dimensions => ({
width: screen.width - translate.x * 2,
height: screen.height - translate.y * 2,
})
export const getImageTranslateForScale = (
currentTranslate: Position,
targetScale: number,
screen: Dimensions,
): Position => {
const {width, height} = getImageDimensionsByTranslate(
currentTranslate,
screen,
)
const targetImageDimensions = {
width: width * targetScale,
height: height * targetScale,
}
return getImageTranslate(targetImageDimensions, screen)
}
export const getDistanceBetweenTouches = (
touches: NativeTouchEvent[],
): number => {
const [a, b] = touches
if (a == null || b == null) {
return 0
}
return Math.sqrt(
Math.pow(a.pageX - b.pageX, 2) + Math.pow(a.pageY - b.pageY, 2),
)
}
+86 -84
View File
@@ -15,94 +15,10 @@ import * as MediaLibrary from 'expo-media-library'
export const Lightbox = observer(function Lightbox() {
const store = useStores()
const [isAltExpanded, setAltExpanded] = React.useState(false)
const [permissionResponse, requestPermission] = MediaLibrary.usePermissions()
const onClose = React.useCallback(() => {
store.shell.closeLightbox()
}, [store])
const saveImageToAlbumWithToasts = React.useCallback(
async (uri: string) => {
if (!permissionResponse || permissionResponse.granted === false) {
Toast.show('Permission to access camera roll is required.')
if (permissionResponse?.canAskAgain) {
requestPermission()
} else {
Toast.show(
'Permission to access camera roll was denied. Please enable it in your system settings.',
)
}
return
}
try {
await saveImageToMediaLibrary({uri})
Toast.show('Saved to your camera roll.')
} catch (e: any) {
Toast.show(`Failed to save image: ${String(e)}`)
}
},
[permissionResponse, requestPermission],
)
const LightboxFooter = React.useCallback(
({imageIndex}: {imageIndex: number}) => {
const lightbox = store.shell.activeLightbox
if (!lightbox) {
return null
}
let altText = ''
let uri = ''
if (lightbox.name === 'images') {
const opts = lightbox as models.ImagesLightbox
uri = opts.images[imageIndex].uri
altText = opts.images[imageIndex].alt || ''
} else if (lightbox.name === 'profile-image') {
const opts = lightbox as models.ProfileImageLightbox
uri = opts.profileView.avatar || ''
}
return (
<View style={[styles.footer]}>
{altText ? (
<Pressable
onPress={() => setAltExpanded(!isAltExpanded)}
accessibilityRole="button">
<Text
style={[s.gray3, styles.footerText]}
numberOfLines={isAltExpanded ? undefined : 3}>
{altText}
</Text>
</Pressable>
) : null}
<View style={styles.footerBtns}>
<Button
type="primary-outline"
style={styles.footerBtn}
onPress={() => saveImageToAlbumWithToasts(uri)}>
<FontAwesomeIcon icon={['far', 'floppy-disk']} style={s.white} />
<Text type="xl" style={s.white}>
Save
</Text>
</Button>
<Button
type="primary-outline"
style={styles.footerBtn}
onPress={() => shareImageModal({uri})}>
<FontAwesomeIcon icon="arrow-up-from-bracket" style={s.white} />
<Text type="xl" style={s.white}>
Share
</Text>
</Button>
</View>
</View>
)
},
[store.shell.activeLightbox, isAltExpanded, saveImageToAlbumWithToasts],
)
if (!store.shell.activeLightbox) {
return null
} else if (store.shell.activeLightbox.name === 'profile-image') {
@@ -132,6 +48,92 @@ export const Lightbox = observer(function Lightbox() {
}
})
const LightboxFooter = observer(function LightboxFooter({
imageIndex,
}: {
imageIndex: number
}) {
const store = useStores()
const [isAltExpanded, setAltExpanded] = React.useState(false)
const [permissionResponse, requestPermission] = MediaLibrary.usePermissions()
const saveImageToAlbumWithToasts = React.useCallback(
async (uri: string) => {
if (!permissionResponse || permissionResponse.granted === false) {
Toast.show('Permission to access camera roll is required.')
if (permissionResponse?.canAskAgain) {
requestPermission()
} else {
Toast.show(
'Permission to access camera roll was denied. Please enable it in your system settings.',
)
}
return
}
try {
await saveImageToMediaLibrary({uri})
Toast.show('Saved to your camera roll.')
} catch (e: any) {
Toast.show(`Failed to save image: ${String(e)}`)
}
},
[permissionResponse, requestPermission],
)
const lightbox = store.shell.activeLightbox
if (!lightbox) {
return null
}
let altText = ''
let uri = ''
if (lightbox.name === 'images') {
const opts = lightbox as models.ImagesLightbox
uri = opts.images[imageIndex].uri
altText = opts.images[imageIndex].alt || ''
} else if (lightbox.name === 'profile-image') {
const opts = lightbox as models.ProfileImageLightbox
uri = opts.profileView.avatar || ''
}
return (
<View style={[styles.footer]}>
{altText ? (
<Pressable
onPress={() => setAltExpanded(!isAltExpanded)}
accessibilityRole="button">
<Text
style={[s.gray3, styles.footerText]}
numberOfLines={isAltExpanded ? undefined : 3}>
{altText}
</Text>
</Pressable>
) : null}
<View style={styles.footerBtns}>
<Button
type="primary-outline"
style={styles.footerBtn}
onPress={() => saveImageToAlbumWithToasts(uri)}>
<FontAwesomeIcon icon={['far', 'floppy-disk']} style={s.white} />
<Text type="xl" style={s.white}>
Save
</Text>
</Button>
<Button
type="primary-outline"
style={styles.footerBtn}
onPress={() => shareImageModal({uri})}>
<FontAwesomeIcon icon="arrow-up-from-bracket" style={s.white} />
<Text type="xl" style={s.white}>
Share
</Text>
</Button>
</View>
</View>
)
})
const styles = StyleSheet.create({
footer: {
paddingTop: 16,
-1
View File
@@ -145,7 +145,6 @@ function LightboxInner({
{imgs[index].alt ? (
<View style={styles.footer}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Expand alt text"
accessibilityHint="If alt text is long, toggles alt text expanded state"
onPress={() => {
+280
View File
@@ -0,0 +1,280 @@
import React, {useState} from 'react'
import {
ActivityIndicator,
KeyboardAvoidingView,
SafeAreaView,
StyleSheet,
View,
} from 'react-native'
import {ScrollView, TextInput} from './util'
import {observer} from 'mobx-react-lite'
import {Text} from '../util/text/Text'
import {Button} from '../util/forms/Button'
import {ErrorMessage} from '../util/error/ErrorMessage'
import * as Toast from '../util/Toast'
import {useStores} from 'state/index'
import {s, colors} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {isWeb} from 'platform/detection'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {cleanError} from 'lib/strings/errors'
enum Stages {
InputEmail,
ConfirmCode,
Done,
}
export const snapPoints = ['90%']
export const Component = observer(function Component({}: {}) {
const pal = usePalette('default')
const store = useStores()
const [stage, setStage] = useState<Stages>(Stages.InputEmail)
const [email, setEmail] = useState<string>(
store.session.currentSession?.email || '',
)
const [confirmationCode, setConfirmationCode] = useState<string>('')
const [isProcessing, setIsProcessing] = useState<boolean>(false)
const [error, setError] = useState<string>('')
const {isMobile} = useWebMediaQueries()
const onRequestChange = async () => {
if (email === store.session.currentSession?.email) {
setError('Enter your new email above')
return
}
setError('')
setIsProcessing(true)
try {
const res = await store.agent.com.atproto.server.requestEmailUpdate()
if (res.data.tokenRequired) {
setStage(Stages.ConfirmCode)
} else {
await store.agent.com.atproto.server.updateEmail({email: email.trim()})
store.session.updateLocalAccountData({
email: email.trim(),
emailConfirmed: false,
})
Toast.show('Email updated')
setStage(Stages.Done)
}
} catch (e) {
let err = cleanError(String(e))
// TEMP
// while rollout is occuring, we're giving a temporary error message
// you can remove this any time after Oct2023
// -prf
if (err === 'email must be confirmed (temporary)') {
err = `Please confirm your email before changing it. This is a temporary requirement while email-updating tools are added, and it will soon be removed.`
}
setError(err)
} finally {
setIsProcessing(false)
}
}
const onConfirm = async () => {
setError('')
setIsProcessing(true)
try {
await store.agent.com.atproto.server.updateEmail({
email: email.trim(),
token: confirmationCode.trim(),
})
store.session.updateLocalAccountData({
email: email.trim(),
emailConfirmed: false,
})
Toast.show('Email updated')
setStage(Stages.Done)
} catch (e) {
setError(cleanError(String(e)))
} finally {
setIsProcessing(false)
}
}
const onVerify = async () => {
store.shell.closeModal()
store.shell.openModal({name: 'verify-email'})
}
return (
<KeyboardAvoidingView
behavior="padding"
style={[pal.view, styles.container]}>
<SafeAreaView style={s.flex1}>
<ScrollView
testID="changeEmailModal"
style={[s.flex1, isMobile && {paddingHorizontal: 18}]}>
<View style={styles.titleSection}>
<Text type="title-lg" style={[pal.text, styles.title]}>
{stage === Stages.InputEmail ? 'Change Your Email' : ''}
{stage === Stages.ConfirmCode ? 'Security Step Required' : ''}
{stage === Stages.Done ? 'Email Updated' : ''}
</Text>
</View>
<Text type="lg" style={[pal.textLight, {marginBottom: 10}]}>
{stage === Stages.InputEmail ? (
<>Enter your new email address below.</>
) : stage === Stages.ConfirmCode ? (
<>
An email has been sent to your previous address,{' '}
{store.session.currentSession?.email || ''}. It includes a
confirmation code which you can enter below.
</>
) : (
<>
Your email has been updated but not verified. As a next step,
please verify your new email.
</>
)}
</Text>
{stage === Stages.InputEmail && (
<TextInput
testID="emailInput"
style={[styles.textInput, pal.border, pal.text]}
placeholder="alice@mail.com"
placeholderTextColor={pal.colors.textLight}
value={email}
onChangeText={setEmail}
accessible={true}
accessibilityLabel="Email"
accessibilityHint=""
autoCapitalize="none"
autoComplete="email"
autoCorrect={false}
/>
)}
{stage === Stages.ConfirmCode && (
<TextInput
testID="confirmCodeInput"
style={[styles.textInput, pal.border, pal.text]}
placeholder="XXXXX-XXXXX"
placeholderTextColor={pal.colors.textLight}
value={confirmationCode}
onChangeText={setConfirmationCode}
accessible={true}
accessibilityLabel="Confirmation code"
accessibilityHint=""
autoCapitalize="none"
autoComplete="off"
autoCorrect={false}
/>
)}
{error ? (
<ErrorMessage message={error} style={styles.error} />
) : undefined}
<View style={[styles.btnContainer]}>
{isProcessing ? (
<View style={styles.btn}>
<ActivityIndicator color="#fff" />
</View>
) : (
<View style={{gap: 6}}>
{stage === Stages.InputEmail && (
<Button
testID="requestChangeBtn"
type="primary"
onPress={onRequestChange}
accessibilityLabel="Request Change"
accessibilityHint=""
label="Request Change"
labelContainerStyle={{justifyContent: 'center', padding: 4}}
labelStyle={[s.f18]}
/>
)}
{stage === Stages.ConfirmCode && (
<Button
testID="confirmBtn"
type="primary"
onPress={onConfirm}
accessibilityLabel="Confirm Change"
accessibilityHint=""
label="Confirm Change"
labelContainerStyle={{justifyContent: 'center', padding: 4}}
labelStyle={[s.f18]}
/>
)}
{stage === Stages.Done && (
<Button
testID="verifyBtn"
type="primary"
onPress={onVerify}
accessibilityLabel="Verify New Email"
accessibilityHint=""
label="Verify New Email"
labelContainerStyle={{justifyContent: 'center', padding: 4}}
labelStyle={[s.f18]}
/>
)}
<Button
testID="cancelBtn"
type="default"
onPress={() => store.shell.closeModal()}
accessibilityLabel="Cancel"
accessibilityHint=""
label="Cancel"
labelContainerStyle={{justifyContent: 'center', padding: 4}}
labelStyle={[s.f18]}
/>
</View>
)}
</View>
</ScrollView>
</SafeAreaView>
</KeyboardAvoidingView>
)
})
const styles = StyleSheet.create({
container: {
flex: 1,
paddingBottom: isWeb ? 0 : 40,
},
titleSection: {
paddingTop: isWeb ? 0 : 4,
paddingBottom: isWeb ? 14 : 10,
},
title: {
textAlign: 'center',
fontWeight: '600',
marginBottom: 5,
},
error: {
borderRadius: 6,
marginTop: 10,
},
emailContainer: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
borderWidth: 1,
borderRadius: 6,
paddingHorizontal: 14,
paddingVertical: 12,
},
textInput: {
borderWidth: 1,
borderRadius: 6,
paddingHorizontal: 14,
paddingVertical: 10,
fontSize: 16,
},
btn: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 32,
padding: 14,
backgroundColor: colors.blue3,
},
btnContainer: {
paddingTop: 20,
},
})
+2 -1
View File
@@ -23,6 +23,7 @@ export function Component({
onPressCancel,
confirmBtnText,
confirmBtnStyle,
cancelBtnText,
}: ConfirmModal) {
const pal = usePalette('default')
const store = useStores()
@@ -84,7 +85,7 @@ export function Component({
accessibilityLabel="Cancel"
accessibilityHint="">
<Text type="button-lg" style={pal.textLight}>
Cancel
{cancelBtnText ?? 'Cancel'}
</Text>
</TouchableOpacity>
)}
+1 -1
View File
@@ -266,7 +266,7 @@ const styles = StyleSheet.create({
paddingHorizontal: 12,
paddingTop: 10,
fontSize: 16,
height: 100,
height: 120,
textAlignVertical: 'top',
},
btn: {
+27
View File
@@ -26,6 +26,33 @@ export function Component({}: {}) {
store.shell.closeModal()
}, [store])
if (store.me.invites === null) {
return (
<View style={[styles.container, pal.view]} testID="inviteCodesModal">
<Text type="title-xl" style={[styles.title, pal.text]}>
Error
</Text>
<Text type="lg" style={[styles.description, pal.text]}>
An error occurred while loading invite codes.
</Text>
<View style={styles.flex1} />
<View
style={[
styles.btnContainer,
isTabletOrDesktop && styles.btnContainerDesktop,
]}>
<Button
type="primary"
label="Done"
style={styles.btn}
labelStyle={styles.btnLabel}
onPress={onClose}
/>
</View>
</View>
)
}
if (store.me.invites.length === 0) {
return (
<View style={[styles.container, pal.view]} testID="inviteCodesModal">
+162
View File
@@ -0,0 +1,162 @@
import React from 'react'
import {Linking, SafeAreaView, StyleSheet, View} from 'react-native'
import {ScrollView} from './util'
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'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {isPossiblyAUrl, splitApexDomain} from 'lib/strings/url-helpers'
export const snapPoints = ['50%']
export const Component = observer(function Component({
text,
href,
}: {
text: string
href: string
}) {
const pal = usePalette('default')
const store = useStores()
const {isMobile} = useWebMediaQueries()
const potentiallyMisleading = isPossiblyAUrl(text)
const onPressVisit = () => {
store.shell.closeModal()
Linking.openURL(href)
}
return (
<SafeAreaView style={[s.flex1, pal.view]}>
<ScrollView
testID="linkWarningModal"
style={[s.flex1, isMobile && {paddingHorizontal: 18}]}>
<View style={styles.titleSection}>
{potentiallyMisleading ? (
<>
<FontAwesomeIcon
icon="circle-exclamation"
color={pal.colors.text}
size={18}
/>
<Text type="title-lg" style={[pal.text, styles.title]}>
Potentially Misleading Link
</Text>
</>
) : (
<Text type="title-lg" style={[pal.text, styles.title]}>
Leaving Bluesky
</Text>
)}
</View>
<View style={{gap: 10}}>
<Text type="lg" style={pal.text}>
This link is taking you to the following website:
</Text>
<LinkBox href={href} />
{potentiallyMisleading && (
<Text type="lg" style={pal.text}>
Make sure this is where you intend to go!
</Text>
)}
</View>
<View style={[styles.btnContainer, isMobile && {paddingBottom: 40}]}>
<Button
testID="confirmBtn"
type="primary"
onPress={onPressVisit}
accessibilityLabel="Visit Site"
accessibilityHint=""
label="Visit Site"
labelContainerStyle={{justifyContent: 'center', padding: 4}}
labelStyle={[s.f18]}
/>
<Button
testID="cancelBtn"
type="default"
onPress={() => store.shell.closeModal()}
accessibilityLabel="Cancel"
accessibilityHint=""
label="Cancel"
labelContainerStyle={{justifyContent: 'center', padding: 4}}
labelStyle={[s.f18]}
/>
</View>
</ScrollView>
</SafeAreaView>
)
})
function LinkBox({href}: {href: string}) {
const pal = usePalette('default')
const [scheme, hostname, rest] = React.useMemo(() => {
try {
const urlp = new URL(href)
const [subdomain, apexdomain] = splitApexDomain(urlp.hostname)
return [
urlp.protocol + '//' + subdomain,
apexdomain,
urlp.pathname + urlp.search + urlp.hash,
]
} catch {
return ['', href, '']
}
}, [href])
return (
<View style={[pal.view, pal.border, styles.linkBox]}>
<Text type="lg" style={pal.textLight}>
{scheme}
<Text type="lg-bold" style={pal.text}>
{hostname}
</Text>
{rest}
</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingBottom: isWeb ? 0 : 40,
},
titleSection: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
gap: 6,
paddingTop: isWeb ? 0 : 4,
paddingBottom: isWeb ? 14 : 10,
},
title: {
textAlign: 'center',
fontWeight: '600',
},
linkBox: {
paddingHorizontal: 12,
paddingVertical: 10,
borderRadius: 6,
borderWidth: 1,
},
btn: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 32,
padding: 14,
backgroundColor: colors.blue3,
},
btnContainer: {
paddingTop: 20,
gap: 6,
},
})
+16
View File
@@ -30,6 +30,10 @@ import * as ContentLanguagesSettingsModal from './lang-settings/ContentLanguages
import * as PostLanguagesSettingsModal from './lang-settings/PostLanguagesSettings'
import * as ModerationDetailsModal from './ModerationDetails'
import * as BirthDateSettingsModal from './BirthDateSettings'
import * as VerifyEmailModal from './VerifyEmail'
import * as ChangeEmailModal from './ChangeEmail'
import * as SwitchAccountModal from './SwitchAccount'
import * as LinkWarningModal from './LinkWarning'
const DEFAULT_SNAPPOINTS = ['90%']
@@ -136,6 +140,18 @@ export const ModalsContainer = observer(function ModalsContainer() {
} else if (activeModal?.name === 'birth-date-settings') {
snapPoints = BirthDateSettingsModal.snapPoints
element = <BirthDateSettingsModal.Component />
} else if (activeModal?.name === 'verify-email') {
snapPoints = VerifyEmailModal.snapPoints
element = <VerifyEmailModal.Component {...activeModal} />
} else if (activeModal?.name === 'change-email') {
snapPoints = ChangeEmailModal.snapPoints
element = <ChangeEmailModal.Component />
} else if (activeModal?.name === 'switch-account') {
snapPoints = SwitchAccountModal.snapPoints
element = <SwitchAccountModal.Component />
} else if (activeModal?.name === 'link-warning') {
snapPoints = LinkWarningModal.snapPoints
element = <LinkWarningModal.Component {...activeModal} />
} else {
return null
}
+11 -2
View File
@@ -28,6 +28,9 @@ import * as ContentLanguagesSettingsModal from './lang-settings/ContentLanguages
import * as PostLanguagesSettingsModal from './lang-settings/PostLanguagesSettings'
import * as ModerationDetailsModal from './ModerationDetails'
import * as BirthDateSettingsModal from './BirthDateSettings'
import * as VerifyEmailModal from './VerifyEmail'
import * as ChangeEmailModal from './ChangeEmail'
import * as LinkWarningModal from './LinkWarning'
export const ModalsContainer = observer(function ModalsContainer() {
const store = useStores()
@@ -110,6 +113,12 @@ function Modal({modal}: {modal: ModalIface}) {
element = <ModerationDetailsModal.Component {...modal} />
} else if (modal.name === 'birth-date-settings') {
element = <BirthDateSettingsModal.Component />
} else if (modal.name === 'verify-email') {
element = <VerifyEmailModal.Component {...modal} />
} else if (modal.name === 'change-email') {
element = <ChangeEmailModal.Component />
} else if (modal.name === 'link-warning') {
element = <LinkWarningModal.Component {...modal} />
} else {
return null
}
@@ -147,11 +156,11 @@ const styles = StyleSheet.create({
justifyContent: 'center',
},
container: {
width: 500,
width: 600,
// @ts-ignore web only
maxWidth: '100vw',
// @ts-ignore web only
maxHeight: '100vh',
maxHeight: '90vh',
paddingVertical: 20,
paddingHorizontal: 24,
borderRadius: 8,
+131
View File
@@ -0,0 +1,131 @@
import React from 'react'
import {
ActivityIndicator,
StyleSheet,
TouchableOpacity,
View,
} from 'react-native'
import {Text} from '../util/text/Text'
import {useStores} from 'state/index'
import {s} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {useAnalytics} from 'lib/analytics/analytics'
import {useAccountSwitcher} from 'lib/hooks/useAccountSwitcher'
import {UserAvatar} from '../util/UserAvatar'
import {AccountDropdownBtn} from '../util/AccountDropdownBtn'
import {Link} from '../util/Link'
import {makeProfileLink} from 'lib/routes/links'
import {BottomSheetScrollView} from '@gorhom/bottom-sheet'
import {Haptics} from 'lib/haptics'
export const snapPoints = ['40%', '90%']
export function Component({}: {}) {
const pal = usePalette('default')
const {track} = useAnalytics()
const store = useStores()
const [isSwitching, _, onPressSwitchAccount] = useAccountSwitcher()
React.useEffect(() => {
Haptics.default()
})
const onPressSignout = React.useCallback(() => {
track('Settings:SignOutButtonClicked')
store.session.logout()
}, [track, store])
return (
<BottomSheetScrollView
style={[styles.container, pal.view]}
contentContainerStyle={[styles.innerContainer, pal.view]}>
<Text type="title-xl" style={[styles.title, pal.text]}>
Switch Account
</Text>
{isSwitching ? (
<View style={[pal.view, styles.linkCard]}>
<ActivityIndicator />
</View>
) : (
<Link href={makeProfileLink(store.me)} title="Your profile" noFeedback>
<View style={[pal.view, styles.linkCard]}>
<View style={styles.avi}>
<UserAvatar size={40} avatar={store.me.avatar} />
</View>
<View style={[s.flex1]}>
<Text type="md-bold" style={pal.text} numberOfLines={1}>
{store.me.displayName || store.me.handle}
</Text>
<Text type="sm" style={pal.textLight} numberOfLines={1}>
{store.me.handle}
</Text>
</View>
<TouchableOpacity
testID="signOutBtn"
onPress={isSwitching ? undefined : onPressSignout}
accessibilityRole="button"
accessibilityLabel="Sign out"
accessibilityHint={`Signs ${store.me.displayName} out of Bluesky`}>
<Text type="lg" style={pal.link}>
Sign out
</Text>
</TouchableOpacity>
</View>
</Link>
)}
{store.session.switchableAccounts.map(account => (
<TouchableOpacity
testID={`switchToAccountBtn-${account.handle}`}
key={account.did}
style={[pal.view, styles.linkCard, isSwitching && styles.dimmed]}
onPress={
isSwitching ? undefined : () => onPressSwitchAccount(account)
}
accessibilityRole="button"
accessibilityLabel={`Switch to ${account.handle}`}
accessibilityHint="Switches the account you are logged in to">
<View style={styles.avi}>
<UserAvatar size={40} avatar={account.aviUrl} />
</View>
<View style={[s.flex1]}>
<Text type="md-bold" style={pal.text}>
{account.displayName || account.handle}
</Text>
<Text type="sm" style={pal.textLight}>
{account.handle}
</Text>
</View>
<AccountDropdownBtn handle={account.handle} />
</TouchableOpacity>
))}
</BottomSheetScrollView>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
innerContainer: {
paddingBottom: 40,
},
title: {
textAlign: 'center',
marginTop: 12,
marginBottom: 12,
},
linkCard: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 12,
paddingHorizontal: 18,
marginBottom: 1,
},
avi: {
marginRight: 12,
},
dimmed: {
opacity: 0.5,
},
})
+323
View File
@@ -0,0 +1,323 @@
import React, {useState} from 'react'
import {
ActivityIndicator,
KeyboardAvoidingView,
Pressable,
SafeAreaView,
StyleSheet,
View,
} from 'react-native'
import {Svg, Circle, Path} from 'react-native-svg'
import {ScrollView, TextInput} from './util'
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 {ErrorMessage} from '../util/error/ErrorMessage'
import * as Toast from '../util/Toast'
import {useStores} from 'state/index'
import {s, colors} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'
import {isWeb} from 'platform/detection'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {cleanError} from 'lib/strings/errors'
export const snapPoints = ['90%']
enum Stages {
Reminder,
Email,
ConfirmCode,
}
export const Component = observer(function Component({
showReminder,
}: {
showReminder?: boolean
}) {
const pal = usePalette('default')
const store = useStores()
const [stage, setStage] = useState<Stages>(
showReminder ? Stages.Reminder : Stages.Email,
)
const [confirmationCode, setConfirmationCode] = useState<string>('')
const [isProcessing, setIsProcessing] = useState<boolean>(false)
const [error, setError] = useState<string>('')
const {isMobile} = useWebMediaQueries()
const onSendEmail = async () => {
setError('')
setIsProcessing(true)
try {
await store.agent.com.atproto.server.requestEmailConfirmation()
setStage(Stages.ConfirmCode)
} catch (e) {
setError(cleanError(String(e)))
} finally {
setIsProcessing(false)
}
}
const onConfirm = async () => {
setError('')
setIsProcessing(true)
try {
await store.agent.com.atproto.server.confirmEmail({
email: (store.session.currentSession?.email || '').trim(),
token: confirmationCode.trim(),
})
store.session.updateLocalAccountData({emailConfirmed: true})
Toast.show('Email verified')
store.shell.closeModal()
} catch (e) {
setError(cleanError(String(e)))
} finally {
setIsProcessing(false)
}
}
const onEmailIncorrect = () => {
store.shell.closeModal()
store.shell.openModal({name: 'change-email'})
}
return (
<KeyboardAvoidingView
behavior="padding"
style={[pal.view, styles.container]}>
<SafeAreaView style={s.flex1}>
<ScrollView
testID="verifyEmailModal"
style={[s.flex1, isMobile && {paddingHorizontal: 18}]}>
{stage === Stages.Reminder && <ReminderIllustration />}
<View style={styles.titleSection}>
<Text type="title-lg" style={[pal.text, styles.title]}>
{stage === Stages.Reminder ? 'Please Verify Your Email' : ''}
{stage === Stages.ConfirmCode ? 'Enter Confirmation Code' : ''}
{stage === Stages.Email ? 'Verify Your Email' : ''}
</Text>
</View>
<Text type="lg" style={[pal.textLight, {marginBottom: 10}]}>
{stage === Stages.Reminder ? (
<>
Your email has not yet been verified. This is an important
security step which we recommend.
</>
) : stage === Stages.Email ? (
<>
This is important in case you ever need to change your email or
reset your password.
</>
) : stage === Stages.ConfirmCode ? (
<>
An email has been sent to{' '}
{store.session.currentSession?.email || ''}. It includes a
confirmation code which you can enter below.
</>
) : (
''
)}
</Text>
{stage === Stages.Email ? (
<>
<View style={styles.emailContainer}>
<FontAwesomeIcon
icon="envelope"
color={pal.colors.text}
size={16}
/>
<Text
type="xl-medium"
style={[pal.text, s.flex1, {minWidth: 0}]}>
{store.session.currentSession?.email || ''}
</Text>
</View>
<Pressable
accessibilityRole="link"
accessibilityLabel="Change my email"
accessibilityHint=""
onPress={onEmailIncorrect}
style={styles.changeEmailLink}>
<Text type="lg" style={pal.link}>
Change
</Text>
</Pressable>
</>
) : stage === Stages.ConfirmCode ? (
<TextInput
testID="confirmCodeInput"
style={[styles.textInput, pal.border, pal.text]}
placeholder="XXXXX-XXXXX"
placeholderTextColor={pal.colors.textLight}
value={confirmationCode}
onChangeText={setConfirmationCode}
accessible={true}
accessibilityLabel="Confirmation code"
accessibilityHint=""
autoCapitalize="none"
autoComplete="off"
autoCorrect={false}
/>
) : undefined}
{error ? (
<ErrorMessage message={error} style={styles.error} />
) : undefined}
<View style={[styles.btnContainer]}>
{isProcessing ? (
<View style={styles.btn}>
<ActivityIndicator color="#fff" />
</View>
) : (
<View style={{gap: 6}}>
{stage === Stages.Reminder && (
<Button
testID="getStartedBtn"
type="primary"
onPress={() => setStage(Stages.Email)}
accessibilityLabel="Get Started"
accessibilityHint=""
label="Get Started"
labelContainerStyle={{justifyContent: 'center', padding: 4}}
labelStyle={[s.f18]}
/>
)}
{stage === Stages.Email && (
<>
<Button
testID="sendEmailBtn"
type="primary"
onPress={onSendEmail}
accessibilityLabel="Send Confirmation Email"
accessibilityHint=""
label="Send Confirmation Email"
labelContainerStyle={{
justifyContent: 'center',
padding: 4,
}}
labelStyle={[s.f18]}
/>
<Button
testID="haveCodeBtn"
type="default"
accessibilityLabel="I have a code"
accessibilityHint=""
label="I have a confirmation code"
labelContainerStyle={{
justifyContent: 'center',
padding: 4,
}}
labelStyle={[s.f18]}
onPress={() => setStage(Stages.ConfirmCode)}
/>
</>
)}
{stage === Stages.ConfirmCode && (
<Button
testID="confirmBtn"
type="primary"
onPress={onConfirm}
accessibilityLabel="Confirm"
accessibilityHint=""
label="Confirm"
labelContainerStyle={{justifyContent: 'center', padding: 4}}
labelStyle={[s.f18]}
/>
)}
<Button
testID="cancelBtn"
type="default"
onPress={() => store.shell.closeModal()}
accessibilityLabel={
stage === Stages.Reminder ? 'Not right now' : 'Cancel'
}
accessibilityHint=""
label={stage === Stages.Reminder ? 'Not right now' : 'Cancel'}
labelContainerStyle={{justifyContent: 'center', padding: 4}}
labelStyle={[s.f18]}
/>
</View>
)}
</View>
</ScrollView>
</SafeAreaView>
</KeyboardAvoidingView>
)
})
function ReminderIllustration() {
const pal = usePalette('default')
const palInverted = usePalette('inverted')
return (
<View style={[pal.viewLight, {borderRadius: 8, marginBottom: 20}]}>
<Svg viewBox="0 0 112 84" fill="none" height={200}>
<Path
fillRule="evenodd"
clipRule="evenodd"
d="M26 26.4264V55C26 60.5229 30.4772 65 36 65H76C81.5228 65 86 60.5229 86 55V27.4214L63.5685 49.8528C59.6633 53.7581 53.3316 53.7581 49.4264 49.8528L26 26.4264Z"
fill={palInverted.colors.background}
/>
<Path
fillRule="evenodd"
clipRule="evenodd"
d="M83.666 19.5784C85.47 21.7297 84.4897 24.7895 82.5044 26.7748L60.669 48.6102C58.3259 50.9533 54.5269 50.9533 52.1838 48.6102L29.9502 26.3766C27.8241 24.2505 26.8952 20.8876 29.0597 18.8005C30.8581 17.0665 33.3045 16 36 16H76C79.0782 16 81.8316 17.3908 83.666 19.5784Z"
fill={palInverted.colors.background}
/>
<Circle cx="82" cy="61" r="13" fill="#20BC07" />
<Path d="M75 61L80 66L89 57" stroke="white" strokeWidth="2" />
</Svg>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingBottom: isWeb ? 0 : 40,
},
titleSection: {
paddingTop: isWeb ? 0 : 4,
paddingBottom: isWeb ? 14 : 10,
},
title: {
textAlign: 'center',
fontWeight: '600',
marginBottom: 5,
},
error: {
borderRadius: 6,
marginTop: 10,
},
emailContainer: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
paddingHorizontal: 14,
marginTop: 10,
},
changeEmailLink: {
marginHorizontal: 12,
marginBottom: 12,
},
textInput: {
borderWidth: 1,
borderRadius: 6,
paddingHorizontal: 14,
paddingVertical: 10,
fontSize: 16,
},
btn: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 32,
padding: 14,
backgroundColor: colors.blue3,
},
btnContainer: {
paddingTop: 20,
},
})
+49 -9
View File
@@ -22,7 +22,7 @@ import {
import {NotificationsFeedItemModel} from 'state/models/feeds/notifications'
import {PostThreadModel} from 'state/models/content/post-thread'
import {s, colors} from 'lib/styles'
import {ago} from 'lib/strings/time'
import {niceDate} from 'lib/strings/time'
import {sanitizeDisplayName} from 'lib/strings/display-names'
import {sanitizeHandle} from 'lib/strings/handles'
import {pluralize} from 'lib/strings/helpers'
@@ -38,6 +38,8 @@ import {usePalette} from 'lib/hooks/usePalette'
import {useAnimatedValue} from 'lib/hooks/useAnimatedValue'
import {formatCount} from '../util/numeric/format'
import {makeProfileLink} from 'lib/routes/links'
import {TimeElapsed} from '../util/TimeElapsed'
import {isWeb} from 'platform/detection'
const MAX_AUTHORS = 5
@@ -88,7 +90,7 @@ export const FeedItem = observer(function FeedItemImpl({
}, [item])
const onToggleAuthorsExpanded = () => {
setAuthorsExpanded(!isAuthorsExpanded)
setAuthorsExpanded(currentlyExpanded => !currentlyExpanded)
}
const authors: Author[] = useMemo(() => {
@@ -179,7 +181,6 @@ export const FeedItem = observer(function FeedItemImpl({
}
return (
// eslint-disable-next-line react-native-a11y/no-nested-touchables
<Link
testID={`feedItem-by-${item.author.handle}`}
style={[
@@ -211,9 +212,9 @@ export const FeedItem = observer(function FeedItemImpl({
)}
</View>
<View style={styles.layoutContent}>
<Pressable
onPress={authors.length > 1 ? onToggleAuthorsExpanded : undefined}
accessible={false}>
<ExpandListPressable
hasMultipleAuthors={authors.length > 1}
onToggleAuthorsExpanded={onToggleAuthorsExpanded}>
<CondensedAuthorsList
visible={!isAuthorsExpanded}
authors={authors}
@@ -239,9 +240,17 @@ export const FeedItem = observer(function FeedItemImpl({
</>
) : undefined}
<Text style={[pal.text]}> {action}</Text>
<Text style={[pal.textLight]}> {ago(item.indexedAt)}</Text>
<TimeElapsed timestamp={item.indexedAt}>
{({timeElapsed}) => (
<Text
style={[pal.textLight, styles.pointer]}
title={niceDate(item.indexedAt)}>
{' ' + timeElapsed}
</Text>
)}
</TimeElapsed>
</Text>
</Pressable>
</ExpandListPressable>
{item.isLike || item.isRepost || item.isQuote ? (
<AdditionalPostText additionalPost={item.additionalPost} />
) : null}
@@ -250,6 +259,29 @@ export const FeedItem = observer(function FeedItemImpl({
)
})
function ExpandListPressable({
hasMultipleAuthors,
children,
onToggleAuthorsExpanded,
}: {
hasMultipleAuthors: boolean
children: React.ReactNode
onToggleAuthorsExpanded: () => void
}) {
if (hasMultipleAuthors) {
return (
<Pressable
onPress={onToggleAuthorsExpanded}
style={[styles.expandedAuthorsTrigger]}
accessible={false}>
{children}
</Pressable>
)
} else {
return <>{children}</>
}
}
function CondensedAuthorsList({
visible,
authors,
@@ -419,6 +451,12 @@ const styles = StyleSheet.create({
overflowHidden: {
overflow: 'hidden',
},
pointer: isWeb
? {
// @ts-ignore web only
cursor: 'pointer',
}
: {},
outer: {
padding: 10,
@@ -466,7 +504,9 @@ const styles = StyleSheet.create({
paddingTop: 4,
paddingLeft: 36,
},
expandedAuthorsTrigger: {
zIndex: 1,
},
expandedAuthorsCloseBtn: {
flexDirection: 'row',
alignItems: 'center',
+1 -1
View File
@@ -75,7 +75,7 @@ function InvitedUser({
<FollowButton
unfollowedType="primary"
followedType="primary-light"
did={profile.did}
profile={profile}
/>
<Button
testID="dismissBtn"
+21 -6
View File
@@ -23,7 +23,7 @@ import {ViewHeader} from '../util/ViewHeader'
import {ErrorMessage} from '../util/error/ErrorMessage'
import {Text} from '../util/text/Text'
import {s} from 'lib/styles'
import {isNative, isDesktopWeb} from 'platform/detection'
import {isNative} from 'platform/detection'
import {usePalette} from 'lib/hooks/usePalette'
import {useSetTitle} from 'lib/hooks/useSetTitle'
import {useNavigation} from '@react-navigation/native'
@@ -78,7 +78,7 @@ export const PostThread = observer(function PostThread({
treeView: boolean
}) {
const pal = usePalette('default')
const {isTablet} = useWebMediaQueries()
const {isTablet, isDesktop} = useWebMediaQueries()
const ref = useRef<FlatList>(null)
const hasScrolledIntoView = useRef<boolean>(false)
const [isRefreshing, setIsRefreshing] = React.useState(false)
@@ -189,7 +189,7 @@ export const PostThread = observer(function PostThread({
} else if (item === REPLY_PROMPT) {
return (
<View>
{isDesktopWeb && <ComposePrompt onPressCompose={onPressReply} />}
{isDesktop && <ComposePrompt onPressCompose={onPressReply} />}
</View>
)
} else if (item === DELETED) {
@@ -261,7 +261,20 @@ export const PostThread = observer(function PostThread({
}
return <></>
},
[onRefresh, onPressReply, pal, posts, isTablet, treeView],
[
isTablet,
isDesktop,
onPressReply,
pal.border,
pal.viewLight,
pal.textLight,
pal.view,
pal.text,
pal.colors.border,
posts,
onRefresh,
treeView,
],
)
// loading
@@ -354,7 +367,7 @@ export const PostThread = observer(function PostThread({
data={posts}
initialNumToRender={posts.length}
maintainVisibleContentPosition={
isNative && view.isFromCache
isNative && view.isFromCache && view.isCachedPostAReply
? MAINTAIN_VISIBLE_CONTENT_POSITION
: undefined
}
@@ -426,5 +439,7 @@ const styles = StyleSheet.create({
parentSpinner: {
paddingVertical: 10,
},
childSpinner: {},
childSpinner: {
paddingBottom: 200,
},
})
+97 -93
View File
@@ -34,7 +34,6 @@ import {usePalette} from 'lib/hooks/usePalette'
import {formatCount} from '../util/numeric/format'
import {TimeElapsed} from 'view/com/util/TimeElapsed'
import {makeProfileLink} from 'lib/routes/links'
import {isDesktopWeb} from 'platform/detection'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {Tag} from 'view/com/Tag'
@@ -52,6 +51,7 @@ export const PostThreadItem = observer(function PostThreadItem({
const pal = usePalette('default')
const store = useStores()
const [deleted, setDeleted] = React.useState(false)
const styles = useStyles()
const record = item.postRecord
const hasEngagement = item.post.likeCount || item.post.repostCount
@@ -586,6 +586,7 @@ function PostOuterWrapper({
}>) {
const {isMobile} = useWebMediaQueries()
const pal = usePalette('default')
const styles = useStyles()
if (treeView && item._depth > 1) {
return (
<View
@@ -654,95 +655,98 @@ function ExpandedPostDetails({
)
}
const styles = StyleSheet.create({
outer: {
borderTopWidth: 1,
paddingLeft: 8,
},
outerHighlighted: {
paddingTop: 16,
paddingLeft: 8,
paddingRight: 8,
},
noTopBorder: {
borderTopWidth: 0,
},
layout: {
flexDirection: 'row',
gap: 10,
paddingLeft: 8,
},
layoutAvi: {},
layoutContent: {
flex: 1,
paddingRight: 10,
},
meta: {
flexDirection: 'row',
paddingTop: 2,
paddingBottom: 2,
},
metaExpandedLine1: {
paddingTop: 5,
paddingBottom: 0,
},
metaItem: {
paddingRight: 5,
maxWidth: isDesktopWeb ? 380 : 220,
},
alert: {
marginBottom: 6,
},
postTextContainer: {
flexDirection: 'row',
alignItems: 'center',
flexWrap: 'wrap',
paddingBottom: 4,
paddingRight: 10,
},
postTextLargeContainer: {
paddingHorizontal: 0,
paddingBottom: 10,
},
translateLink: {
marginBottom: 6,
},
contentHider: {
marginBottom: 6,
},
contentHiderChild: {
marginTop: 6,
},
expandedInfo: {
flexDirection: 'row',
padding: 10,
borderTopWidth: 1,
borderBottomWidth: 1,
marginTop: 5,
marginBottom: 15,
},
expandedInfoItem: {
marginRight: 10,
},
loadMore: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
gap: 4,
paddingHorizontal: 20,
},
replyLine: {
width: 2,
marginLeft: 'auto',
marginRight: 'auto',
},
cursor: {
// @ts-ignore web only
cursor: 'pointer',
},
tag: {
paddingVertical: 4,
paddingHorizontal: 8,
borderRadius: 4,
},
})
const useStyles = () => {
const {isDesktop} = useWebMediaQueries()
return StyleSheet.create({
outer: {
borderTopWidth: 1,
paddingLeft: 8,
},
outerHighlighted: {
paddingTop: 16,
paddingLeft: 8,
paddingRight: 8,
},
noTopBorder: {
borderTopWidth: 0,
},
layout: {
flexDirection: 'row',
gap: 10,
paddingLeft: 8,
},
layoutAvi: {},
layoutContent: {
flex: 1,
paddingRight: 10,
},
meta: {
flexDirection: 'row',
paddingTop: 2,
paddingBottom: 2,
},
metaExpandedLine1: {
paddingTop: 5,
paddingBottom: 0,
},
metaItem: {
paddingRight: 5,
maxWidth: isDesktop ? 380 : 220,
},
alert: {
marginBottom: 6,
},
postTextContainer: {
flexDirection: 'row',
alignItems: 'center',
flexWrap: 'wrap',
paddingBottom: 4,
paddingRight: 10,
},
postTextLargeContainer: {
paddingHorizontal: 0,
paddingBottom: 10,
},
translateLink: {
marginBottom: 6,
},
contentHider: {
marginBottom: 6,
},
contentHiderChild: {
marginTop: 6,
},
expandedInfo: {
flexDirection: 'row',
padding: 10,
borderTopWidth: 1,
borderBottomWidth: 1,
marginTop: 5,
marginBottom: 15,
},
expandedInfoItem: {
marginRight: 10,
},
loadMore: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
gap: 4,
paddingHorizontal: 20,
},
replyLine: {
width: 2,
marginLeft: 'auto',
marginRight: 'auto',
},
cursor: {
// @ts-ignore web only
cursor: 'pointer',
},
tag: {
paddingVertical: 4,
paddingHorizontal: 8,
borderRadius: 4,
},
})
}
+6 -2
View File
@@ -33,6 +33,7 @@ export const Feed = observer(function Feed({
onScroll,
scrollEventThrottle,
renderEmptyState,
renderEndOfFeed,
testID,
headerOffset = 0,
ListHeaderComponent,
@@ -45,6 +46,7 @@ export const Feed = observer(function Feed({
onScroll?: OnScrollCb
scrollEventThrottle?: number
renderEmptyState?: () => JSX.Element
renderEndOfFeed?: () => JSX.Element
testID?: string
headerOffset?: number
ListHeaderComponent?: () => JSX.Element
@@ -142,14 +144,16 @@ export const Feed = observer(function Feed({
const FeedFooter = React.useCallback(
() =>
feed.isLoading ? (
feed.isLoadingMore ? (
<View style={styles.feedFooter}>
<ActivityIndicator />
</View>
) : !feed.hasMore && !feed.isEmpty && renderEndOfFeed ? (
renderEndOfFeed()
) : (
<View />
),
[feed],
[feed.isLoadingMore, feed.hasMore, feed.isEmpty, renderEndOfFeed],
)
return (
+51 -47
View File
@@ -28,60 +28,73 @@ export function FollowingEmptyState() {
}, [navigation])
const onPressDiscoverFeeds = React.useCallback(() => {
navigation.navigate('Feeds')
if (isWeb) {
navigation.navigate('Feeds')
} else {
navigation.navigate('FeedsTab')
navigation.popToTop()
}
}, [navigation])
return (
<View style={styles.emptyContainer}>
<View style={styles.emptyIconContainer}>
<MagnifyingGlassIcon style={[styles.emptyIcon, pal.text]} size={62} />
</View>
<Text type="xl-medium" style={[s.textCenter, pal.text]}>
Your following feed is empty! Find some accounts to follow to fix this.
</Text>
<Button
type="inverted"
style={styles.emptyBtn}
onPress={onPressFindAccounts}>
<Text type="lg-medium" style={palInverted.text}>
Find accounts to follow
<View style={styles.container}>
<View style={styles.inner}>
<View style={styles.iconContainer}>
<MagnifyingGlassIcon style={[styles.icon, pal.text]} size={62} />
</View>
<Text type="xl-medium" style={[s.textCenter, pal.text]}>
Your following feed is empty! Follow more users to see what's
happening.
</Text>
<FontAwesomeIcon
icon="angle-right"
style={palInverted.text as FontAwesomeIconStyle}
size={14}
/>
</Button>
<Button
type="inverted"
style={styles.emptyBtn}
onPress={onPressFindAccounts}>
<Text type="lg-medium" style={palInverted.text}>
Find accounts to follow
</Text>
<FontAwesomeIcon
icon="angle-right"
style={palInverted.text as FontAwesomeIconStyle}
size={14}
/>
</Button>
<Text type="xl-medium" style={[s.textCenter, pal.text, s.mt20]}>
You can also discover new Custom Feeds to follow.
</Text>
<Button
type="inverted"
style={[styles.emptyBtn, s.mt10]}
onPress={onPressDiscoverFeeds}>
<Text type="lg-medium" style={palInverted.text}>
Discover new custom feeds
<Text type="xl-medium" style={[s.textCenter, pal.text, s.mt20]}>
You can also discover new Custom Feeds to follow.
</Text>
<FontAwesomeIcon
icon="angle-right"
style={palInverted.text as FontAwesomeIconStyle}
size={14}
/>
</Button>
<Button
type="inverted"
style={[styles.emptyBtn, s.mt10]}
onPress={onPressDiscoverFeeds}>
<Text type="lg-medium" style={palInverted.text}>
Discover new custom feeds
</Text>
<FontAwesomeIcon
icon="angle-right"
style={palInverted.text as FontAwesomeIconStyle}
size={14}
/>
</Button>
</View>
</View>
)
}
const styles = StyleSheet.create({
emptyContainer: {
container: {
height: '100%',
flexDirection: 'row',
justifyContent: 'center',
paddingVertical: 40,
paddingHorizontal: 30,
},
emptyIconContainer: {
inner: {
maxWidth: 460,
},
iconContainer: {
marginBottom: 16,
},
emptyIcon: {
icon: {
marginLeft: 'auto',
marginRight: 'auto',
},
@@ -94,13 +107,4 @@ const styles = StyleSheet.create({
paddingHorizontal: 24,
borderRadius: 30,
},
feedsTip: {
position: 'absolute',
left: 22,
},
feedsTipArrow: {
marginLeft: 32,
marginTop: 8,
},
})
+100
View File
@@ -0,0 +1,100 @@
import React from 'react'
import {StyleSheet, View} from 'react-native'
import {useNavigation} from '@react-navigation/native'
import {
FontAwesomeIcon,
FontAwesomeIconStyle,
} from '@fortawesome/react-native-fontawesome'
import {Text} from '../util/text/Text'
import {Button} from '../util/forms/Button'
import {NavigationProp} from 'lib/routes/types'
import {usePalette} from 'lib/hooks/usePalette'
import {s} from 'lib/styles'
import {isWeb} from 'platform/detection'
export function FollowingEndOfFeed() {
const pal = usePalette('default')
const palInverted = usePalette('inverted')
const navigation = useNavigation<NavigationProp>()
const onPressFindAccounts = React.useCallback(() => {
if (isWeb) {
navigation.navigate('Search', {})
} else {
navigation.navigate('SearchTab')
navigation.popToTop()
}
}, [navigation])
const onPressDiscoverFeeds = React.useCallback(() => {
if (isWeb) {
navigation.navigate('Feeds')
} else {
navigation.navigate('FeedsTab')
navigation.popToTop()
}
}, [navigation])
return (
<View style={[styles.container, pal.border]}>
<View style={styles.inner}>
<Text type="xl-medium" style={[s.textCenter, pal.text]}>
You've reached the end of your feed! Find some more accounts to
follow.
</Text>
<Button
type="inverted"
style={styles.emptyBtn}
onPress={onPressFindAccounts}>
<Text type="lg-medium" style={palInverted.text}>
Find accounts to follow
</Text>
<FontAwesomeIcon
icon="angle-right"
style={palInverted.text as FontAwesomeIconStyle}
size={14}
/>
</Button>
<Text type="xl-medium" style={[s.textCenter, pal.text, s.mt20]}>
You can also discover new Custom Feeds to follow.
</Text>
<Button
type="inverted"
style={[styles.emptyBtn, s.mt10]}
onPress={onPressDiscoverFeeds}>
<Text type="lg-medium" style={palInverted.text}>
Discover new custom feeds
</Text>
<FontAwesomeIcon
icon="angle-right"
style={palInverted.text as FontAwesomeIconStyle}
size={14}
/>
</Button>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
justifyContent: 'center',
paddingTop: 40,
paddingBottom: 80,
paddingHorizontal: 30,
borderTopWidth: 1,
},
inner: {
maxWidth: 460,
},
emptyBtn: {
marginVertical: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingVertical: 18,
paddingHorizontal: 24,
borderRadius: 30,
},
})
+5 -4
View File
@@ -1,25 +1,26 @@
import React from 'react'
import {StyleProp, TextStyle, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import {AppBskyActorDefs} from '@atproto/api'
import {Button, ButtonType} from '../util/forms/Button'
import * as Toast from '../util/Toast'
import {FollowState} from 'state/models/cache/my-follows'
import {useFollowDid} from 'lib/hooks/useFollowDid'
import {useFollowProfile} from 'lib/hooks/useFollowProfile'
export const FollowButton = observer(function FollowButtonImpl({
unfollowedType = 'inverted',
followedType = 'default',
did,
profile,
onToggleFollow,
labelStyle,
}: {
unfollowedType?: ButtonType
followedType?: ButtonType
did: string
profile: AppBskyActorDefs.ProfileViewBasic
onToggleFollow?: (v: boolean) => void
labelStyle?: StyleProp<TextStyle>
}) {
const {state, following, toggle} = useFollowDid({did})
const {state, following, toggle} = useFollowProfile(profile)
const onPress = React.useCallback(async () => {
try {
+1 -1
View File
@@ -200,7 +200,7 @@ export const ProfileCardWithFollowBtn = observer(
noBorder={noBorder}
followers={followers}
renderButton={
isMe ? undefined : () => <FollowButton did={profile.did} />
isMe ? undefined : () => <FollowButton profile={profile} />
}
/>
)
+2 -2
View File
@@ -392,8 +392,8 @@ const ProfileHeaderLoaded = observer(function ProfileHeaderLoadedImpl({
{
paddingHorizontal: 10,
backgroundColor: showSuggestedFollows
? colors.blue3
: pal.viewLight.backgroundColor,
? pal.colors.text
: pal.colors.backgroundLight,
},
]}
accessibilityRole="button"
@@ -19,7 +19,7 @@ import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette'
import {Text} from 'view/com/util/text/Text'
import {UserAvatar} from 'view/com/util/UserAvatar'
import {useFollowDid} from 'lib/hooks/useFollowDid'
import {useFollowProfile} from 'lib/hooks/useFollowProfile'
import {Button} from 'view/com/util/forms/Button'
import {sanitizeDisplayName} from 'lib/strings/display-names'
import {sanitizeHandle} from 'lib/strings/handles'
@@ -83,7 +83,7 @@ export function ProfileHeaderSuggestedFollows({
return []
}
store.me.follows.hydrateProfiles(suggestions)
store.me.follows.hydrateMany(suggestions)
return suggestions
} catch (e) {
@@ -218,7 +218,7 @@ const SuggestedFollow = observer(function SuggestedFollowImpl({
const {track} = useAnalytics()
const pal = usePalette('default')
const store = useStores()
const {following, toggle} = useFollowDid({did: profile.did})
const {following, toggle} = useFollowProfile(profile)
const moderation = moderateProfile(profile, store.preferences.moderationOpts)
const onPress = React.useCallback(async () => {
+1 -1
View File
@@ -93,7 +93,7 @@ export function HeaderWithInput({
onBlur={() => setIsInputFocused(false)}
onChangeText={onChangeQuery}
onSubmitEditing={onSubmitQuery}
autoFocus={isMobile}
autoFocus={false}
accessibilityRole="search"
accessibilityLabel="Search"
accessibilityHint=""
+84 -48
View File
@@ -2,7 +2,7 @@ import React, {forwardRef, ForwardedRef} from 'react'
import {RefreshControl, StyleSheet, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import {AppBskyActorDefs} from '@atproto/api'
import {CenteredView, FlatList} from '../util/Views'
import {FlatList} from '../util/Views'
import {FoafsModel} from 'state/models/discovery/foafs'
import {
SuggestedActorsModel,
@@ -10,11 +10,12 @@ import {
} from 'state/models/discovery/suggested-actors'
import {Text} from '../util/text/Text'
import {ProfileCardWithFollowBtn} from '../profile/ProfileCard'
import {ProfileCardFeedLoadingPlaceholder} from 'view/com/util/LoadingPlaceholder'
import {ProfileCardLoadingPlaceholder} from 'view/com/util/LoadingPlaceholder'
import {sanitizeDisplayName} from 'lib/strings/display-names'
import {sanitizeHandle} from 'lib/strings/handles'
import {RefWithInfoAndFollowers} from 'state/models/discovery/foafs'
import {usePalette} from 'lib/hooks/usePalette'
import {s} from 'lib/styles'
interface Heading {
_reactKey: string
@@ -36,7 +37,16 @@ interface ProfileView {
type: 'profile-view'
view: AppBskyActorDefs.ProfileViewBasic
}
type Item = Heading | RefWrapper | SuggestWrapper | ProfileView
interface LoadingPlaceholder {
_reactKey: string
type: 'loading-placeholder'
}
type Item =
| Heading
| RefWrapper
| SuggestWrapper
| ProfileView
| LoadingPlaceholder
// FIXME(dan): Figure out why the false positives
/* eslint-disable react/prop-types */
@@ -57,23 +67,6 @@ export const Suggestions = observer(
const data = React.useMemo(() => {
let items: Item[] = []
if (foafs.popular.length > 0) {
items = items
.concat([
{
_reactKey: '__popular_heading__',
type: 'heading',
title: 'In Your Network',
},
])
.concat(
foafs.popular.map(ref => ({
_reactKey: `popular-${ref.did}`,
type: 'ref',
ref,
})),
)
}
if (suggestedActors.hasContent) {
items = items
.concat([
@@ -90,34 +83,73 @@ export const Suggestions = observer(
suggested,
})),
)
} else if (suggestedActors.isLoading) {
items = items.concat([
{
_reactKey: '__suggested_heading__',
type: 'heading',
title: 'Suggested Follows',
},
{_reactKey: '__suggested_loading__', type: 'loading-placeholder'},
])
}
for (const source of foafs.sources) {
const item = foafs.foafs.get(source)
if (!item || item.follows.length === 0) {
continue
if (foafs.isLoading) {
items = items.concat([
{
_reactKey: '__popular_heading__',
type: 'heading',
title: 'In Your Network',
},
{_reactKey: '__foafs_loading__', type: 'loading-placeholder'},
])
} else {
if (foafs.popular.length > 0) {
items = items
.concat([
{
_reactKey: '__popular_heading__',
type: 'heading',
title: 'In Your Network',
},
])
.concat(
foafs.popular.map(ref => ({
_reactKey: `popular-${ref.did}`,
type: 'ref',
ref,
})),
)
}
for (const source of foafs.sources) {
const item = foafs.foafs.get(source)
if (!item || item.follows.length === 0) {
continue
}
items = items
.concat([
{
_reactKey: `__${item.did}_heading__`,
type: 'heading',
title: `Followed by ${sanitizeDisplayName(
item.displayName || sanitizeHandle(item.handle),
)}`,
},
])
.concat(
item.follows.slice(0, 10).map(view => ({
_reactKey: `${item.did}-${view.did}`,
type: 'profile-view',
view,
})),
)
}
items = items
.concat([
{
_reactKey: `__${item.did}_heading__`,
type: 'heading',
title: `Followed by ${sanitizeDisplayName(
item.displayName || sanitizeHandle(item.handle),
)}`,
},
])
.concat(
item.follows.slice(0, 10).map(view => ({
_reactKey: `${item.did}-${view.did}`,
type: 'profile-view',
view,
})),
)
}
return items
}, [
foafs.isLoading,
foafs.popular,
suggestedActors.isLoading,
suggestedActors.hasContent,
suggestedActors.suggestions,
foafs.sources,
@@ -183,18 +215,21 @@ export const Suggestions = observer(
</View>
)
}
if (item.type === 'loading-placeholder') {
return (
<View>
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
</View>
)
}
return null
},
[pal],
)
if (foafs.isLoading || suggestedActors.isLoading) {
return (
<CenteredView>
<ProfileCardFeedLoadingPlaceholder />
</CenteredView>
)
}
return (
<FlatList
ref={flatListRef}
@@ -210,6 +245,7 @@ export const Suggestions = observer(
}
renderItem={renderItem}
initialNumToRender={15}
contentContainerStyle={s.contentContainer}
/>
)
}),
+46
View File
@@ -0,0 +1,46 @@
import React from 'react'
import {Pressable} from 'react-native'
import {
FontAwesomeIcon,
FontAwesomeIconStyle,
} from '@fortawesome/react-native-fontawesome'
import {s} from 'lib/styles'
import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette'
import {DropdownItem, NativeDropdown} from './forms/NativeDropdown'
import * as Toast from '../../com/util/Toast'
export function AccountDropdownBtn({handle}: {handle: string}) {
const store = useStores()
const pal = usePalette('default')
const items: DropdownItem[] = [
{
label: 'Remove account',
onPress: () => {
store.session.removeAccount(handle)
Toast.show('Account removed from quick access')
},
icon: {
ios: {
name: 'trash',
},
android: 'ic_delete',
web: 'trash',
},
},
]
return (
<Pressable accessibilityRole="button" style={s.pl10}>
<NativeDropdown
testID="accountSettingsDropdownBtn"
items={items}
accessibilityLabel="Account options"
accessibilityHint="">
<FontAwesomeIcon
icon="ellipsis-h"
style={pal.textLight as FontAwesomeIconStyle}
/>
</NativeDropdown>
</Pressable>
)
}
+2 -1
View File
@@ -22,7 +22,7 @@ export function EmptyState({
}) {
const pal = usePalette('default')
return (
<View testID={testID} style={[styles.container, style]}>
<View testID={testID} style={[styles.container, pal.border, style]}>
<View style={styles.iconContainer}>
{icon === 'user-group' ? (
<UserGroupIcon size="64" style={styles.icon} />
@@ -50,6 +50,7 @@ const styles = StyleSheet.create({
container: {
paddingVertical: 20,
paddingHorizontal: 36,
borderTopWidth: 1,
},
iconContainer: {
flexDirection: 'row',
+1 -1
View File
@@ -28,7 +28,7 @@ export class ErrorBoundary extends Component<Props, State> {
public render() {
if (this.state.hasError) {
return (
<CenteredView>
<CenteredView style={{height: '100%', flex: 1}}>
<ErrorScreen
title="Oh no!"
message="There was an unexpected issue in the application. Please let us know if this happened to you!"
+69 -56
View File
@@ -4,13 +4,13 @@ import {usePalette} from 'lib/hooks/usePalette'
import {useTheme} from 'lib/ThemeContext'
import {Text} from './text/Text'
import {TextLink} from './Link'
import {isDesktopWeb} from 'platform/detection'
import {
H1 as ExpoH1,
H2 as ExpoH2,
H3 as ExpoH3,
H4 as ExpoH4,
} from '@expo/html-elements'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
/**
* These utilities are used to define long documents in an html-like
@@ -27,30 +27,35 @@ interface IsChildProps {
// | React.ReactNode
export function H1({children}: React.PropsWithChildren<{}>) {
const styles = useStyles()
const pal = usePalette('default')
const typography = useTheme().typography['title-xl']
return <ExpoH1 style={[typography, pal.text, styles.h1]}>{children}</ExpoH1>
}
export function H2({children}: React.PropsWithChildren<{}>) {
const styles = useStyles()
const pal = usePalette('default')
const typography = useTheme().typography['title-lg']
return <ExpoH2 style={[typography, pal.text, styles.h2]}>{children}</ExpoH2>
}
export function H3({children}: React.PropsWithChildren<{}>) {
const styles = useStyles()
const pal = usePalette('default')
const typography = useTheme().typography.title
return <ExpoH3 style={[typography, pal.text, styles.h3]}>{children}</ExpoH3>
}
export function H4({children}: React.PropsWithChildren<{}>) {
const styles = useStyles()
const pal = usePalette('default')
const typography = useTheme().typography['title-sm']
return <ExpoH4 style={[typography, pal.text, styles.h4]}>{children}</ExpoH4>
}
export function P({children}: React.PropsWithChildren<{}>) {
const styles = useStyles()
const pal = usePalette('default')
return (
<Text type="md" style={[pal.text, styles.p]}>
@@ -60,6 +65,7 @@ export function P({children}: React.PropsWithChildren<{}>) {
}
export function UL({children, isChild}: React.PropsWithChildren<IsChildProps>) {
const styles = useStyles()
return (
<View style={[styles.ul, isChild && styles.ulChild]}>
{markChildProps(children)}
@@ -68,6 +74,7 @@ export function UL({children, isChild}: React.PropsWithChildren<IsChildProps>) {
}
export function OL({children, isChild}: React.PropsWithChildren<IsChildProps>) {
const styles = useStyles()
return (
<View style={[styles.ol, isChild && styles.olChild]}>
{markChildProps(children)}
@@ -79,6 +86,7 @@ export function LI({
children,
value,
}: React.PropsWithChildren<{value?: string}>) {
const styles = useStyles()
const pal = usePalette('default')
return (
<View style={styles.li}>
@@ -91,6 +99,7 @@ export function LI({
}
export function A({children, href}: React.PropsWithChildren<{href: string}>) {
const styles = useStyles()
const pal = usePalette('default')
return (
<TextLink
@@ -112,6 +121,7 @@ export function STRONG({children}: React.PropsWithChildren<{}>) {
}
export function EM({children}: React.PropsWithChildren<{}>) {
const styles = useStyles()
const pal = usePalette('default')
return (
<Text type="md" style={[pal.text, styles.em]}>
@@ -132,58 +142,61 @@ function markChildProps(children: React.ReactNode) {
})
}
const styles = StyleSheet.create({
h1: {
marginTop: 20,
marginBottom: 10,
letterSpacing: 0.8,
},
h2: {
marginTop: 20,
marginBottom: 10,
letterSpacing: 0.8,
},
h3: {
marginTop: 0,
marginBottom: 10,
},
h4: {
marginTop: 0,
marginBottom: 10,
fontWeight: 'bold',
},
p: {
marginBottom: 10,
},
ul: {
marginBottom: 10,
paddingLeft: isDesktopWeb ? 18 : 4,
},
ulChild: {
paddingTop: 10,
marginBottom: 0,
},
ol: {
marginBottom: 10,
paddingLeft: isDesktopWeb ? 18 : 4,
},
olChild: {
paddingTop: 10,
marginBottom: 0,
},
li: {
flexDirection: 'row',
paddingRight: 20,
marginBottom: 10,
},
liBullet: {
paddingRight: 10,
},
liText: {},
a: {
marginBottom: 10,
},
em: {
fontStyle: 'italic',
},
})
const useStyles = () => {
const {isDesktop} = useWebMediaQueries()
return StyleSheet.create({
h1: {
marginTop: 20,
marginBottom: 10,
letterSpacing: 0.8,
},
h2: {
marginTop: 20,
marginBottom: 10,
letterSpacing: 0.8,
},
h3: {
marginTop: 0,
marginBottom: 10,
},
h4: {
marginTop: 0,
marginBottom: 10,
fontWeight: 'bold',
},
p: {
marginBottom: 10,
},
ul: {
marginBottom: 10,
paddingLeft: isDesktop ? 18 : 4,
},
ulChild: {
paddingTop: 10,
marginBottom: 0,
},
ol: {
marginBottom: 10,
paddingLeft: isDesktop ? 18 : 4,
},
olChild: {
paddingTop: 10,
marginBottom: 0,
},
li: {
flexDirection: 'row',
paddingRight: 20,
marginBottom: 10,
},
liBullet: {
paddingRight: 10,
},
liText: {},
a: {
marginBottom: 10,
},
em: {
fontStyle: 'italic',
},
})
}
+28 -4
View File
@@ -23,11 +23,16 @@ import {TypographyVariant} from 'lib/ThemeContext'
import {NavigationProp} from 'lib/routes/types'
import {router} from '../../../routes'
import {useStores, RootStoreModel} from 'state/index'
import {convertBskyAppUrlIfNeeded, isExternalUrl} from 'lib/strings/url-helpers'
import {isAndroid, isDesktopWeb} from 'platform/detection'
import {
convertBskyAppUrlIfNeeded,
isExternalUrl,
linkRequiresWarning,
} from 'lib/strings/url-helpers'
import {isAndroid} from 'platform/detection'
import {sanitizeUrl} from '@braintree/sanitize-url'
import {PressableWithHover} from './PressableWithHover'
import FixedTouchableHighlight from '../pager/FixedTouchableHighlight'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
type Event =
| React.MouseEvent<HTMLAnchorElement, MouseEvent>
@@ -142,6 +147,7 @@ export const TextLink = observer(function TextLink({
dataSet,
title,
onPress,
warnOnMismatchingLabel,
...orgProps
}: {
testID?: string
@@ -153,13 +159,29 @@ export const TextLink = observer(function TextLink({
lineHeight?: number
dataSet?: any
title?: string
warnOnMismatchingLabel?: boolean
} & TextProps) {
const {...props} = useLinkProps({to: sanitizeUrl(href)})
const store = useStores()
const navigation = useNavigation<NavigationProp>()
if (warnOnMismatchingLabel && typeof text !== 'string') {
console.error('Unable to detect mismatching label')
}
props.onPress = React.useCallback(
(e?: Event) => {
const requiresWarning =
warnOnMismatchingLabel &&
linkRequiresWarning(href, typeof text === 'string' ? text : '')
if (requiresWarning) {
e?.preventDefault?.()
store.shell.openModal({
name: 'link-warning',
text: typeof text === 'string' ? text : '',
href,
})
}
if (onPress) {
e?.preventDefault?.()
// @ts-ignore function signature differs by platform -prf
@@ -167,7 +189,7 @@ export const TextLink = observer(function TextLink({
}
return onPressInner(store, navigation, sanitizeUrl(href), e)
},
[onPress, store, navigation, href],
[onPress, store, navigation, href, text, warnOnMismatchingLabel],
)
const hrefAttrs = useMemo(() => {
const isExternal = isExternalUrl(href)
@@ -224,7 +246,9 @@ export const DesktopWebTextLink = observer(function DesktopWebTextLink({
lineHeight,
...props
}: DesktopWebTextLinkProps) {
if (isDesktopWeb) {
const {isDesktop} = useWebMediaQueries()
if (isDesktop) {
return (
<TextLink
testID={testID}
+3
View File
@@ -174,6 +174,9 @@ export function UserAvatar({
aspect: [1, 1],
})
const item = items[0]
if (!item) {
return
}
const croppedImage = await openCropper(store, {
mediaType: 'photo',
+3
View File
@@ -69,6 +69,9 @@ export function UserBanner({
return
}
const items = await openPicker()
if (!items[0]) {
return
}
onSelectNewBanner?.(
await openCropper(store, {
+12 -2
View File
@@ -42,6 +42,7 @@ export function Button({
type = 'primary',
label,
style,
labelContainerStyle,
labelStyle,
onPress,
children,
@@ -55,6 +56,7 @@ export function Button({
type?: ButtonType
label?: string
style?: StyleProp<ViewStyle>
labelContainerStyle?: StyleProp<ViewStyle>
labelStyle?: StyleProp<TextStyle>
onPress?: () => void | Promise<void>
testID?: string
@@ -173,7 +175,7 @@ export function Button({
}
return (
<View style={styles.labelContainer}>
<View style={[styles.labelContainer, labelContainerStyle]}>
{label && withLoading && isLoading ? (
<ActivityIndicator size={12} color={typeLabelStyle.color} />
) : null}
@@ -182,7 +184,15 @@ export function Button({
</Text>
</View>
)
}, [children, label, withLoading, isLoading, typeLabelStyle, labelStyle])
}, [
children,
label,
withLoading,
isLoading,
labelContainerStyle,
typeLabelStyle,
labelStyle,
])
return (
<Pressable
+1
View File
@@ -91,6 +91,7 @@ export function RichText({
href={link.uri}
style={[style, lineHeightStyle, pal.link]}
dataSet={WORD_WRAP}
warnOnMismatchingLabel
/>,
)
} else if (tag && AppBskyRichtextFacet.validateTag(tag).success) {
+9
View File
@@ -13,6 +13,7 @@ import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {TextLink} from 'view/com/util/Link'
import {Feed} from '../com/posts/Feed'
import {FollowingEmptyState} from 'view/com/posts/FollowingEmptyState'
import {FollowingEndOfFeed} from 'view/com/posts/FollowingEndOfFeed'
import {CustomFeedEmptyState} from 'view/com/posts/CustomFeedEmptyState'
import {LoadLatestBtn} from '../com/util/load-latest/LoadLatestBtn'
import {FeedsTabBar} from '../com/pager/FeedsTabBar'
@@ -110,6 +111,10 @@ export const HomeScreen = withAuthRequired(
return <FollowingEmptyState />
}, [])
const renderFollowingEndOfFeed = React.useCallback(() => {
return <FollowingEndOfFeed />
}, [])
const renderCustomFeedEmptyState = React.useCallback(() => {
return <CustomFeedEmptyState />
}, [])
@@ -127,6 +132,7 @@ export const HomeScreen = withAuthRequired(
isPageFocused={selectedPage === 0}
feed={store.me.mainFeed}
renderEmptyState={renderFollowingEmptyState}
renderEndOfFeed={renderFollowingEndOfFeed}
/>
{customFeeds.map((f, index) => {
return (
@@ -149,11 +155,13 @@ const FeedPage = observer(function FeedPageImpl({
isPageFocused,
feed,
renderEmptyState,
renderEndOfFeed,
}: {
testID?: string
feed: PostsFeedModel
isPageFocused: boolean
renderEmptyState?: () => JSX.Element
renderEndOfFeed?: () => JSX.Element
}) {
const store = useStores()
const pal = usePalette('default')
@@ -307,6 +315,7 @@ const FeedPage = observer(function FeedPageImpl({
onScroll={onMainScroll}
scrollEventThrottle={100}
renderEmptyState={renderEmptyState}
renderEndOfFeed={renderEndOfFeed}
ListHeaderComponent={ListHeaderComponent}
headerOffset={headerOffset}
/>
+1
View File
@@ -71,6 +71,7 @@ export const NotificationsScreen = withAuthRequired(
}
}, [store, screen, onPressLoadLatest]),
)
useTabFocusEffect(
'Notifications',
React.useCallback(
+6 -6
View File
@@ -148,18 +148,18 @@ export const SearchScreen = withAuthRequired(
style={pal.view}
onScroll={onMainScroll}
scrollEventThrottle={100}>
{query && autocompleteView.searchRes.length ? (
{query && autocompleteView.suggestions.length ? (
<>
{autocompleteView.searchRes.map((profile, index) => (
{autocompleteView.suggestions.map((suggestion, index) => (
<ProfileCard
key={profile.did}
testID={`searchAutoCompleteResult-${profile.handle}`}
profile={profile}
key={suggestion.did}
testID={`searchAutoCompleteResult-${suggestion.handle}`}
profile={suggestion}
noBorder={index === 0}
/>
))}
</>
) : query && !autocompleteView.searchRes.length ? (
) : query && !autocompleteView.suggestions.length ? (
<View>
<Text style={[pal.textLight, styles.searchPrompt]}>
No results found for {autocompleteView.prefix}
+123 -92
View File
@@ -3,8 +3,8 @@ import {
ActivityIndicator,
Linking,
Platform,
Pressable,
StyleSheet,
Pressable,
TextStyle,
TouchableOpacity,
View,
@@ -36,22 +36,21 @@ import {SelectableBtn} from 'view/com/util/forms/SelectableBtn'
import {usePalette} from 'lib/hooks/usePalette'
import {useCustomPalette} from 'lib/hooks/useCustomPalette'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {AccountData} from 'state/models/session'
import {useAccountSwitcher} from 'lib/hooks/useAccountSwitcher'
import {useAnalytics} from 'lib/analytics/analytics'
import {NavigationProp} from 'lib/routes/types'
import {pluralize} from 'lib/strings/helpers'
import {HandIcon, HashtagIcon} from 'lib/icons'
import {formatCount} from 'view/com/util/numeric/format'
import Clipboard from '@react-native-clipboard/clipboard'
import {reset as resetNavigation} from '../../Navigation'
import {makeProfileLink} from 'lib/routes/links'
import {AccountDropdownBtn} from 'view/com/util/AccountDropdownBtn'
// TEMPORARY (APP-700)
// remove after backend testing finishes
// -prf
import {useDebugHeaderSetting} from 'lib/api/debug-appview-proxy-header'
import {STATUS_PAGE_URL} from 'lib/constants'
import {DropdownItem, NativeDropdown} from 'view/com/util/forms/NativeDropdown'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'Settings'>
export const SettingsScreen = withAuthRequired(
@@ -61,7 +60,8 @@ export const SettingsScreen = withAuthRequired(
const navigation = useNavigation<NavigationProp>()
const {isMobile} = useWebMediaQueries()
const {screen, track} = useAnalytics()
const [isSwitching, setIsSwitching] = React.useState(false)
const [isSwitching, setIsSwitching, onPressSwitchAccount] =
useAccountSwitcher()
const [debugHeaderEnabled, toggleDebugHeader] = useDebugHeaderSetting(
store.agent,
)
@@ -91,25 +91,6 @@ export const SettingsScreen = withAuthRequired(
}, [screen, store]),
)
const onPressSwitchAccount = React.useCallback(
async (acct: AccountData) => {
track('Settings:SwitchAccountButtonClicked')
setIsSwitching(true)
if (await store.session.resumeSession(acct)) {
setIsSwitching(false)
resetNavigation()
Toast.show(`Signed in as ${acct.displayName || acct.handle}`)
return
}
setIsSwitching(false)
Toast.show('Sorry! We need you to enter your password.')
navigation.navigate('HomeTab')
navigation.dispatch(StackActions.popToTop())
store.session.clear()
},
[track, setIsSwitching, navigation, store],
)
const onPressAddAccount = React.useCallback(() => {
track('Settings:AddAccountButtonClicked')
navigation.navigate('HomeTab')
@@ -219,10 +200,25 @@ export const SettingsScreen = withAuthRequired(
<View style={[styles.infoLine]}>
<Text type="lg-medium" style={pal.text}>
Email:{' '}
<Text type="lg" style={pal.text}>
{store.session.currentSession?.email}
</Text>
</Text>
{!store.session.emailNeedsConfirmation && (
<>
<FontAwesomeIcon
icon="check"
size={10}
style={{color: colors.green3, marginRight: 2}}
/>
</>
)}
<Text type="lg" style={pal.text}>
{store.session.currentSession?.email}{' '}
</Text>
<Link
onPress={() => store.shell.openModal({name: 'change-email'})}>
<Text type="lg" style={pal.link}>
Change
</Text>
</Link>
</View>
<View style={[styles.infoLine]}>
<Text type="lg-medium" style={pal.text}>
@@ -238,6 +234,7 @@ export const SettingsScreen = withAuthRequired(
</Link>
</View>
<View style={styles.spacer20} />
<EmailConfirmationNotice />
</>
) : null}
<View style={[s.flexRow, styles.heading]}>
@@ -325,37 +322,45 @@ export const SettingsScreen = withAuthRequired(
<View style={styles.spacer20} />
<Text type="xl-bold" style={[pal.text, styles.heading]}>
Invite a Friend
</Text>
<TouchableOpacity
testID="inviteFriendBtn"
style={[styles.linkCard, pal.view, isSwitching && styles.dimmed]}
onPress={isSwitching ? undefined : onPressInviteCodes}
accessibilityRole="button"
accessibilityLabel="Invite"
accessibilityHint="Opens invite code list">
<View
style={[
styles.iconContainer,
store.me.invitesAvailable > 0 ? primaryBg : pal.btn,
]}>
<FontAwesomeIcon
icon="ticket"
style={
(store.me.invitesAvailable > 0
? primaryText
: pal.text) as FontAwesomeIconStyle
}
/>
</View>
<Text
type="lg"
style={store.me.invitesAvailable > 0 ? pal.link : pal.text}>
{formatCount(store.me.invitesAvailable)} invite{' '}
{pluralize(store.me.invitesAvailable, 'code')} available
</Text>
</TouchableOpacity>
{store.me.invitesAvailable !== null && (
<>
<Text type="xl-bold" style={[pal.text, styles.heading]}>
Invite a Friend
</Text>
<TouchableOpacity
testID="inviteFriendBtn"
style={[
styles.linkCard,
pal.view,
isSwitching && styles.dimmed,
]}
onPress={isSwitching ? undefined : onPressInviteCodes}
accessibilityRole="button"
accessibilityLabel="Invite"
accessibilityHint="Opens invite code list">
<View
style={[
styles.iconContainer,
store.me.invitesAvailable > 0 ? primaryBg : pal.btn,
]}>
<FontAwesomeIcon
icon="ticket"
style={
(store.me.invitesAvailable > 0
? primaryText
: pal.text) as FontAwesomeIconStyle
}
/>
</View>
<Text
type="lg"
style={store.me.invitesAvailable > 0 ? pal.link : pal.text}>
{formatCount(store.me.invitesAvailable)} invite{' '}
{pluralize(store.me.invitesAvailable, 'code')} available
</Text>
</TouchableOpacity>
</>
)}
<View style={styles.spacer20} />
@@ -630,40 +635,66 @@ export const SettingsScreen = withAuthRequired(
}),
)
function AccountDropdownBtn({handle}: {handle: string}) {
const store = useStores()
const pal = usePalette('default')
const items: DropdownItem[] = [
{
label: 'Remove account',
onPress: () => {
store.session.removeAccount(handle)
Toast.show('Account removed from quick access')
},
icon: {
ios: {
name: 'trash',
},
android: 'ic_delete',
web: 'trash',
},
},
]
return (
<Pressable accessibilityRole="button" style={s.pl10}>
<NativeDropdown
testID="accountSettingsDropdownBtn"
items={items}
accessibilityLabel="Account options"
accessibilityHint="">
<FontAwesomeIcon
icon="ellipsis-h"
style={pal.textLight as FontAwesomeIconStyle}
/>
</NativeDropdown>
</Pressable>
)
}
const EmailConfirmationNotice = observer(
function EmailConfirmationNoticeImpl() {
const pal = usePalette('default')
const palInverted = usePalette('inverted')
const store = useStores()
const {isMobile} = useWebMediaQueries()
if (!store.session.emailNeedsConfirmation) {
return null
}
return (
<View style={{marginBottom: 20}}>
<Text type="xl-bold" style={[pal.text, styles.heading]}>
Verify email
</Text>
<View
style={[
{
paddingVertical: isMobile ? 12 : 0,
paddingHorizontal: 18,
},
pal.view,
]}>
<View style={{flexDirection: 'row', marginBottom: 8}}>
<Pressable
style={[
palInverted.view,
{
flexDirection: 'row',
gap: 6,
borderRadius: 6,
paddingHorizontal: 12,
paddingVertical: 10,
alignItems: 'center',
},
isMobile && {flex: 1},
]}
accessibilityRole="button"
accessibilityLabel="Verify my email"
accessibilityHint=""
onPress={() => store.shell.openModal({name: 'verify-email'})}>
<FontAwesomeIcon
icon="envelope"
color={palInverted.colors.text}
size={16}
/>
<Text type="button" style={palInverted.text}>
Verify My Email
</Text>
</Pressable>
</View>
<Text style={pal.textLight}>
Protect your account by verifying your email.
</Text>
</View>
</View>
)
},
)
const styles = StyleSheet.create({
dimmed: {
-3
View File
@@ -11,7 +11,6 @@ export const Composer = observer(function ComposerImpl({
winHeight,
replyTo,
onPost,
onClose,
quote,
mention,
}: {
@@ -19,7 +18,6 @@ export const Composer = observer(function ComposerImpl({
winHeight: number
replyTo?: ComposerOpts['replyTo']
onPost?: ComposerOpts['onPost']
onClose: () => void
quote?: ComposerOpts['quote']
mention?: ComposerOpts['mention']
}) {
@@ -64,7 +62,6 @@ export const Composer = observer(function ComposerImpl({
<ComposePost
replyTo={replyTo}
onPost={onPost}
onClose={onClose}
quote={quote}
mention={mention}
/>
-3
View File
@@ -13,7 +13,6 @@ export const Composer = observer(function ComposerImpl({
replyTo,
quote,
onPost,
onClose,
mention,
}: {
active: boolean
@@ -21,7 +20,6 @@ export const Composer = observer(function ComposerImpl({
replyTo?: ComposerOpts['replyTo']
quote: ComposerOpts['quote']
onPost?: ComposerOpts['onPost']
onClose: () => void
mention?: ComposerOpts['mention']
}) {
const pal = usePalette('default')
@@ -47,7 +45,6 @@ export const Composer = observer(function ComposerImpl({
replyTo={replyTo}
quote={quote}
onPost={onPost}
onClose={onClose}
mention={mention}
/>
</View>
+29 -26
View File
@@ -273,6 +273,7 @@ export const DrawerContent = observer(function DrawerContentImpl() {
label="Feeds"
accessibilityLabel="Feeds"
accessibilityHint=""
bold={isAtFeeds}
onPress={onPressMyFeeds}
/>
<MenuItem
@@ -425,32 +426,34 @@ const InviteCodes = observer(function InviteCodesImpl({
store.shell.openModal({name: 'invite-codes'})
}, [store, track])
return (
<TouchableOpacity
testID="menuItemInviteCodes"
style={[styles.inviteCodes, style]}
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={
invitesAvailable === 1
? 'Invite codes: 1 available'
: `Invite codes: ${invitesAvailable} available`
}
accessibilityHint="Opens list of invite codes">
<FontAwesomeIcon
icon="ticket"
style={[
styles.inviteCodesIcon,
store.me.invitesAvailable > 0 ? pal.link : pal.textLight,
]}
size={18}
/>
<Text
type="lg-medium"
style={store.me.invitesAvailable > 0 ? pal.link : pal.textLight}>
{formatCount(store.me.invitesAvailable)} invite{' '}
{pluralize(store.me.invitesAvailable, 'code')}
</Text>
</TouchableOpacity>
store.me.invitesAvailable !== null && (
<TouchableOpacity
testID="menuItemInviteCodes"
style={[styles.inviteCodes, style]}
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={
invitesAvailable === 1
? 'Invite codes: 1 available'
: `Invite codes: ${invitesAvailable} available`
}
accessibilityHint="Opens list of invite codes">
<FontAwesomeIcon
icon="ticket"
style={[
styles.inviteCodesIcon,
store.me.invitesAvailable > 0 ? pal.link : pal.textLight,
]}
size={18}
/>
<Text
type="lg-medium"
style={store.me.invitesAvailable > 0 ? pal.link : pal.textLight}>
{formatCount(store.me.invitesAvailable)} invite{' '}
{pluralize(store.me.invitesAvailable, 'code')}
</Text>
</TouchableOpacity>
)
)
})
+4
View File
@@ -75,6 +75,9 @@ export const BottomBar = observer(function BottomBarImpl({
const onPressProfile = React.useCallback(() => {
onPressTab('MyProfile')
}, [onPressTab])
const onLongPressProfile = React.useCallback(() => {
store.shell.openModal({name: 'switch-account'})
}, [store])
return (
<Animated.View
@@ -202,6 +205,7 @@ export const BottomBar = observer(function BottomBarImpl({
</View>
}
onPress={onPressProfile}
onLongPress={onLongPressProfile}
accessibilityRole="tab"
accessibilityLabel="Profile"
accessibilityHint=""
+6 -1
View File
@@ -109,7 +109,12 @@ const NavItem: React.FC<{
href: string
routeName: string
}> = ({children, href, routeName}) => {
const currentRoute = useNavigationState(getCurrentRoute)
const currentRoute = useNavigationState(state => {
if (!state) {
return {name: 'Home'}
}
return getCurrentRoute(state)
})
const store = useStores()
const isActive =
currentRoute.name === 'Profile'
+3 -2
View File
@@ -82,11 +82,12 @@ function FeedItem({
const styles = StyleSheet.create({
container: {
position: 'relative',
flex: 1,
overflowY: 'auto',
width: 300,
paddingHorizontal: 12,
paddingVertical: 18,
borderTopWidth: 1,
borderBottomWidth: 1,
paddingVertical: 18,
},
})
+1 -1
View File
@@ -42,7 +42,7 @@ import {makeProfileLink} from 'lib/routes/links'
const ProfileCard = observer(function ProfileCardImpl() {
const store = useStores()
const {isDesktop} = useWebMediaQueries()
const size = isDesktop ? 64 : 48
const size = 48
return store.me.handle ? (
<Link
href={makeProfileLink(store.me)}
+46 -30
View File
@@ -7,6 +7,7 @@ import {DesktopSearch} from './Search'
import {DesktopFeeds} from './Feeds'
import {Text} from 'view/com/util/text/Text'
import {TextLink} from 'view/com/util/Link'
import {LoadingPlaceholder} from 'view/com/util/LoadingPlaceholder'
import {FEEDBACK_FORM_URL, HELP_DESK_URL} from 'lib/constants'
import {s} from 'lib/styles'
import {useStores} from 'state/index'
@@ -89,32 +90,41 @@ const InviteCodes = observer(function InviteCodesImpl() {
const onPress = React.useCallback(() => {
store.shell.openModal({name: 'invite-codes'})
}, [store])
return (
<TouchableOpacity
style={[styles.inviteCodes, pal.border]}
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={
invitesAvailable === 1
? 'Invite codes: 1 available'
: `Invite codes: ${invitesAvailable} available`
}
accessibilityHint="Opens list of invite codes">
<FontAwesomeIcon
icon="ticket"
style={[
styles.inviteCodesIcon,
store.me.invitesAvailable > 0 ? pal.link : pal.textLight,
]}
size={16}
/>
<Text
type="md-medium"
style={store.me.invitesAvailable > 0 ? pal.link : pal.textLight}>
{formatCount(store.me.invitesAvailable)} invite{' '}
{pluralize(store.me.invitesAvailable, 'code')} available
</Text>
</TouchableOpacity>
<View style={[styles.separator, pal.border]}>
{store.me.invitesAvailable === null ? (
<View style={[s.p10]}>
<LoadingPlaceholder width={186} height={32} style={[styles.br40]} />
</View>
) : (
<TouchableOpacity
style={[styles.inviteCodes]}
onPress={onPress}
accessibilityRole="button"
accessibilityLabel={
invitesAvailable === 1
? 'Invite codes: 1 available'
: `Invite codes: ${invitesAvailable} available`
}
accessibilityHint="Opens list of invite codes">
<FontAwesomeIcon
icon="ticket"
style={[
styles.inviteCodesIcon,
store.me.invitesAvailable > 0 ? pal.link : pal.textLight,
]}
size={16}
/>
<Text
type="md-medium"
style={store.me.invitesAvailable > 0 ? pal.link : pal.textLight}>
{formatCount(store.me.invitesAvailable)} invite{' '}
{pluralize(store.me.invitesAvailable, 'code')} available
</Text>
</TouchableOpacity>
)}
</View>
)
})
@@ -123,22 +133,28 @@ const styles = StyleSheet.create({
position: 'absolute',
top: 20,
// @ts-ignore web only
left: 'calc(50vw + 310px)',
left: 'calc(50vw + 320px)',
width: 304,
// @ts-ignore web only
maxHeight: '90vh',
},
message: {
paddingVertical: 18,
paddingHorizontal: 10,
paddingHorizontal: 12,
},
messageLine: {
marginBottom: 10,
},
inviteCodes: {
separator: {
borderTopWidth: 1,
paddingHorizontal: 16,
paddingVertical: 12,
},
br40: {borderRadius: 40},
inviteCodes: {
paddingHorizontal: 12,
paddingVertical: 16,
flexDirection: 'row',
alignItems: 'center',
},
+2 -2
View File
@@ -90,9 +90,9 @@ export const DesktopSearch = observer(function DesktopSearch() {
{query !== '' && (
<View style={[pal.view, pal.borderDark, styles.resultsContainer]}>
{autocompleteView.searchRes.length ? (
{autocompleteView.suggestions.length ? (
<>
{autocompleteView.searchRes.map((item, i) => (
{autocompleteView.suggestions.map((item, i) => (
<ProfileCard key={item.did} profile={item} noBorder={i === 0} />
))}
</>
+4 -2
View File
@@ -44,7 +44,10 @@ const ShellInner = observer(function ShellInnerImpl() {
)
const canGoBack = useNavigationState(state => !isStateAtTabRoot(state))
React.useEffect(() => {
backHandler.init(store)
const listener = backHandler.init(store)
return () => {
listener()
}
}, [store])
return (
@@ -68,7 +71,6 @@ const ShellInner = observer(function ShellInnerImpl() {
</View>
<Composer
active={store.shell.isComposerActive}
onClose={() => store.shell.closeComposer()}
winHeight={winDim.height}
replyTo={store.shell.composerOpts?.replyTo}
onPost={store.shell.composerOpts?.onPost}
-1
View File
@@ -48,7 +48,6 @@ const ShellInner = observer(function ShellInnerImpl() {
)}
<Composer
active={store.shell.isComposerActive}
onClose={() => store.shell.closeComposer()}
winHeight={0}
replyTo={store.shell.composerOpts?.replyTo}
quote={store.shell.composerOpts?.quote}