Remove SCREEN from lightbox layout (#6124)

* Assign an ID to lightbox and use it as a key

* Consolidate lightbox props into an object

* Remove unused prop

* Move SafeAreaView declaration

* Keep SafeAreaView always mounted

When exploring Android animation, I noticed its content jumps on the first frame. I think this should help prevent that.

* Pass safe area down for measurement

* Remove dependency on SCREEN in Android event handlers

* Remove dependency on SCREEN in iOS event handlers

* Remove dependency on SCREEN on iOS

* Remove dependency on SCREEN on Android

* Remove dependency on JS calc in controls

* Use flex for iOS layout
This commit is contained in:
dan
2024-11-06 00:21:35 +00:00
committed by GitHub
parent 6b826fb88d
commit 206df2ab80
6 changed files with 281 additions and 232 deletions
+9 -5
View File
@@ -1,10 +1,12 @@
import React from 'react' import React from 'react'
import type {MeasuredDimensions} from 'react-native-reanimated' import type {MeasuredDimensions} from 'react-native-reanimated'
import {nanoid} from 'nanoid/non-secure'
import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback'
import {ImageSource} from '#/view/com/lightbox/ImageViewing/@types' import {ImageSource} from '#/view/com/lightbox/ImageViewing/@types'
type Lightbox = { export type Lightbox = {
id: string
images: ImageSource[] images: ImageSource[]
thumbDims: MeasuredDimensions | null thumbDims: MeasuredDimensions | null
index: number index: number
@@ -17,7 +19,7 @@ const LightboxContext = React.createContext<{
}) })
const LightboxControlContext = React.createContext<{ const LightboxControlContext = React.createContext<{
openLightbox: (lightbox: Lightbox) => void openLightbox: (lightbox: Omit<Lightbox, 'id'>) => void
closeLightbox: () => boolean closeLightbox: () => boolean
}>({ }>({
openLightbox: () => {}, openLightbox: () => {},
@@ -29,9 +31,11 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
null, null,
) )
const openLightbox = useNonReactiveCallback((lightbox: Lightbox) => { const openLightbox = useNonReactiveCallback(
setActiveLightbox(lightbox) (lightbox: Omit<Lightbox, 'id'>) => {
}) setActiveLightbox({...lightbox, id: nanoid()})
},
)
const closeLightbox = useNonReactiveCallback(() => { const closeLightbox = useNonReactiveCallback(() => {
let wasActive = !!activeLightbox let wasActive = !!activeLightbox
@@ -1,7 +1,9 @@
import React, {useState} from 'react' import React, {useState} from 'react'
import {ActivityIndicator, Dimensions, StyleSheet} from 'react-native' import {ActivityIndicator, StyleSheet, View} from 'react-native'
import {Gesture, GestureDetector} from 'react-native-gesture-handler' import {Gesture, GestureDetector} from 'react-native-gesture-handler'
import Animated, { import Animated, {
AnimatedRef,
measure,
runOnJS, runOnJS,
useAnimatedReaction, useAnimatedReaction,
useAnimatedRef, useAnimatedRef,
@@ -24,13 +26,6 @@ import {
TransformMatrix, TransformMatrix,
} from '../../transforms' } from '../../transforms'
const windowDim = Dimensions.get('window')
const screenDim = Dimensions.get('screen')
const statusBarHeight = windowDim.height - screenDim.height
const SCREEN = {
width: windowDim.width,
height: windowDim.height + statusBarHeight,
}
const MIN_DOUBLE_TAP_SCALE = 2 const MIN_DOUBLE_TAP_SCALE = 2
const MAX_ORIGINAL_IMAGE_ZOOM = 2 const MAX_ORIGINAL_IMAGE_ZOOM = 2
@@ -43,6 +38,7 @@ type Props = {
onZoom: (isZoomed: boolean) => void onZoom: (isZoomed: boolean) => void
isScrollViewBeingDragged: boolean isScrollViewBeingDragged: boolean
showControls: boolean showControls: boolean
safeAreaRef: AnimatedRef<View>
} }
const ImageItem = ({ const ImageItem = ({
imageSrc, imageSrc,
@@ -50,6 +46,7 @@ const ImageItem = ({
onZoom, onZoom,
onRequestClose, onRequestClose,
isScrollViewBeingDragged, isScrollViewBeingDragged,
safeAreaRef,
}: Props) => { }: Props) => {
const [isScaled, setIsScaled] = useState(false) const [isScaled, setIsScaled] = useState(false)
const [imageAspect, imageDimensions] = useImageDimensions({ const [imageAspect, imageDimensions] = useImageDimensions({
@@ -102,10 +99,10 @@ const ImageItem = ({
const [translateX, translateY, scale] = readTransform(t) const [translateX, translateY, scale] = readTransform(t)
const dismissDistance = dismissSwipeTranslateY.value const dismissDistance = dismissSwipeTranslateY.value
const dismissProgress = Math.min( const screenSize = measure(safeAreaRef)
Math.abs(dismissDistance) / (SCREEN.height / 2), const dismissProgress = screenSize
1, ? Math.min(Math.abs(dismissDistance) / (screenSize.height / 2), 1)
) : 0
return { return {
opacity: 1 - dismissProgress, opacity: 1 - dismissProgress,
transform: [ transform: [
@@ -120,6 +117,7 @@ const ImageItem = ({
// If the user tried to pan too hard, this function will provide the negative panning to stay in bounds. // If the user tried to pan too hard, this function will provide the negative panning to stay in bounds.
function getExtraTranslationToStayInBounds( function getExtraTranslationToStayInBounds(
candidateTransform: TransformMatrix, candidateTransform: TransformMatrix,
screenSize: {width: number; height: number},
) { ) {
'worklet' 'worklet'
if (!imageAspect) { if (!imageAspect) {
@@ -127,16 +125,20 @@ const ImageItem = ({
} }
const [nextTranslateX, nextTranslateY, nextScale] = const [nextTranslateX, nextTranslateY, nextScale] =
readTransform(candidateTransform) readTransform(candidateTransform)
const scaledDimensions = getScaledDimensions(imageAspect, nextScale) const scaledDimensions = getScaledDimensions(
imageAspect,
nextScale,
screenSize,
)
const clampedTranslateX = clampTranslation( const clampedTranslateX = clampTranslation(
nextTranslateX, nextTranslateX,
scaledDimensions.width, scaledDimensions.width,
SCREEN.width, screenSize.width,
) )
const clampedTranslateY = clampTranslation( const clampedTranslateY = clampTranslation(
nextTranslateY, nextTranslateY,
scaledDimensions.height, scaledDimensions.height,
SCREEN.height, screenSize.height,
) )
const dx = clampedTranslateX - nextTranslateX const dx = clampedTranslateX - nextTranslateX
const dy = clampedTranslateY - nextTranslateY const dy = clampedTranslateY - nextTranslateY
@@ -146,21 +148,26 @@ const ImageItem = ({
const pinch = Gesture.Pinch() const pinch = Gesture.Pinch()
.onStart(e => { .onStart(e => {
'worklet' 'worklet'
const screenSize = measure(safeAreaRef)
if (!screenSize) {
return
}
pinchOrigin.value = { pinchOrigin.value = {
x: e.focalX - SCREEN.width / 2, x: e.focalX - screenSize.width / 2,
y: e.focalY - SCREEN.height / 2, y: e.focalY - screenSize.height / 2,
} }
}) })
.onChange(e => { .onChange(e => {
'worklet' 'worklet'
if (!imageDimensions) { const screenSize = measure(safeAreaRef)
if (!imageDimensions || !screenSize) {
return return
} }
// Don't let the picture zoom in so close that it gets blurry. // 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. // Also, like in stock Android apps, don't let the user zoom out further than 1:1.
const [, , committedScale] = readTransform(committedTransform.value) const [, , committedScale] = readTransform(committedTransform.value)
const maxCommittedScale = const maxCommittedScale =
(imageDimensions.width / SCREEN.width) * MAX_ORIGINAL_IMAGE_ZOOM (imageDimensions.width / screenSize.width) * MAX_ORIGINAL_IMAGE_ZOOM
const minPinchScale = 1 / committedScale const minPinchScale = 1 / committedScale
const maxPinchScale = maxCommittedScale / committedScale const maxPinchScale = maxCommittedScale / committedScale
const nextPinchScale = Math.min( const nextPinchScale = Math.min(
@@ -175,7 +182,7 @@ const ImageItem = ({
prependPan(t, panTranslation.value) prependPan(t, panTranslation.value)
prependPinch(t, nextPinchScale, pinchOrigin.value, pinchTranslation.value) prependPinch(t, nextPinchScale, pinchOrigin.value, pinchTranslation.value)
prependTransform(t, committedTransform.value) prependTransform(t, committedTransform.value)
const [dx, dy] = getExtraTranslationToStayInBounds(t) const [dx, dy] = getExtraTranslationToStayInBounds(t, screenSize)
if (dx !== 0 || dy !== 0) { if (dx !== 0 || dy !== 0) {
pinchTranslation.value = { pinchTranslation.value = {
x: pinchTranslation.value.x + dx, x: pinchTranslation.value.x + dx,
@@ -209,9 +216,11 @@ const ImageItem = ({
.minPointers(isScaled ? 1 : 2) .minPointers(isScaled ? 1 : 2)
.onChange(e => { .onChange(e => {
'worklet' 'worklet'
if (!imageDimensions) { const screenSize = measure(safeAreaRef)
if (!imageDimensions || !screenSize) {
return return
} }
const nextPanTranslation = {x: e.translationX, y: e.translationY} const nextPanTranslation = {x: e.translationX, y: e.translationY}
let t = createTransform() let t = createTransform()
prependPan(t, nextPanTranslation) prependPan(t, nextPanTranslation)
@@ -224,7 +233,7 @@ const ImageItem = ({
prependTransform(t, committedTransform.value) prependTransform(t, committedTransform.value)
// Prevent panning from going out of bounds. // Prevent panning from going out of bounds.
const [dx, dy] = getExtraTranslationToStayInBounds(t) const [dx, dy] = getExtraTranslationToStayInBounds(t, screenSize)
nextPanTranslation.x += dx nextPanTranslation.x += dx
nextPanTranslation.y += dy nextPanTranslation.y += dy
panTranslation.value = nextPanTranslation panTranslation.value = nextPanTranslation
@@ -251,7 +260,8 @@ const ImageItem = ({
.numberOfTaps(2) .numberOfTaps(2)
.onEnd(e => { .onEnd(e => {
'worklet' 'worklet'
if (!imageDimensions || !imageAspect) { const screenSize = measure(safeAreaRef)
if (!imageDimensions || !imageAspect || !screenSize) {
return return
} }
const [, , committedScale] = readTransform(committedTransform.value) const [, , committedScale] = readTransform(committedTransform.value)
@@ -263,7 +273,7 @@ const ImageItem = ({
} }
// Try to zoom in so that we get rid of the black bars (whatever the orientation was). // Try to zoom in so that we get rid of the black bars (whatever the orientation was).
const screenAspect = SCREEN.width / SCREEN.height const screenAspect = screenSize.width / screenSize.height
const candidateScale = Math.max( const candidateScale = Math.max(
imageAspect / screenAspect, imageAspect / screenAspect,
screenAspect / imageAspect, screenAspect / imageAspect,
@@ -271,20 +281,23 @@ const ImageItem = ({
) )
// But don't zoom in so close that the picture gets blurry. // But don't zoom in so close that the picture gets blurry.
const maxScale = const maxScale =
(imageDimensions.width / SCREEN.width) * MAX_ORIGINAL_IMAGE_ZOOM (imageDimensions.width / screenSize.width) * MAX_ORIGINAL_IMAGE_ZOOM
const scale = Math.min(candidateScale, maxScale) const scale = Math.min(candidateScale, maxScale)
// Calculate where we would be if the user pinched into the double tapped point. // 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. // We won't use this transform directly because it may go out of bounds.
const candidateTransform = createTransform() const candidateTransform = createTransform()
const origin = { const origin = {
x: e.absoluteX - SCREEN.width / 2, x: e.absoluteX - screenSize.width / 2,
y: e.absoluteY - SCREEN.height / 2, y: e.absoluteY - screenSize.height / 2,
} }
prependPinch(candidateTransform, scale, origin, {x: 0, y: 0}) prependPinch(candidateTransform, scale, origin, {x: 0, y: 0})
// Now we know how much we went out of bounds, so we can shoot correctly. // Now we know how much we went out of bounds, so we can shoot correctly.
const [dx, dy] = getExtraTranslationToStayInBounds(candidateTransform) const [dx, dy] = getExtraTranslationToStayInBounds(
candidateTransform,
screenSize,
)
const finalTransform = createTransform() const finalTransform = createTransform()
prependPinch(finalTransform, scale, origin, {x: dx, y: dy}) prependPinch(finalTransform, scale, origin, {x: dx, y: dy})
committedTransform.value = withClampedSpring(finalTransform) committedTransform.value = withClampedSpring(finalTransform)
@@ -348,8 +361,7 @@ const ImageItem = ({
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
width: SCREEN.width, height: '100%',
height: SCREEN.height,
overflow: 'hidden', overflow: 'hidden',
}, },
image: { image: {
@@ -367,19 +379,20 @@ const styles = StyleSheet.create({
function getScaledDimensions( function getScaledDimensions(
imageAspect: number, imageAspect: number,
scale: number, scale: number,
screenSize: {width: number; height: number},
): ImageDimensions { ): ImageDimensions {
'worklet' 'worklet'
const screenAspect = SCREEN.width / SCREEN.height const screenAspect = screenSize.width / screenSize.height
const isLandscape = imageAspect > screenAspect const isLandscape = imageAspect > screenAspect
if (isLandscape) { if (isLandscape) {
return { return {
width: scale * SCREEN.width, width: scale * screenSize.width,
height: (scale * SCREEN.width) / imageAspect, height: (scale * screenSize.width) / imageAspect,
} }
} else { } else {
return { return {
width: scale * SCREEN.height * imageAspect, width: scale * screenSize.height * imageAspect,
height: scale * SCREEN.height, height: scale * screenSize.height,
} }
} }
} }
@@ -7,15 +7,18 @@
*/ */
import React, {useState} from 'react' import React, {useState} from 'react'
import {ActivityIndicator, Dimensions, StyleSheet} from 'react-native' import {ActivityIndicator, StyleSheet, View} from 'react-native'
import {Gesture, GestureDetector} from 'react-native-gesture-handler' import {Gesture, GestureDetector} from 'react-native-gesture-handler'
import Animated, { import Animated, {
AnimatedRef,
interpolate, interpolate,
measure,
runOnJS, runOnJS,
useAnimatedRef, useAnimatedRef,
useAnimatedStyle, useAnimatedStyle,
useSharedValue, useSharedValue,
} from 'react-native-reanimated' } from 'react-native-reanimated'
import {useSafeAreaFrame} from 'react-native-safe-area-context'
import {Image} from 'expo-image' import {Image} from 'expo-image'
import {useAnimatedScrollHandler} from '#/lib/hooks/useAnimatedScrollHandler_FIXED' import {useAnimatedScrollHandler} from '#/lib/hooks/useAnimatedScrollHandler_FIXED'
@@ -24,7 +27,6 @@ import {ImageSource} from '../../@types'
const SWIPE_CLOSE_OFFSET = 75 const SWIPE_CLOSE_OFFSET = 75
const SWIPE_CLOSE_VELOCITY = 1 const SWIPE_CLOSE_VELOCITY = 1
const SCREEN = Dimensions.get('screen')
const MAX_ORIGINAL_IMAGE_ZOOM = 2 const MAX_ORIGINAL_IMAGE_ZOOM = 2
const MIN_DOUBLE_TAP_SCALE = 2 const MIN_DOUBLE_TAP_SCALE = 2
@@ -35,6 +37,7 @@ type Props = {
onZoom: (scaled: boolean) => void onZoom: (scaled: boolean) => void
isScrollViewBeingDragged: boolean isScrollViewBeingDragged: boolean
showControls: boolean showControls: boolean
safeAreaRef: AnimatedRef<View>
} }
const ImageItem = ({ const ImageItem = ({
@@ -43,20 +46,24 @@ const ImageItem = ({
onZoom, onZoom,
onRequestClose, onRequestClose,
showControls, showControls,
safeAreaRef,
}: Props) => { }: Props) => {
const scrollViewRef = useAnimatedRef<Animated.ScrollView>() const scrollViewRef = useAnimatedRef<Animated.ScrollView>()
const translationY = useSharedValue(0) const translationY = useSharedValue(0)
const [scaled, setScaled] = useState(false) const [scaled, setScaled] = useState(false)
const screenSizeDelayedForJSThreadOnly = useSafeAreaFrame()
const [imageAspect, imageDimensions] = useImageDimensions({ const [imageAspect, imageDimensions] = useImageDimensions({
src: imageSrc.uri, src: imageSrc.uri,
knownDimensions: imageSrc.dimensions, knownDimensions: imageSrc.dimensions,
}) })
const maxZoomScale = imageDimensions const maxZoomScale = imageDimensions
? (imageDimensions.width / SCREEN.width) * MAX_ORIGINAL_IMAGE_ZOOM ? (imageDimensions.width / screenSizeDelayedForJSThreadOnly.width) *
MAX_ORIGINAL_IMAGE_ZOOM
: 1 : 1
const animatedStyle = useAnimatedStyle(() => { const animatedStyle = useAnimatedStyle(() => {
return { return {
flex: 1,
opacity: interpolate( opacity: interpolate(
translationY.value, translationY.value,
[-SWIPE_CLOSE_OFFSET, 0, SWIPE_CLOSE_OFFSET], [-SWIPE_CLOSE_OFFSET, 0, SWIPE_CLOSE_OFFSET],
@@ -90,24 +97,13 @@ const ImageItem = ({
setScaled(nextIsScaled) setScaled(nextIsScaled)
} }
function handleDoubleTap(absoluteX: number, absoluteY: number) { function zoomTo(nextZoomRect: {
x: number
y: number
width: number
height: number
}) {
const scrollResponderRef = scrollViewRef?.current?.getScrollResponder() const scrollResponderRef = scrollViewRef?.current?.getScrollResponder()
let nextZoomRect = {
x: 0,
y: 0,
width: SCREEN.width,
height: SCREEN.height,
}
const willZoom = !scaled
if (willZoom) {
nextZoomRect = getZoomRectAfterDoubleTap(
imageAspect,
absoluteX,
absoluteY,
)
}
// @ts-ignore // @ts-ignore
scrollResponderRef?.scrollResponderZoomTo({ scrollResponderRef?.scrollResponderZoomTo({
...nextZoomRect, // This rect is in screen coordinates ...nextZoomRect, // This rect is in screen coordinates
@@ -124,8 +120,27 @@ const ImageItem = ({
.numberOfTaps(2) .numberOfTaps(2)
.onEnd(e => { .onEnd(e => {
'worklet' 'worklet'
const screenSize = measure(safeAreaRef)
if (!screenSize) {
return
}
const {absoluteX, absoluteY} = e const {absoluteX, absoluteY} = e
runOnJS(handleDoubleTap)(absoluteX, absoluteY) let nextZoomRect = {
x: 0,
y: 0,
width: screenSize.width,
height: screenSize.height,
}
const willZoom = !scaled
if (willZoom) {
nextZoomRect = getZoomRectAfterDoubleTap(
imageAspect,
absoluteX,
absoluteY,
screenSize,
)
}
runOnJS(zoomTo)(nextZoomRect)
}) })
const composedGesture = Gesture.Exclusive(doubleTap, singleTap) const composedGesture = Gesture.Exclusive(doubleTap, singleTap)
@@ -135,13 +150,13 @@ const ImageItem = ({
<Animated.ScrollView <Animated.ScrollView
// @ts-ignore Something's up with the types here // @ts-ignore Something's up with the types here
ref={scrollViewRef} ref={scrollViewRef}
style={styles.listItem}
pinchGestureEnabled pinchGestureEnabled
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false} showsVerticalScrollIndicator={false}
maximumZoomScale={maxZoomScale} maximumZoomScale={maxZoomScale}
onScroll={scrollHandler}> onScroll={scrollHandler}
<Animated.View style={[styles.imageScrollContainer, animatedStyle]}> contentContainerStyle={styles.scrollContainer}>
<Animated.View style={animatedStyle}>
<ActivityIndicator size="small" color="#FFF" style={styles.loading} /> <ActivityIndicator size="small" color="#FFF" style={styles.loading} />
<Image <Image
contentFit="contain" contentFit="contain"
@@ -161,17 +176,6 @@ const ImageItem = ({
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
imageScrollContainer: {
height: SCREEN.height,
},
listItem: {
width: SCREEN.width,
height: SCREEN.height,
},
image: {
width: SCREEN.width,
height: SCREEN.height,
},
loading: { loading: {
position: 'absolute', position: 'absolute',
top: 0, top: 0,
@@ -179,30 +183,38 @@ const styles = StyleSheet.create({
right: 0, right: 0,
bottom: 0, bottom: 0,
}, },
scrollContainer: {
flex: 1,
},
image: {
flex: 1,
},
}) })
const getZoomRectAfterDoubleTap = ( const getZoomRectAfterDoubleTap = (
imageAspect: number | undefined, imageAspect: number | undefined,
touchX: number, touchX: number,
touchY: number, touchY: number,
screenSize: {width: number; height: number},
): { ): {
x: number x: number
y: number y: number
width: number width: number
height: number height: number
} => { } => {
'worklet'
if (!imageAspect) { if (!imageAspect) {
return { return {
x: 0, x: 0,
y: 0, y: 0,
width: SCREEN.width, width: screenSize.width,
height: SCREEN.height, height: screenSize.height,
} }
} }
// First, let's figure out how much we want to zoom in. // 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. // We want to try to zoom in at least close enough to get rid of black bars.
const screenAspect = SCREEN.width / SCREEN.height const screenAspect = screenSize.width / screenSize.height
const zoom = Math.max( const zoom = Math.max(
imageAspect / screenAspect, imageAspect / screenAspect,
screenAspect / imageAspect, screenAspect / imageAspect,
@@ -213,25 +225,25 @@ const getZoomRectAfterDoubleTap = (
// Next, we'll be calculating the rectangle to "zoom into" in screen coordinates. // 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. // We already know the zoom level, so this gives us the rectangle size.
let rectWidth = SCREEN.width / zoom let rectWidth = screenSize.width / zoom
let rectHeight = SCREEN.height / zoom let rectHeight = screenSize.height / zoom
// Before we settle on the zoomed rect, figure out the safe area it has to be inside. // 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. // We don't want to introduce new black bars or make existing black bars unbalanced.
let minX = 0 let minX = 0
let minY = 0 let minY = 0
let maxX = SCREEN.width - rectWidth let maxX = screenSize.width - rectWidth
let maxY = SCREEN.height - rectHeight let maxY = screenSize.height - rectHeight
if (imageAspect >= screenAspect) { if (imageAspect >= screenAspect) {
// The image has horizontal black bars. Exclude them from the safe area. // The image has horizontal black bars. Exclude them from the safe area.
const renderedHeight = SCREEN.width / imageAspect const renderedHeight = screenSize.width / imageAspect
const horizontalBarHeight = (SCREEN.height - renderedHeight) / 2 const horizontalBarHeight = (screenSize.height - renderedHeight) / 2
minY += horizontalBarHeight minY += horizontalBarHeight
maxY -= horizontalBarHeight maxY -= horizontalBarHeight
} else { } else {
// The image has vertical black bars. Exclude them from the safe area. // The image has vertical black bars. Exclude them from the safe area.
const renderedWidth = SCREEN.height * imageAspect const renderedWidth = screenSize.height * imageAspect
const verticalBarWidth = (SCREEN.width - renderedWidth) / 2 const verticalBarWidth = (screenSize.width - renderedWidth) / 2
minX += verticalBarWidth minX += verticalBarWidth
maxX -= verticalBarWidth maxX -= verticalBarWidth
} }
@@ -246,7 +258,7 @@ const getZoomRectAfterDoubleTap = (
rectX = Math.max(rectX, minX) rectX = Math.max(rectX, minX)
} else { } else {
// Keep the rect centered on the screen so that black bars are balanced. // Keep the rect centered on the screen so that black bars are balanced.
rectX = SCREEN.width / 2 - rectWidth / 2 rectX = screenSize.width / 2 - rectWidth / 2
} }
let rectY let rectY
if (maxY >= minY) { if (maxY >= minY) {
@@ -257,7 +269,7 @@ const getZoomRectAfterDoubleTap = (
rectY = Math.max(rectY, minY) rectY = Math.max(rectY, minY)
} else { } else {
// Keep the rect centered on the screen so that black bars are balanced. // Keep the rect centered on the screen so that black bars are balanced.
rectY = SCREEN.height / 2 - rectHeight / 2 rectY = screenSize.height / 2 - rectHeight / 2
} }
return { return {
@@ -2,6 +2,7 @@
import React from 'react' import React from 'react'
import {View} from 'react-native' import {View} from 'react-native'
import {AnimatedRef} from 'react-native-reanimated'
import {ImageSource} from '../../@types' import {ImageSource} from '../../@types'
@@ -12,6 +13,7 @@ type Props = {
onZoom: (scaled: boolean) => void onZoom: (scaled: boolean) => void
isScrollViewBeingDragged: boolean isScrollViewBeingDragged: boolean
showControls: boolean showControls: boolean
safeAreaRef: AnimatedRef<View>
} }
const ImageItem = (_props: Props) => { const ImageItem = (_props: Props) => {
+161 -136
View File
@@ -8,24 +8,22 @@
// Original code copied and simplified from the link below as the codebase is currently not maintained: // Original code copied and simplified from the link below as the codebase is currently not maintained:
// https://github.com/jobtoday/react-native-image-viewing // https://github.com/jobtoday/react-native-image-viewing
import React, {useCallback, useMemo, useState} from 'react' import React, {useCallback, useState} from 'react'
import { import {LayoutAnimation, Platform, StyleSheet, View} from 'react-native'
Dimensions,
LayoutAnimation,
Platform,
StyleSheet,
View,
} from 'react-native'
import PagerView from 'react-native-pager-view' import PagerView from 'react-native-pager-view'
import {MeasuredDimensions} from 'react-native-reanimated' import Animated, {
import Animated, {useAnimatedStyle, withSpring} from 'react-native-reanimated' AnimatedRef,
import {useSafeAreaInsets} from 'react-native-safe-area-context' useAnimatedRef,
useAnimatedStyle,
withSpring,
} from 'react-native-reanimated'
import {Edge, SafeAreaView} from 'react-native-safe-area-context' import {Edge, SafeAreaView} from 'react-native-safe-area-context'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome' import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {Trans} from '@lingui/macro' import {Trans} from '@lingui/macro'
import {colors, s} from '#/lib/styles' import {colors, s} from '#/lib/styles'
import {isIOS} from '#/platform/detection' import {isIOS} from '#/platform/detection'
import {Lightbox} from '#/state/lightbox'
import {Button} from '#/view/com/util/forms/Button' import {Button} from '#/view/com/util/forms/Button'
import {Text} from '#/view/com/util/text/Text' import {Text} from '#/view/com/util/text/Text'
import {ScrollView} from '#/view/com/util/Views' import {ScrollView} from '#/view/com/util/Views'
@@ -33,37 +31,68 @@ import {ImageSource} from './@types'
import ImageDefaultHeader from './components/ImageDefaultHeader' import ImageDefaultHeader from './components/ImageDefaultHeader'
import ImageItem from './components/ImageItem/ImageItem' import ImageItem from './components/ImageItem/ImageItem'
type Props = { const EDGES =
images: ImageSource[] Platform.OS === 'android'
thumbDims: MeasuredDimensions | null ? (['top', 'bottom', 'left', 'right'] satisfies Edge[])
initialImageIndex: number : (['left', 'right'] satisfies Edge[]) // iOS, so no top/bottom safe area
visible: boolean
onRequestClose: () => void
backgroundColor?: string
onPressSave: (uri: string) => void
onPressShare: (uri: string) => void
}
const SCREEN_HEIGHT = Dimensions.get('window').height export default function ImageViewRoot({
const DEFAULT_BG_COLOR = '#000' lightbox,
function ImageViewing({
images,
thumbDims: _thumbDims, // TODO: Pass down and use for animation.
initialImageIndex,
visible,
onRequestClose, onRequestClose,
backgroundColor = DEFAULT_BG_COLOR,
onPressSave, onPressSave,
onPressShare, onPressShare,
}: Props) { }: {
lightbox: Lightbox | null
onRequestClose: () => void
onPressSave: (uri: string) => void
onPressShare: (uri: string) => void
}) {
const ref = useAnimatedRef<View>()
return (
// Keep it always mounted to avoid flicker on the first frame.
<SafeAreaView
style={[styles.screen, !lightbox && styles.screenHidden]}
edges={EDGES}
aria-modal
accessibilityViewIsModal
aria-hidden={!lightbox}>
<Animated.View ref={ref} style={{flex: 1}} collapsable={false}>
{lightbox && (
<ImageView
key={lightbox.id}
lightbox={lightbox}
onRequestClose={onRequestClose}
onPressSave={onPressSave}
onPressShare={onPressShare}
safeAreaRef={ref}
/>
)}
</Animated.View>
</SafeAreaView>
)
}
function ImageView({
lightbox,
onRequestClose,
onPressSave,
onPressShare,
safeAreaRef,
}: {
lightbox: Lightbox
onRequestClose: () => void
onPressSave: (uri: string) => void
onPressShare: (uri: string) => void
safeAreaRef: AnimatedRef<View>
}) {
const {images, index: initialImageIndex} = lightbox
const [isScaled, setIsScaled] = useState(false) const [isScaled, setIsScaled] = useState(false)
const [isDragging, setIsDragging] = useState(false) const [isDragging, setIsDragging] = useState(false)
const [imageIndex, setImageIndex] = useState(initialImageIndex) const [imageIndex, setImageIndex] = useState(initialImageIndex)
const [showControls, setShowControls] = useState(true) const [showControls, setShowControls] = useState(true)
const animatedHeaderStyle = useAnimatedStyle(() => ({ const animatedHeaderStyle = useAnimatedStyle(() => ({
pointerEvents: showControls ? 'auto' : 'none', pointerEvents: showControls ? 'box-none' : 'none',
opacity: withClampedSpring(showControls ? 1 : 0), opacity: withClampedSpring(showControls ? 1 : 0),
transform: [ transform: [
{ {
@@ -72,7 +101,8 @@ function ImageViewing({
], ],
})) }))
const animatedFooterStyle = useAnimatedStyle(() => ({ const animatedFooterStyle = useAnimatedStyle(() => ({
pointerEvents: showControls ? 'auto' : 'none', flexGrow: 1,
pointerEvents: showControls ? 'box-none' : 'none',
opacity: withClampedSpring(showControls ? 1 : 0), opacity: withClampedSpring(showControls ? 1 : 0),
transform: [ transform: [
{ {
@@ -92,53 +122,39 @@ function ImageViewing({
} }
}, []) }, [])
const edges = useMemo(() => {
if (Platform.OS === 'android') {
return ['top', 'bottom', 'left', 'right'] satisfies Edge[]
}
return ['left', 'right'] satisfies Edge[] // iOS, so no top/bottom safe area
}, [])
if (!visible) {
return null
}
return ( return (
<SafeAreaView <View style={[styles.container]}>
style={styles.screen} <PagerView
edges={edges} scrollEnabled={!isScaled}
aria-modal initialPage={initialImageIndex}
accessibilityViewIsModal> onPageSelected={e => {
<View style={[styles.container, {backgroundColor}]}> setImageIndex(e.nativeEvent.position)
<Animated.View style={[styles.header, animatedHeaderStyle]}> setIsScaled(false)
}}
onPageScrollStateChanged={e => {
setIsDragging(e.nativeEvent.pageScrollState !== 'idle')
}}
overdrag={true}
style={styles.pager}>
{images.map(imageSrc => (
<View key={imageSrc.uri}>
<ImageItem
onTap={onTap}
onZoom={onZoom}
imageSrc={imageSrc}
onRequestClose={onRequestClose}
isScrollViewBeingDragged={isDragging}
showControls={showControls}
safeAreaRef={safeAreaRef}
/>
</View>
))}
</PagerView>
<View style={styles.controls}>
<Animated.View style={animatedHeaderStyle}>
<ImageDefaultHeader onRequestClose={onRequestClose} /> <ImageDefaultHeader onRequestClose={onRequestClose} />
</Animated.View> </Animated.View>
<PagerView <Animated.View style={animatedFooterStyle}>
scrollEnabled={!isScaled}
initialPage={initialImageIndex}
onPageSelected={e => {
setImageIndex(e.nativeEvent.position)
setIsScaled(false)
}}
onPageScrollStateChanged={e => {
setIsDragging(e.nativeEvent.pageScrollState !== 'idle')
}}
overdrag={true}
style={styles.pager}>
{images.map(imageSrc => (
<View key={imageSrc.uri}>
<ImageItem
onTap={onTap}
onZoom={onZoom}
imageSrc={imageSrc}
onRequestClose={onRequestClose}
isScrollViewBeingDragged={isDragging}
showControls={showControls}
/>
</View>
))}
</PagerView>
<Animated.View style={[styles.footer, animatedFooterStyle]}>
<LightboxFooter <LightboxFooter
images={images} images={images}
index={imageIndex} index={imageIndex}
@@ -147,7 +163,7 @@ function ImageViewing({
/> />
</Animated.View> </Animated.View>
</View> </View>
</SafeAreaView> </View>
) )
} }
@@ -164,17 +180,10 @@ function LightboxFooter({
}) { }) {
const {alt: altText, uri} = images[index] const {alt: altText, uri} = images[index]
const [isAltExpanded, setAltExpanded] = React.useState(false) const [isAltExpanded, setAltExpanded] = React.useState(false)
const insets = useSafeAreaInsets()
const svMaxHeight = SCREEN_HEIGHT - insets.top - 50
const isMomentumScrolling = React.useRef(false) const isMomentumScrolling = React.useRef(false)
return ( return (
<ScrollView <ScrollView
style={[ style={styles.footerScrollView}
{
backgroundColor: '#000d',
},
{maxHeight: svMaxHeight},
]}
scrollEnabled={isAltExpanded} scrollEnabled={isAltExpanded}
onMomentumScrollBegin={() => { onMomentumScrollBegin={() => {
isMomentumScrolling.current = true isMomentumScrolling.current = true
@@ -183,51 +192,52 @@ function LightboxFooter({
isMomentumScrolling.current = false isMomentumScrolling.current = false
}} }}
contentContainerStyle={{ contentContainerStyle={{
paddingTop: 16, paddingVertical: 12,
paddingBottom: insets.bottom + 10,
paddingHorizontal: 24, paddingHorizontal: 24,
}}> }}>
{altText ? ( <SafeAreaView edges={['bottom']}>
<View accessibilityRole="button" style={styles.footerText}> {altText ? (
<Text <View accessibilityRole="button" style={styles.footerText}>
style={[s.gray3]} <Text
numberOfLines={isAltExpanded ? undefined : 3} style={[s.gray3]}
selectable numberOfLines={isAltExpanded ? undefined : 3}
onPress={() => { selectable
if (isMomentumScrolling.current) { onPress={() => {
return if (isMomentumScrolling.current) {
} return
LayoutAnimation.configureNext({ }
duration: 450, LayoutAnimation.configureNext({
update: {type: 'spring', springDamping: 1}, duration: 450,
}) update: {type: 'spring', springDamping: 1},
setAltExpanded(prev => !prev) })
}} setAltExpanded(prev => !prev)
onLongPress={() => {}}> }}
{altText} onLongPress={() => {}}>
</Text> {altText}
</Text>
</View>
) : null}
<View style={styles.footerBtns}>
<Button
type="primary-outline"
style={styles.footerBtn}
onPress={() => onPressSave(uri)}>
<FontAwesomeIcon icon={['far', 'floppy-disk']} style={s.white} />
<Text type="xl" style={s.white}>
<Trans context="action">Save</Trans>
</Text>
</Button>
<Button
type="primary-outline"
style={styles.footerBtn}
onPress={() => onPressShare(uri)}>
<FontAwesomeIcon icon="arrow-up-from-bracket" style={s.white} />
<Text type="xl" style={s.white}>
<Trans context="action">Share</Trans>
</Text>
</Button>
</View> </View>
) : null} </SafeAreaView>
<View style={styles.footerBtns}>
<Button
type="primary-outline"
style={styles.footerBtn}
onPress={() => onPressSave(uri)}>
<FontAwesomeIcon icon={['far', 'floppy-disk']} style={s.white} />
<Text type="xl" style={s.white}>
<Trans context="action">Save</Trans>
</Text>
</Button>
<Button
type="primary-outline"
style={styles.footerBtn}
onPress={() => onPressShare(uri)}>
<FontAwesomeIcon icon="arrow-up-from-bracket" style={s.white} />
<Text type="xl" style={s.white}>
<Trans context="action">Share</Trans>
</Text>
</Button>
</View>
</ScrollView> </ScrollView>
) )
} }
@@ -240,26 +250,47 @@ const styles = StyleSheet.create({
bottom: 0, bottom: 0,
right: 0, right: 0,
}, },
screenHidden: {
opacity: 0,
pointerEvents: 'none',
},
container: { container: {
flex: 1, flex: 1,
backgroundColor: '#000', backgroundColor: '#000',
}, },
controls: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
gap: 20,
zIndex: 1,
pointerEvents: 'box-none',
},
pager: { pager: {
flex: 1, flex: 1,
}, },
header: { header: {
position: 'absolute', position: 'absolute',
width: '100%', width: '100%',
zIndex: 1,
top: 0, top: 0,
pointerEvents: 'box-none', pointerEvents: 'box-none',
}, },
footer: { footer: {
position: 'absolute', position: 'absolute',
width: '100%', width: '100%',
zIndex: 1, maxHeight: '100%',
bottom: 0, bottom: 0,
}, },
footerScrollView: {
backgroundColor: '#000d',
flex: 1,
position: 'absolute',
bottom: 0,
width: '100%',
maxHeight: '100%',
},
footerText: { footerText: {
paddingBottom: isIOS ? 20 : 16, paddingBottom: isIOS ? 20 : 16,
}, },
@@ -277,13 +308,7 @@ const styles = StyleSheet.create({
}, },
}) })
const EnhancedImageViewing = (props: Props) => (
<ImageViewing key={props.initialImageIndex} {...props} />
)
function withClampedSpring(value: any) { function withClampedSpring(value: any) {
'worklet' 'worklet'
return withSpring(value, {overshootClamping: true, stiffness: 300}) return withSpring(value, {overshootClamping: true, stiffness: 300})
} }
export default EnhancedImageViewing
+1 -8
View File
@@ -49,16 +49,9 @@ export function Lightbox() {
[permissionResponse, requestPermission, _], [permissionResponse, requestPermission, _],
) )
if (!activeLightbox) {
return null
}
return ( return (
<ImageView <ImageView
images={activeLightbox.images} lightbox={activeLightbox}
initialImageIndex={activeLightbox.index}
thumbDims={activeLightbox.thumbDims}
visible
onRequestClose={onClose} onRequestClose={onClose}
onPressSave={saveImageToAlbumWithToasts} onPressSave={saveImageToAlbumWithToasts}
onPressShare={uri => shareImageModal({uri})} onPressShare={uri => shareImageModal({uri})}