main
js 100 lines 2.44 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @flow
8 */
9
10 import * as React from 'react';
11
12 function deferred<T>(
13 timeoutMS: number,
14 resolvedValue: T,
15 displayName: string,
16 ): Promise<T> {
17 const promise = new Promise<T>(resolve => {
18 setTimeout(() => resolve(resolvedValue), timeoutMS);
19 });
20 (promise as any).displayName = displayName;
21
22 return promise;
23 }
24
25 const title = deferred(100, 'Segmented Page Title', 'title');
26 const content = deferred(
27 400,
28 'This is the content of a segmented page. It loads in multiple parts.',
29 'content',
30 );
31 function Page(): React.Node {
32 return (
33 <article>
34 <h1>{title}</h1>
35 <p>{content}</p>
36 </article>
37 );
38 }
39
40 function InnerSegment({children}: {children: React.Node}): React.Node {
41 return (
42 <>
43 <h3>Inner Segment</h3>
44 <React.Suspense name="InnerSegment" fallback={<p>Loading...</p>}>
45 <section>{children}</section>
46 <p>After inner</p>
47 </React.Suspense>
48 </>
49 );
50 }
51
52 const cookies = deferred(200, 'Cookies: 🍪🍪🍪', 'cookies');
53 function OuterSegment({children}: {children: React.Node}): React.Node {
54 return (
55 <>
56 <h2>Outer Segment</h2>
57 <React.Suspense name="OuterSegment" fallback={<p>Loading outer</p>}>
58 <p>{cookies}</p>
59 <div>{children}</div>
60 <p>After outer</p>
61 </React.Suspense>
62 </>
63 );
64 }
65
66 function Root({children}: {children: React.Node}): React.Node {
67 return (
68 <>
69 <h1>Root Segment</h1>
70 <React.Suspense name="Root" fallback={<p>Loading root</p>}>
71 <main>{children}</main>
72 <footer>After root</footer>
73 </React.Suspense>
74 </>
75 );
76 }
77
78 const dynamicData = deferred(10, 'Dynamic Data: 📈📉📊', 'dynamicData');
79 export default function Segments(): React.Node {
80 return (
81 <>
82 <p>{dynamicData}</p>
83 <React.Activity name="root" mode="visible">
84 <Root>
85 <React.Activity name="outer" mode="visible">
86 <OuterSegment>
87 <React.Activity name="inner" mode="visible">
88 <InnerSegment>
89 <React.Activity name="slot" mode="visible">
90 <Page />
91 </React.Activity>
92 </InnerSegment>
93 </React.Activity>
94 </OuterSegment>
95 </React.Activity>
96 </Root>
97 </React.Activity>
98 </>
99 );
100 }