|
1 | | -import React from 'react'; |
| 1 | +import React, { |
| 2 | + startTransition, |
| 3 | + useInsertionEffect, |
| 4 | + useEffect, |
| 5 | + useState, |
| 6 | +} from 'react'; |
2 | 7 |
|
3 | 8 | import Chrome from './Chrome'; |
4 | 9 | import Page from './Page'; |
5 | 10 |
|
6 | | -export default function App({assets}) { |
| 11 | +const enableNavigationAPI = typeof navigation === 'object'; |
| 12 | + |
| 13 | +export default function App({assets, initialURL}) { |
| 14 | + const [routerState, setRouterState] = useState({ |
| 15 | + pendingNav: () => {}, |
| 16 | + url: initialURL, |
| 17 | + }); |
| 18 | + function navigate(url) { |
| 19 | + if (enableNavigationAPI) { |
| 20 | + window.navigation.navigate(url); |
| 21 | + } else { |
| 22 | + startTransition(() => { |
| 23 | + setRouterState({ |
| 24 | + url, |
| 25 | + pendingNav() { |
| 26 | + window.history.pushState({}, '', url); |
| 27 | + }, |
| 28 | + }); |
| 29 | + }); |
| 30 | + } |
| 31 | + } |
| 32 | + useEffect(() => { |
| 33 | + if (enableNavigationAPI) { |
| 34 | + window.navigation.addEventListener('navigate', event => { |
| 35 | + if (!event.canIntercept) { |
| 36 | + return; |
| 37 | + } |
| 38 | + const newURL = new URL(event.destination.url); |
| 39 | + event.intercept({ |
| 40 | + handler() { |
| 41 | + let promise; |
| 42 | + startTransition(() => { |
| 43 | + promise = new Promise(resolve => { |
| 44 | + setRouterState({ |
| 45 | + url: newURL.pathname + newURL.search, |
| 46 | + pendingNav: resolve, |
| 47 | + }); |
| 48 | + }); |
| 49 | + }); |
| 50 | + return promise; |
| 51 | + }, |
| 52 | + commit: 'after-transition', // plz ship this, browsers |
| 53 | + }); |
| 54 | + }); |
| 55 | + } else { |
| 56 | + window.addEventListener('popstate', () => { |
| 57 | + // This should not animate because restoration has to be synchronous. |
| 58 | + // Even though it's a transition. |
| 59 | + startTransition(() => { |
| 60 | + setRouterState({ |
| 61 | + url: document.location.pathname + document.location.search, |
| 62 | + pendingNav() { |
| 63 | + // Noop. URL has already updated. |
| 64 | + }, |
| 65 | + }); |
| 66 | + }); |
| 67 | + }); |
| 68 | + } |
| 69 | + }, []); |
| 70 | + const pendingNav = routerState.pendingNav; |
| 71 | + useInsertionEffect(() => { |
| 72 | + pendingNav(); |
| 73 | + }, [pendingNav]); |
7 | 74 | return ( |
8 | 75 | <Chrome title="Hello World" assets={assets}> |
9 | | - <Page /> |
| 76 | + <Page url={routerState.url} navigate={navigate} /> |
10 | 77 | </Chrome> |
11 | 78 | ); |
12 | 79 | } |
0 commit comments