1
- import React , { useEffect , useMemo , useState } from "react" ;
1
+ import React , { useEffect , useState } from "react" ;
2
2
3
3
import createRuby , { Ruby } from "./createRuby" ;
4
4
5
+ // Create a singleton since we don't actually want there to be multiple virtual
6
+ // machines running even if there are multiple Tree components.
7
+ let ruby : Ruby = {
8
+ prettyPrint ( source ) {
9
+ return "Loading..." ;
10
+ }
11
+ } ;
12
+
13
+ // Track a state that represents where the ruby constant is at any given time.
14
+ let rubyState : "initial" | "creating" | "ready" = "initial" ;
15
+
5
16
function prettyPrint ( ruby : Ruby , value : string ) {
6
17
try {
7
18
return ruby . prettyPrint ( value ) ;
@@ -17,23 +28,36 @@ type TreeProps = {
17
28
} ;
18
29
19
30
const Tree : React . FC < TreeProps > = ( { cols, value } ) => {
20
- const [ ruby , setRuby ] = useState < Ruby > ( null ) ;
21
- const [ output , setOutput ] = useState < string > ( "" ) ;
31
+ const [ output , setOutput ] = useState < string > ( ( ) => prettyPrint ( ruby , value ) ) ;
22
32
23
33
useEffect ( ( ) => {
24
- createRuby ( ) . then ( ( ruby ) => {
25
- setRuby ( ruby ) ;
26
- setOutput ( prettyPrint ( ruby , value ) ) ;
27
- } ) ;
28
- } , [ ] ) ;
29
-
30
- useMemo ( ( ) => {
31
- if ( ruby ) {
32
- setOutput ( prettyPrint ( ruby , value ) ) ;
34
+ switch ( rubyState ) {
35
+ case "initial" :
36
+ rubyState = "creating" ;
37
+
38
+ createRuby ( ) . then ( ( newRuby ) => {
39
+ ruby = newRuby ;
40
+ rubyState = "ready" ;
41
+ setOutput ( prettyPrint ( ruby , value ) ) ;
42
+ } ) ;
43
+
44
+ break ;
45
+ case "creating" :
46
+ break ;
47
+ case "ready" :
48
+ setOutput ( prettyPrint ( ruby , value ) ) ;
49
+ break ;
33
50
}
34
- } , [ ruby , value ] ) ;
35
-
36
- return < textarea cols = { cols } value = { output } readOnly /> ;
51
+ } , [ value ] ) ;
52
+
53
+ return (
54
+ < textarea
55
+ className = { rubyState != "ready" ? "loading" : "" }
56
+ cols = { cols }
57
+ value = { output }
58
+ readOnly
59
+ />
60
+ ) ;
37
61
} ;
38
62
39
63
export default Tree ;
0 commit comments