@@ -29,11 +29,9 @@ function ErrorFallback({ error }) {
2929 ) ;
3030}
3131
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 , {
3735 outputFormat : "function-body" ,
3836 remarkPlugins : [
3937 [
@@ -45,19 +43,49 @@ function InnerPreview({ input, standalone, refreshKey }) {
4543 } ,
4644 ] ,
4745 ] ,
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+ } ;
6082 } , [ 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 ) ;
6189 // console.log(error);
6290 return (
6391 < >
@@ -78,6 +106,7 @@ function InnerPreview({ input, standalone, refreshKey }) {
78106 </ a >
79107 ) }
80108 < div className = { `preview-container ${ error ? "with-error" : "" } ` } >
109+ < div style = { { opacity : loading ? 1 : 0 } } className = "loading-border" />
81110 { Content ? < Content components = { { CH } } key = { refreshKey } /> : null }
82111 </ div >
83112 </ >
0 commit comments