|
6 | 6 | getContext,
|
7 | 7 | getElement,
|
8 | 8 | withSyncEvent,
|
| 9 | + withScope, |
9 | 10 | } from '@wordpress/interactivity';
|
10 | 11 |
|
11 | 12 | /**
|
@@ -50,6 +51,7 @@ const { state, actions, callbacks } = store(
|
50 | 51 | {
|
51 | 52 | state: {
|
52 | 53 | currentImageId: null,
|
| 54 | + prefetchTimers: {}, |
53 | 55 | get currentImage() {
|
54 | 56 | return state.metadata[ state.currentImageId ];
|
55 | 57 | },
|
@@ -212,20 +214,43 @@ const { state, actions, callbacks } = store(
|
212 | 214 | }
|
213 | 215 | },
|
214 | 216 | prefetchImage() {
|
215 |
| - const ctx = getContext(); |
216 |
| - if ( ! isValidLink( ctx.uploadedSrc ) ) { |
| 217 | + const { imageId } = getContext(); |
| 218 | + const uploadedSrc = state.metadata[ imageId ].uploadedSrc; |
| 219 | + |
| 220 | + if ( ! isValidLink( uploadedSrc ) ) { |
217 | 221 | return;
|
218 | 222 | }
|
219 | 223 |
|
220 |
| - // Creates a link element to prefetch the image. |
221 | 224 | const imageLink = document.createElement( 'link' );
|
222 | 225 | imageLink.rel = 'prefetch';
|
223 | 226 | imageLink.as = 'image';
|
224 |
| - imageLink.href = ctx.uploadedSrc; |
| 227 | + imageLink.href = uploadedSrc; |
225 | 228 |
|
226 |
| - // Appends the link element to the head of the document to start the prefetch. |
| 229 | + // Appends the link element to start the prefetch. |
227 | 230 | document.head.appendChild( imageLink );
|
228 | 231 | },
|
| 232 | + prefetchImageWithDelay() { |
| 233 | + const { imageId } = getContext(); |
| 234 | + |
| 235 | + if ( state.prefetchTimers && state.prefetchTimers[ imageId ] ) { |
| 236 | + clearTimeout( state.prefetchTimers[ imageId ] ); |
| 237 | + } |
| 238 | + |
| 239 | + state.prefetchTimers[ imageId ] = setTimeout( |
| 240 | + withScope( () => { |
| 241 | + actions.prefetchImage(); |
| 242 | + delete state.prefetchTimers[ imageId ]; |
| 243 | + } ), |
| 244 | + 200 |
| 245 | + ); |
| 246 | + }, |
| 247 | + cancelPrefetch() { |
| 248 | + const { imageId } = getContext(); |
| 249 | + if ( state.prefetchTimers && state.prefetchTimers[ imageId ] ) { |
| 250 | + clearTimeout( state.prefetchTimers[ imageId ] ); |
| 251 | + delete state.prefetchTimers[ imageId ]; |
| 252 | + } |
| 253 | + }, |
229 | 254 | },
|
230 | 255 | callbacks: {
|
231 | 256 | setOverlayStyles() {
|
|
0 commit comments