@@ -41,13 +41,12 @@ export function useImageLightbox<P extends Partial<ImageLightboxProps>>(
41
41
const propsRef = React . useRef ( props ) ;
42
42
43
43
React . useEffect ( ( ) => {
44
- const newProps = { ...props } ;
45
- if ( newProps ?. images ) {
46
- newProps . images = newProps . images . map ( ( image ) => ( { imgRef : React . createRef ( ) , ...image } ) ) ;
47
- }
48
- propsRef . current = newProps ;
44
+ propsRef . current = props ;
49
45
} , [ props ] ) ;
50
46
47
+ // Keep reference for each image elements
48
+ const imageRefsRef = React . useRef < Array < React . RefObject < HTMLImageElement > > > ( [ ] ) ;
49
+
51
50
const currentImageRef = React . useRef < HTMLImageElement > ( null ) ;
52
51
const [ imageLightboxProps , setImageLightboxProps ] = React . useState (
53
52
( ) => ( { ...EMPTY_PROPS , ...props } ) as ManagedProps & P ,
@@ -61,8 +60,8 @@ export function useImageLightbox<P extends Partial<ImageLightboxProps>>(
61
60
if ( ! currentImage ) {
62
61
return ;
63
62
}
64
- const currentIndex = propsRef . current ?. images ? .findIndex (
65
- ( { imgRef } ) => ( imgRef as any ) ? .current === currentImage ,
63
+ const currentIndex = imageRefsRef . current . findIndex (
64
+ ( imageRef ) => imageRef . current === currentImage ,
66
65
) as number ;
67
66
68
67
await startViewTransition ( {
@@ -83,12 +82,20 @@ export function useImageLightbox<P extends Partial<ImageLightboxProps>>(
83
82
// If we find an image inside the trigger, animate it in transition with the opening image
84
83
const triggerImage = triggerImageRefs [ activeImageIndex as any ] ?. current || findImage ( triggerElement ) ;
85
84
86
- // Inject the trigger image as loading placeholder for better loading state
87
- const imagesWithFallbackSize = propsRef . current ?. images ?. map ( ( image , idx ) => {
88
- if ( triggerImage && idx === activeImageIndex && ! image . loadingPlaceholderImageRef ) {
89
- return { ...image , loadingPlaceholderImageRef : { current : triggerImage } } ;
85
+ // Inject refs to improve transition and loading style
86
+ const images = propsRef . current ?. images ?. map ( ( image , idx ) => {
87
+ // Get or create image reference
88
+ let imgRef = imageRefsRef . current [ idx ] ;
89
+ if ( ! imgRef ) {
90
+ imgRef = React . createRef ( ) ;
91
+ imageRefsRef . current [ idx ] = imgRef ;
90
92
}
91
- return image ;
93
+
94
+ // Try to use the trigger image as the loading placeholder
95
+ const loadingPlaceholderImageRef =
96
+ triggerImage && idx === activeImageIndex ? { current : triggerImage } : undefined ;
97
+
98
+ return { loadingPlaceholderImageRef, ...image , imgRef } ;
92
99
} ) ;
93
100
94
101
await startViewTransition ( {
@@ -104,7 +111,7 @@ export function useImageLightbox<P extends Partial<ImageLightboxProps>>(
104
111
close ( ) ;
105
112
prevProps ?. onClose ?.( ) ;
106
113
} ,
107
- images : imagesWithFallbackSize ,
114
+ images,
108
115
activeImageIndex : activeImageIndex || 0 ,
109
116
} ) ) ;
110
117
} ,
0 commit comments