@@ -29,11 +29,9 @@ function ErrorFallback({ error }) {
29
29
) ;
30
30
}
31
31
32
- function InnerPreview ( { input, standalone, refreshKey } ) {
33
- const [ Content , setContent ] = useState ( undefined ) ;
34
- const [ error , setError ] = useState ( undefined ) ;
35
- useEffect ( ( ) => {
36
- compile ( input . mdx , {
32
+ async function compileAndRun ( input ) {
33
+ try {
34
+ const c = await compile ( input . mdx , {
37
35
outputFormat : "function-body" ,
38
36
remarkPlugins : [
39
37
[
@@ -45,19 +43,49 @@ function InnerPreview({ input, standalone, refreshKey }) {
45
43
} ,
46
44
] ,
47
45
] ,
48
- } )
49
- . then ( ( c ) => {
50
- return run ( String ( c ) , runtime ) ;
51
- } )
52
- . then ( ( x ) => {
53
- setContent ( ( ) => x . default ) ;
54
- setError ( undefined ) ;
55
- } )
56
- . catch ( ( e ) => {
57
- setError ( e . message ) ;
58
- console . error ( { e } ) ;
59
- } ) ;
46
+ } ) ;
47
+ const x = await run ( String ( c ) , runtime ) ;
48
+ return { content : x . default , error : undefined } ;
49
+ } catch ( e ) {
50
+ return { content : undefined , error : e . message } ;
51
+ }
52
+ }
53
+
54
+ let effectId = 0 ;
55
+
56
+ function useInput ( input ) {
57
+ const [ { Content, error } , setState ] = useState ( {
58
+ Content : undefined ,
59
+ error : undefined ,
60
+ } ) ;
61
+ const [ loading , setLoading ] = useState ( true ) ;
62
+ useEffect ( ( ) => {
63
+ const id = effectId ;
64
+ // console.log("compiling...", id);
65
+ setLoading ( true ) ;
66
+ compileAndRun ( input ) . then ( ( { content, error } ) => {
67
+ // console.log("compiled", id, error);
68
+ if ( id !== effectId ) {
69
+ // console.log("skipping", id);
70
+ return ;
71
+ }
72
+ setState ( ( state ) => ( {
73
+ Content : content || state . Content ,
74
+ error,
75
+ } ) ) ;
76
+ setLoading ( false ) ;
77
+ } ) ;
78
+ return ( ) => {
79
+ // console.log("cancelling", id);
80
+ effectId ++ ;
81
+ } ;
60
82
} , [ input . mdx , input . css , input . config ] ) ;
83
+
84
+ return { Content, error, loading } ;
85
+ }
86
+
87
+ function InnerPreview ( { input, standalone, refreshKey } ) {
88
+ const { Content, error, loading } = useInput ( input ) ;
61
89
// console.log(error);
62
90
return (
63
91
< >
@@ -78,6 +106,7 @@ function InnerPreview({ input, standalone, refreshKey }) {
78
106
</ a >
79
107
) }
80
108
< div className = { `preview-container ${ error ? "with-error" : "" } ` } >
109
+ < div style = { { opacity : loading ? 1 : 0 } } className = "loading-border" />
81
110
{ Content ? < Content components = { { CH } } key = { refreshKey } /> : null }
82
111
</ div >
83
112
</ >
0 commit comments