-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathindex.js
More file actions
100 lines (89 loc) · 2.16 KB
/
Copy pathindex.js
File metadata and controls
100 lines (89 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import {
Suspense,
createElement as h,
startTransition,
use,
useDeferredValue,
useRef,
useState,
useTransition,
} from 'react'
import { createRoot } from 'react-dom/client'
import * as RSC from 'react-server-dom-esm/client'
import { ErrorBoundary } from './error-boundary.js'
import { shipFallbackSrc } from './img-utils.js'
import { RouterContext, getGlobalLocation, useLinkHandler } from './router.js'
function fetchContent(location) {
return fetch(`/rsc${location}`)
}
function createFromFetch(fetchPromise) {
return RSC.createFromFetch(fetchPromise, {
moduleBaseURL: `${window.location.origin}/ui`,
})
}
const initialLocation = getGlobalLocation()
const initialContentPromise = createFromFetch(fetchContent(initialLocation))
function Root() {
const latestNav = useRef(null)
const [nextLocation, setNextLocation] = useState(getGlobalLocation)
const [contentPromise, setContentPromise] = useState(initialContentPromise)
const [, startTransition] = useTransition()
const location = useDeferredValue(nextLocation)
function navigate(nextLocation, { replace = false } = {}) {
setNextLocation(nextLocation)
const thisNav = Symbol(`Nav for ${nextLocation}`)
latestNav.current = thisNav
const nextContentPromise = createFromFetch(
fetchContent(nextLocation).then((response) => {
if (thisNav !== latestNav.current) return
if (replace) {
window.history.replaceState({}, '', nextLocation)
} else {
window.history.pushState({}, '', nextLocation)
}
return response
}),
)
startTransition(() => setContentPromise(nextContentPromise))
}
useLinkHandler(navigate)
return h(
RouterContext,
{
value: {
navigate,
location,
nextLocation,
},
},
use(contentPromise),
)
}
startTransition(() => {
createRoot(document.getElementById('root')).render(
h(
'div',
{ className: 'app-wrapper' },
h(
ErrorBoundary,
{
fallback: h(
'div',
{ className: 'app-error' },
h('p', null, 'Something went wrong!'),
),
},
h(
Suspense,
{
fallback: h('img', {
style: { maxWidth: 400 },
src: shipFallbackSrc,
}),
},
h(Root),
),
),
),
)
})