11import { afterNavigate , beforeNavigate } from '$app/navigation' ;
2- import { getTransitionContext } from '$lib/utils/resource-context' ;
2+ import { setContext , getContext , hasContext } from 'svelte' ;
3+ import { writable } from 'svelte/store' ;
4+
5+ const contextKey = 'transition' ;
6+
7+ export function initTransitionContext ( ) {
8+ if ( hasContext ( contextKey ) ) return getContext ( contextKey ) ;
9+ return setContext ( contextKey , writable ( { } ) ) ;
10+ }
11+
12+ export function getTransitionContext ( ) {
13+ if ( ! hasContext ( contextKey ) ) {
14+ return initTransitionContext ( ) ;
15+ }
16+ return getContext ( contextKey ) ;
17+ }
318
419// Call this hook on this first page before you start the page transition.
520// For Shared Element Transitions, you need to call the transition.start()
@@ -11,9 +26,16 @@ export const preparePageTransition = () => {
1126 const transitionStore = getTransitionContext ( ) ;
1227 let unsub ;
1328
29+ function updateStore ( key , value ) {
30+ transitionStore . update ( ( current ) => ( {
31+ ...current ,
32+ [ key ] : value
33+ } ) ) ;
34+ }
35+
1436 // before navigating, start a new transition
1537 beforeNavigate ( ( { to } ) => {
16- unsub ?. ( ) ;
38+ unsub ?. ( ) ; // clean up previous subscription
1739
1840 // Feature detection
1941 if ( ! document . createDocumentTransition ) {
@@ -23,16 +45,11 @@ export const preparePageTransition = () => {
2345 const transitionKey = to . pathname ;
2446 const transition = document . createDocumentTransition ( ) ;
2547 transition . start ( async ( ) => {
48+ // set transition data for afterNavigate hook to pick up
2649 await new Promise ( ( resolver ) => {
27- transitionStore . update ( ( current ) => ( {
28- ...current ,
29- [ transitionKey ] : { transition, resolver }
30- } ) ) ;
50+ updateStore ( transitionKey , { transition, resolver } ) ;
3151 } ) ;
32- transitionStore . update ( ( current ) => ( {
33- ...current ,
34- [ transitionKey ] : null
35- } ) ) ;
52+ updateStore ( transitionKey , null ) ;
3653 } ) ;
3754 } ) ;
3855
0 commit comments