1
1
import { useContext , useEffect , useState } from "react" ;
2
2
import { PlaygroundContext } from "@/core/context" ;
3
- import { compile } from "./compiler" ;
3
+ import type { CompilerMessageEventData } from "./compiler.worker " ;
4
4
import iframeSource from "./iframe.html?raw" ;
5
5
import { IMPORT_MAP_FILE_NAME } from "@/core/files" ;
6
6
import ErrorAlert from "@/components/error-alert" ;
7
7
import { cn } from "@/lib/utils" ;
8
8
9
+ const compilerWorker = new Worker ( new URL ( "./compiler.worker.ts" , import . meta. url ) , {
10
+ type : "module" ,
11
+ } ) ;
12
+
9
13
function genIframeUrl ( importMap : string , compilerCode : string ) {
10
14
const htmlStr = iframeSource
11
15
. replace (
@@ -36,11 +40,21 @@ export default function RootPreview() {
36
40
37
41
// ============== Compiler ==============
38
42
const [ compiledCode , setCompiledCode ] = useState ( "" ) ;
43
+
39
44
useEffect ( ( ) => {
40
- const res = compile ( files ) ;
41
- setCompiledCode ( res ) ;
45
+ compilerWorker . postMessage ( files ) ;
42
46
} , [ files ] ) ;
43
47
48
+ useEffect ( ( ) => {
49
+ compilerWorker . addEventListener ( "message" , ( ev : MessageEvent < CompilerMessageEventData > ) => {
50
+ if ( ev . data . type === "CODE_COMPILED" ) {
51
+ setCompiledCode ( ev . data . data as string ) ;
52
+ } else if ( ev . data . type === "CODE_COMPILE_ERROR" ) {
53
+ console . error ( ev . data . data ) ;
54
+ }
55
+ } ) ;
56
+ } , [ ] ) ;
57
+
44
58
// ============== Iframe Url ==============
45
59
const [ iframeUrl , setIframeUrl ] = useState ( ( ) => genIframeUrl ( importMapContent , compiledCode ) ) ;
46
60
@@ -52,9 +66,9 @@ export default function RootPreview() {
52
66
// ============== Error Handler ==============
53
67
const [ errMsg , setErrMsg ] = useState < string > ( ) ;
54
68
55
- const handleMessage = ( event : MessageEvent < MessageData > ) => {
56
- if ( event . data . type === "ERROR" ) {
57
- setErrMsg ( event . data . message ) ;
69
+ const handleMessage = ( ev : MessageEvent < MessageData > ) => {
70
+ if ( ev . data . type === "ERROR" ) {
71
+ setErrMsg ( ev . data . message ) ;
58
72
}
59
73
} ;
60
74
0 commit comments